Files
codiki-hexagonal/frontend/src/app/pages/login/login.service.ts
2026-02-03 11:00:29 +01:00

84 lines
2.4 KiB
TypeScript

import {inject, Injectable} from '@angular/core';
import {BehaviorSubject, Observable} from 'rxjs';
import {copy} from '../../core/utils/ObjectUtils';
import {FormError} from '../../core/model/FormError';
import {UserRestService} from '../../core/rest-services/user/user.rest-service';
import {LoginRequest} from '../../core/rest-services/user/model/login.model';
import {AuthenticationService} from '../../core/service/authentication.service';
import {MatSnackBar} from '@angular/material/snack-bar';
import {Router} from '@angular/router';
export interface LoginState {
request: LoginRequest;
errors: FormError[];
}
const DEFAULT_STATE: LoginState = {
request: {
email: undefined,
password: undefined,
},
errors: [],
};
@Injectable()
export class LoginService {
private stateSubject = new BehaviorSubject<LoginState>(copy(DEFAULT_STATE));
private userRestService = inject(UserRestService);
private authenticationService = inject(AuthenticationService);
private snackBar = inject(MatSnackBar);
private router = inject(Router);
get state$(): Observable<LoginState> {
return this.stateSubject.asObservable();
}
private get state(): LoginState {
return this.stateSubject.value;
}
private save(newState: LoginState): void {
this.stateSubject.next(newState);
}
editEmail(newEmail: string): void {
const state = this.state;
state.request.email = newEmail;
this.save(state);
}
editPassword(newPassword: string): void {
const state = this.state;
state.request.password = newPassword;
this.save(state);
}
performLogin(): void {
const state = this.state;
if (this.isStateValid(state)) {
this.userRestService
.login(state.request)
.then((response) => {
this.authenticationService.authenticate(response.accessToken, response.refreshToken);
this.snackBar.open($localize`Authentication succeeded!`, $localize`Close`, {duration: 5000});
this.router.navigate(['/home']);
})
.catch((error) => {
console.error(error);
this.snackBar.open($localize`Authentication failed.`, $localize`Close`, {duration: 5000});
});
} else {
this.snackBar.open($localize`Please, fill the inputs before send.`, $localize`Close`, {duration: 5000});
}
}
isStateValid(state: LoginState): boolean {
return !!state.request.email?.trim().length && !!state.request.password?.length;
}
}