103 lines
2.6 KiB
TypeScript
103 lines
2.6 KiB
TypeScript
import {inject, Injectable} from '@angular/core';
|
|
import {SigninRequest} from '../../core/rest-services/user/model/signin.model';
|
|
import {FormError} from '../../core/model/FormError';
|
|
import {BehaviorSubject, Observable} from 'rxjs';
|
|
import {copy} from '../../core/utils/ObjectUtils';
|
|
import {UserRestService} from '../../core/rest-services/user/user.rest-service';
|
|
import {MatSnackBar} from '@angular/material/snack-bar';
|
|
import {Router} from '@angular/router';
|
|
import {LoginService} from '../login/login.service';
|
|
|
|
export interface SigninState {
|
|
request: SigninRequest;
|
|
confirmPassword?: string;
|
|
errors: FormError[];
|
|
}
|
|
|
|
const DEFAULT_STATE: SigninState = {
|
|
request: {
|
|
pseudo: undefined,
|
|
email: undefined,
|
|
password: undefined,
|
|
},
|
|
confirmPassword: undefined,
|
|
errors: [],
|
|
};
|
|
|
|
@Injectable()
|
|
export class SigninService {
|
|
private stateSubject = new BehaviorSubject<SigninState>(copy(DEFAULT_STATE));
|
|
private userRestService = inject(UserRestService);
|
|
private snackBar = inject(MatSnackBar);
|
|
private router = inject(Router);
|
|
private loginService = inject(LoginService);
|
|
|
|
get state$(): Observable<SigninState> {
|
|
return this.stateSubject.asObservable();
|
|
}
|
|
|
|
private get state(): SigninState {
|
|
return this.stateSubject.value;
|
|
}
|
|
|
|
private save(newState: SigninState): void {
|
|
this.stateSubject.next(newState);
|
|
}
|
|
|
|
editPseudo(newPseudo: string): void {
|
|
const state = this.state;
|
|
|
|
state.request.pseudo = newPseudo;
|
|
|
|
this.save(state);
|
|
}
|
|
|
|
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);
|
|
}
|
|
|
|
editConfirmPassword(newConfirmPassword: string): void {
|
|
const state = this.state;
|
|
|
|
state.confirmPassword = newConfirmPassword;
|
|
|
|
if (state.request.password !== state.confirmPassword) {
|
|
const confirmPasswordError: FormError = {
|
|
fieldName: 'confirmPassword',
|
|
errorMessage: $localize`Typed passwords are different.`
|
|
}
|
|
state.errors.filter(error => error.fieldName !== 'confirmPassword');
|
|
state.errors.push(confirmPasswordError)
|
|
}
|
|
|
|
this.save(state);
|
|
}
|
|
|
|
performSignin(): void {
|
|
const state = this.state;
|
|
|
|
// Check state is valid
|
|
|
|
this.userRestService
|
|
.signin(state.request)
|
|
.then(() => {
|
|
this.loginService.editEmail(state.request.email!!);
|
|
this.loginService.editPassword(state.request.password!!);
|
|
|
|
this.loginService.performLogin();
|
|
})
|
|
}
|
|
}
|