Files
codiki-hexagonal/frontend/src/app/pages/login/login.service.ts
2024-09-21 11:22:35 +02:00

78 lines
2.1 KiB
TypeScript

import { Injectable, inject } 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;
// Check state is valid
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 });
});
}
}