review-front/src/app/login/login.component.ts
2024-12-21 13:46:22 +01:00

85 lines
2.4 KiB
TypeScript

import {Component, CUSTOM_ELEMENTS_SCHEMA, OnDestroy} from '@angular/core';
import {FormsModule} from '@angular/forms';
import {InputTextModule} from 'primeng/inputtext';
import {Button} from 'primeng/button';
import {AuthorService} from '../services/author.service';
import {ToastModule} from 'primeng/toast';
import {MessageService} from 'primeng/api';
import {Author} from '../model/author';
import {Subscription, switchMap} from 'rxjs';
import {JsonPipe} from '@angular/common';
import { CookieService } from 'ngx-cookie-service';
import {HeaderComponent} from '../header/header.component';
import {Router} from '@angular/router';
@Component({
selector: 'app-login',
standalone: true,
imports: [
FormsModule,
InputTextModule,
Button,
ToastModule,
JsonPipe,
HeaderComponent
],
templateUrl: './login.component.html',
styleUrl: './login.component.css',
providers: [
MessageService,
]
})
export class LoginComponent implements OnDestroy {
name: string = "";
actualAuthor: Author | undefined;
password: string = "";
confirmPassword: string = "";
subs: Subscription[] = [];
constructor(private authorService: AuthorService,
private messageService: MessageService,
private cookieService: CookieService,
private router: Router) {}
sendLogins(): void {
if (this.password === this.confirmPassword) {
this.subs.push
(
this.authorService.login(this.name, this.password).pipe(
switchMap((tokenObj: any) => this.authorService.me(tokenObj.token)))
.subscribe({
next: (author: Author) => {
this.cookieService.set("author", JSON.stringify(author));
this.cookieService.set("just-authenticated", "true");
this.getAuthorCookie();
this.router.navigate(['/']);
},
error: (err) => this.failureMessage('Erreur de connexion', err.message)
})
);
} else {
this.failureMessage('Erreur de connexion', 'Les deux mots de passe ne correspondent pas')
}
}
getAuthorCookie(): void {
this.actualAuthor = JSON.parse(this.cookieService.get("author"));
}
failureMessage(summary: string, detail: string): void {
this.messageService.add({
severity: 'error',
summary: summary,
detail: detail,
life: 1500,
closable: false
});
}
ngOnDestroy(): void {
this.subs.forEach(sub => sub.unsubscribe());
}
}