Gestion des cookies et token d'authentification

This commit is contained in:
Guams 2025-01-29 21:27:46 +01:00
parent 4990bd9db7
commit 63b553d31c
30 changed files with 226 additions and 14371 deletions

View File

@ -1,4 +1,5 @@
{ {
"serverAddress": "localhost", "serverAddress": "localhost",
"apiURL": "http://localhost:8080/api" "apiURL": "http://localhost:8080/api",
"tokenTTL": 36000000
} }

14272
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@ -39,6 +39,7 @@
"@types/express": "^4.17.17", "@types/express": "^4.17.17",
"@types/jasmine": "~5.1.0", "@types/jasmine": "~5.1.0",
"@types/jwt-decode": "^3.1.0", "@types/jwt-decode": "^3.1.0",
"@types/luxon": "^3.4.2",
"@types/node": "^18.18.0", "@types/node": "^18.18.0",
"jasmine-core": "~5.2.0", "jasmine-core": "~5.2.0",
"karma": "~6.4.0", "karma": "~6.4.0",

View File

@ -0,0 +1,5 @@
.expired-dialog {
margin-top: 2rem;
display: flex;
justify-content: space-around;
}

View File

@ -1,2 +1,10 @@
<router-outlet></router-outlet> <router-outlet></router-outlet>
@if (isBrowser()) {
<p-dialog header="ATTENTION !" [modal]="true" [closable]="false" [visible]="isSessionExpired">
<span>Votre session a <strong>expiré</strong> ! Il va falloir se reconnecter.</span>
<div class="expired-dialog">
<p-button severity="info" icon="pi pi-sign-out" label="OK, je me déconnecte" (onClick)="setSessionExpiredFalse()" routerLink="/logout"></p-button>
</div>
</p-dialog>
}
<p-toast></p-toast> <p-toast></p-toast>

View File

@ -1,22 +1,44 @@
import {Component} from '@angular/core'; import {Component, Inject, OnInit, PLATFORM_ID} from '@angular/core';
import {MenubarModule} from 'primeng/menubar'; import {MenubarModule} from 'primeng/menubar';
import {MenuItem, MessageService} from 'primeng/api'; import {MessageService} from 'primeng/api';
import {FloatLabelModule} from 'primeng/floatlabel'; import {FloatLabelModule} from 'primeng/floatlabel';
import {CookieService} from 'ngx-cookie-service';
import {ToastModule} from 'primeng/toast'; import {ToastModule} from 'primeng/toast';
import {DialogModule} from 'primeng/dialog';
import {isPlatformBrowser} from '@angular/common';
import {Button} from 'primeng/button';
import {AuthService} from './auth.service';
import {CookieService} from 'ngx-cookie-service';
@Component({ @Component({
selector: 'app-root', selector: 'app-root',
standalone: true, standalone: true,
imports: [MenubarModule, FloatLabelModule, ToastModule], imports: [MenubarModule, FloatLabelModule, ToastModule, DialogModule, Button],
providers: [ providers: [
MessageService, MessageService,
], ],
templateUrl: './app.component.html', templateUrl: './app.component.html',
styleUrl: './app.component.css' styleUrl: './app.component.css'
}) })
export class AppComponent{ export class AppComponent implements OnInit {
isSessionExpired: boolean = false;
constructor() { constructor(@Inject(PLATFORM_ID) private platformId: object,
private authService: AuthService,
private cookieService: CookieService) {
}
isBrowser(): boolean {
return isPlatformBrowser(this.platformId);
}
setSessionExpiredFalse(): void {
this.isSessionExpired = false;
this.authService.setSessionExpired(false);
}
ngOnInit(): void {
this.authService.sessionExpired$.subscribe(expired => {
this.isSessionExpired = expired;
});
} }
} }

View File

@ -1,7 +1,6 @@
import {Routes} from '@angular/router'; import {Routes} from '@angular/router';
import {LoginComponent} from './pages/login/login.component'; import {LoginComponent} from './pages/login/login.component';
import {HomeComponent} from './pages/home/home.component'; import {HomeComponent} from './pages/home/home.component';
import {RegisterFormComponent} from './components/register-form/register-form.component';
import {LogoutComponent} from './pages/logout/logout.component'; import {LogoutComponent} from './pages/logout/logout.component';
import {NotFoundComponent} from './pages/not-found/not-found.component'; import {NotFoundComponent} from './pages/not-found/not-found.component';
import {authGuard} from './guards/auth.guard'; import {authGuard} from './guards/auth.guard';
@ -11,6 +10,9 @@ import {writerGuard} from './guards/writer.guard';
import {PostComponent} from './pages/post/post.component'; import {PostComponent} from './pages/post/post.component';
import {MyPostsComponent} from './pages/my-posts/my-posts.component'; import {MyPostsComponent} from './pages/my-posts/my-posts.component';
import {RegisterComponent} from './pages/register/register.component'; import {RegisterComponent} from './pages/register/register.component';
import {AdminPostsComponent} from './pages/admin-posts/admin-posts.component';
import {adminGuard} from './guards/admin.guard';
import {AdminAuthorsComponent} from './pages/admin-authors/admin-authors.component';
export const routes: Routes = [ export const routes: Routes = [
{path: '', component: HomeComponent}, {path: '', component: HomeComponent},
@ -21,5 +23,7 @@ export const routes: Routes = [
{path: 'post/:postId', component: PostComponent}, {path: 'post/:postId', component: PostComponent},
{path: 'my-posts', component: MyPostsComponent, canActivate: [writerGuard]}, {path: 'my-posts', component: MyPostsComponent, canActivate: [writerGuard]},
{path: 'new-post', component: NewPostComponent, canActivate: [writerGuard]}, {path: 'new-post', component: NewPostComponent, canActivate: [writerGuard]},
{path: 'admin/posts', component: AdminPostsComponent, canActivate: [adminGuard]},
{path: 'admin/authors', component: AdminAuthorsComponent, canActivate: [adminGuard]},
{path: '**', component: NotFoundComponent} {path: '**', component: NotFoundComponent}
]; ];

52
src/app/auth.service.ts Normal file
View File

@ -0,0 +1,52 @@
import { Injectable } from '@angular/core';
import { CookieService } from 'ngx-cookie-service';
import { Author } from './models/author';
import { BehaviorSubject } from 'rxjs';
import {DateTime} from 'luxon';
@Injectable({
providedIn: 'root'
})
export class AuthService {
private sessionExpiredSubject = new BehaviorSubject<boolean>(false);
sessionExpired$ = this.sessionExpiredSubject.asObservable();
constructor(private cookieService: CookieService) {
this.checkSessionExpiration();
}
isAuthenticated(): boolean {
return this.cookieService.check("author") &&
this.cookieService.check("token") &&
this.cookieService.check("token-expiration-date") &&
this.cookieService.get("author") !== '' &&
this.cookieService.get("token-expiration-date") !== '' &&
this.cookieService.get("token") !== '';
}
getTokenExpirationDate(): DateTime {
return DateTime.fromISO(this.cookieService.get("token-expiration-date"));
}
isSessionExpired(): boolean {
return this.getTokenExpirationDate() < DateTime.now() && this.isAuthenticated();
}
getAuthenticatedAuthor(): Author {
return JSON.parse(this.cookieService.get('author'));
}
getAuthenticatedAuthorToken(): string {
return this.cookieService.get('token');
}
setSessionExpired(expired: boolean) {
this.sessionExpiredSubject.next(expired);
}
checkSessionExpiration() {
if (this.isSessionExpired()) {
this.setSessionExpired(true);
}
}
}

View File

@ -3,12 +3,12 @@ import {FormControl, FormGroup, ReactiveFormsModule, Validators} from '@angular/
import {InputTextareaModule} from 'primeng/inputtextarea'; import {InputTextareaModule} from 'primeng/inputtextarea';
import {Button} from 'primeng/button'; import {Button} from 'primeng/button';
import {CommentService} from '../../services/comment.service'; import {CommentService} from '../../services/comment.service';
import {CookieService} from 'ngx-cookie-service';
import {Author} from '../../models/author'; import {Author} from '../../models/author';
import {Subscription} from 'rxjs'; import {Subscription} from 'rxjs';
import {Comment} from '../../models/comment'; import {Comment} from '../../models/comment';
import {MessageService} from 'primeng/api'; import {MessageService} from 'primeng/api';
import {NgStyle} from '@angular/common'; import {NgStyle} from '@angular/common';
import {AuthService} from '../../auth.service';
@Component({ @Component({
selector: 'app-comment-form', selector: 'app-comment-form',
@ -31,13 +31,13 @@ export class CommentFormComponent {
subs: Subscription[] = []; subs: Subscription[] = [];
constructor(private commentService: CommentService, constructor(private commentService: CommentService,
private cookieService: CookieService, private messageService: MessageService,
private messageService: MessageService,) { private authService: AuthService,) {
} }
onSubmit() { onSubmit() {
let token: string = this.cookieService.get("token"); let token: string = this.authService.getAuthenticatedAuthorToken();
let author: Author = this.cookieService.get("author") ? JSON.parse(this.cookieService.get("author")) : undefined; let author: Author = this.authService.getAuthenticatedAuthor();
if (this.commentForm.valid && author && token && this.commentForm.value.content) { if (this.commentForm.valid && author && token && this.commentForm.value.content) {
// get l'image de profile après avoir créé le commentaire // get l'image de profile après avoir créé le commentaire
this.subs.push(this.commentService.create(this.commentForm.value.content, this.postId, author.id, token).subscribe({ this.subs.push(this.commentService.create(this.commentForm.value.content, this.postId, author.id, token).subscribe({

View File

@ -1,9 +1,9 @@
import { Component } from '@angular/core'; import {Component} from '@angular/core';
import { CookieService } from 'ngx-cookie-service'; import {MenuItem} from 'primeng/api';
import { MenuItem } from 'primeng/api'; import {MenubarModule} from 'primeng/menubar';
import { MenubarModule } from 'primeng/menubar'; import {ToastModule} from 'primeng/toast';
import { ToastModule } from 'primeng/toast'; import {Author} from '../../models/author';
import { Author } from '../../models/author'; import {AuthService} from '../../auth.service';
@Component({ @Component({
selector: 'app-header', selector: 'app-header',
@ -19,13 +19,14 @@ export class HeaderComponent {
actualAuthor: Author | undefined; actualAuthor: Author | undefined;
items: MenuItem[] = []; items: MenuItem[] = [];
constructor(private cookieService: CookieService) { constructor(private authService: AuthService) {
this.initializeMenu(); this.initializeMenu();
} }
private initializeMenu(): void { private initializeMenu(): void {
const authorData = this.cookieService.get('author'); if (!(this.authService.isSessionExpired()) && this.authService.isAuthenticated()) {
this.actualAuthor = authorData ? JSON.parse(authorData) : undefined; this.actualAuthor = this.authService.getAuthenticatedAuthor();
}
if (this.actualAuthor) { if (this.actualAuthor) {
this.items = this.getMenuForAuthor(this.actualAuthor); this.items = this.getMenuForAuthor(this.actualAuthor);

View File

@ -1,16 +1,16 @@
import {AfterViewInit, Component, Input, OnDestroy, OnInit, ViewChild} from '@angular/core'; import {Component, Input, OnDestroy} from '@angular/core';
import {FormBuilder, FormGroup, ReactiveFormsModule, Validators} from '@angular/forms'; import {FormBuilder, FormGroup, ReactiveFormsModule, Validators} from '@angular/forms';
import {InputTextModule} from 'primeng/inputtext'; import {InputTextModule} from 'primeng/inputtext';
import {InputTextareaModule} from 'primeng/inputtextarea'; import {InputTextareaModule} from 'primeng/inputtextarea';
import {FileSelectEvent, FileUploadModule} from 'primeng/fileupload'; import {FileSelectEvent, FileUploadModule} from 'primeng/fileupload';
import {mergeMap, Subscription} from 'rxjs'; import {mergeMap, Subscription} from 'rxjs';
import {PostService} from '../../services/post.service'; import {PostService} from '../../services/post.service';
import {CookieService} from 'ngx-cookie-service';
import {MessageService} from 'primeng/api'; import {MessageService} from 'primeng/api';
import {EditorModule} from 'primeng/editor'; import {EditorModule} from 'primeng/editor';
import {Router} from '@angular/router'; import {Router} from '@angular/router';
import {Author} from '../../models/author'; import {Author} from '../../models/author';
import {AuthorService} from '../../services/author.service'; import {AuthorService} from '../../services/author.service';
import {AuthService} from '../../auth.service';
@Component({ @Component({
selector: 'app-post-form', selector: 'app-post-form',
@ -49,7 +49,7 @@ export class PostFormComponent implements OnDestroy {
private formBuilder: FormBuilder, private formBuilder: FormBuilder,
private postService: PostService, private postService: PostService,
private authorService: AuthorService, private authorService: AuthorService,
private cookieService: CookieService, private authService: AuthService,
private messageService: MessageService, private messageService: MessageService,
private router: Router private router: Router
) { ) {
@ -105,9 +105,9 @@ export class PostFormComponent implements OnDestroy {
if (this.isUpdateMode && this.postId) { if (this.isUpdateMode && this.postId) {
this.subs.push( this.subs.push(
this.postService.updatePost(this.postId, postData, this.cookieService.get('token')).pipe( this.postService.updatePost(this.postId, postData, this.authService.getAuthenticatedAuthorToken()).pipe(
mergeMap((_) => { mergeMap((_) => {
return this.postService.changeIllustration(this.postId, this.uploadedFile, this.cookieService.get('token')); return this.postService.changeIllustration(this.postId, this.uploadedFile, this.authService.getAuthenticatedAuthorToken());
}) })
).subscribe({ ).subscribe({
next: (_) => { next: (_) => {
@ -119,11 +119,11 @@ export class PostFormComponent implements OnDestroy {
); );
} else { } else {
this.subs.push( this.subs.push(
this.postService.createPost(postData, this.cookieService.get("token")).pipe( this.postService.createPost(postData, this.authService.getAuthenticatedAuthorToken()).pipe(
mergeMap(post => mergeMap(post =>
this.authorService.attributePost(this.actualAuthor?.id, post.id, this.cookieService.get("token")).pipe( this.authorService.attributePost(this.actualAuthor?.id, post.id, this.authService.getAuthenticatedAuthorToken()).pipe(
mergeMap((_) => mergeMap((_) =>
this.postService.changeIllustration(post.id, this.uploadedFile, this.cookieService.get("token")) this.postService.changeIllustration(post.id, this.uploadedFile, this.authService.getAuthenticatedAuthorToken()),
) )
) )
) )
@ -143,7 +143,7 @@ export class PostFormComponent implements OnDestroy {
private transformYouTubeLinksToIframes(html: string): string { private transformYouTubeLinksToIframes(html: string): string {
return html.replace(/<a[^>]*href="(https?:\/\/(?:www\.)?(youtube\.com\/watch\?v=|youtu\.be\/|youtube\.com\/embed\/)([a-zA-Z0-9_-]+)[^"]*)".*?<\/a>/g, return html.replace(/<a[^>]*href="(https?:\/\/(?:www\.)?(youtube\.com\/watch\?v=|youtu\.be\/|youtube\.com\/embed\/)([a-zA-Z0-9_-]+)[^"]*)".*?<\/a>/g,
(_, url, _prefix, videoId) => { (_, _url, _prefix, videoId) => {
return `<iframe width="560" height="315" src="https://www.youtube.com/embed/${videoId}" frameborder="0" allowfullscreen></iframe>`; return `<iframe width="560" height="315" src="https://www.youtube.com/embed/${videoId}" frameborder="0" allowfullscreen></iframe>`;
}); });
} }

View File

@ -1,3 +1,7 @@
.title {
text-align: center;
}
.form-container { .form-container {
margin-top: 2em; margin-top: 2em;
display: flex; display: flex;

View File

@ -1,3 +1,4 @@
<h1 class="title">S'inscrire</h1>
<div class="form-container"> <div class="form-container">
<form class="form" [formGroup]="form" (ngSubmit)="onSubmit()"> <form class="form" [formGroup]="form" (ngSubmit)="onSubmit()">
<label for="username">Nom d'utilisateur</label> <label for="username">Nom d'utilisateur</label>

View File

@ -2,14 +2,14 @@
<form class="form" [formGroup]="form" (ngSubmit)="onSubmit()"> <form class="form" [formGroup]="form" (ngSubmit)="onSubmit()">
<label for="username">Nom d'utilisateur</label> <label for="username">Nom d'utilisateur</label>
<input [(ngModel)]="username" id="username" type="text" pInputText formControlName="username"/> <input [(ngModel)]="username" id="username" type="text" pInputText formControlName="username"/>
<label for="password">Mot de passe</label> <label for="password">Nouveau mot de passe</label>
<input type="password" [(ngModel)]="password" id="password" pInputText formControlName="password"/> <input type="password" [(ngModel)]="password" id="password" pInputText formControlName="password"/>
<label for="passwordConfirm">Confirmez le mot de passe</label> <label for="passwordConfirm">Confirmez le nouveau mot de passe</label>
<input type="password" [(ngModel)]="passwordConfirm" id="passwordConfirm" pInputText <input type="password" [(ngModel)]="passwordConfirm" id="passwordConfirm" pInputText
formControlName="passwordConfirm"/> formControlName="passwordConfirm"/>
<p-fileUpload <p-fileUpload
accept="image/*" accept="image/*"
maxFileSize="1000000" maxFileSize="2000000"
[showUploadButton]="false" [showUploadButton]="false"
[showCancelButton]="false" [showCancelButton]="false"
chooseLabel="Sélectionner une image" chooseLabel="Sélectionner une image"

View File

@ -10,6 +10,7 @@ import {FileSelectEvent, FileUploadModule} from 'primeng/fileupload';
import {CookieService} from 'ngx-cookie-service'; import {CookieService} from 'ngx-cookie-service';
import {Author} from '../../models/author'; import {Author} from '../../models/author';
import {Router} from '@angular/router'; import {Router} from '@angular/router';
import {AuthService} from '../../auth.service';
@Component({ @Component({
selector: 'app-update-profile', selector: 'app-update-profile',
@ -38,6 +39,7 @@ export class UpdateProfileFormComponent implements OnDestroy {
private authorService: AuthorService, private authorService: AuthorService,
private messageService: MessageService, private messageService: MessageService,
private cookieService: CookieService, private cookieService: CookieService,
private authService: AuthService,
private router: Router, private router: Router,
) { ) {
this.form = this.formBuilder.group({ this.form = this.formBuilder.group({
@ -78,7 +80,7 @@ export class UpdateProfileFormComponent implements OnDestroy {
} }
onSubmit() { onSubmit() {
const token: string | undefined = this.cookieService.get('token'); const token: string = this.authService.getAuthenticatedAuthorToken();
if (this.form.valid && token && this.password === this.passwordConfirm) { if (this.form.valid && token && this.password === this.passwordConfirm) {
const newUsername = this.form.value.username; const newUsername = this.form.value.username;
if (this.uploadedFile) { if (this.uploadedFile) {

View File

@ -13,4 +13,8 @@ export class ConfigurationService {
getServerAddress(): string { getServerAddress(): string {
return config.serverAddress return config.serverAddress
} }
getTokenTTL(): number {
return config.tokenTTL
}
} }

View File

@ -2,17 +2,16 @@ import {CanActivateFn, Router} from '@angular/router';
import {inject} from '@angular/core'; import {inject} from '@angular/core';
import {CookieService} from 'ngx-cookie-service'; import {CookieService} from 'ngx-cookie-service';
import {Author} from '../models/author'; import {Author} from '../models/author';
import {AuthService} from '../auth.service';
export const adminGuard: CanActivateFn = (route, state) => { export const adminGuard: CanActivateFn = (route, state) => {
const router = inject(Router); const router = inject(Router);
const cookieService = inject(CookieService); const cookieService = inject(CookieService);
const authService: AuthService = inject(AuthService);
if (cookieService.get("author") !== '') { if ((authService.isAuthenticated() && JSON.parse(cookieService.get("author")).role !== 'ADMIN') || !authService.isAuthenticated()) {
if (JSON.parse(cookieService.get("author")).role !== 'ADMIN')
{
router.navigate(['/']); router.navigate(['/']);
} }
}
return true; return true;
}; };

View File

@ -5,7 +5,7 @@ import {CookieService} from 'ngx-cookie-service';
export const authGuard: CanActivateFn = (route, state) => { export const authGuard: CanActivateFn = (route, state) => {
const router = inject(Router); const router = inject(Router);
const cookieService = inject(CookieService); const cookieService = inject(CookieService);
if (cookieService.get("author") !== '') { if (cookieService.check("author") || cookieService.check("token")) {
router.navigate(['/']); router.navigate(['/']);
} }

View File

@ -1,17 +1,16 @@
import {CanActivateFn, Router} from '@angular/router'; import {CanActivateFn, Router} from '@angular/router';
import {inject} from '@angular/core'; import {inject} from '@angular/core';
import {CookieService} from 'ngx-cookie-service'; import {CookieService} from 'ngx-cookie-service';
import {AuthService} from '../auth.service';
export const writerGuard: CanActivateFn = (route, state) => { export const writerGuard: CanActivateFn = (route, state) => {
const router = inject(Router); const router = inject(Router);
const cookieService = inject(CookieService); const cookieService = inject(CookieService);
const authService = inject(AuthService);
if (cookieService.get("author") !== '') { if ((authService.isAuthenticated() && JSON.parse(cookieService.get("author")).role !== 'WRITER') || !authService.isAuthenticated()) {
if (JSON.parse(cookieService.get("author")).role !== 'WRITER' && JSON.parse(cookieService.get("author")).role !== 'ADMIN')
{
router.navigate(['/']); router.navigate(['/']);
} }
}
return true; return true;
}; };

View File

@ -1,19 +1,14 @@
import {Component, OnDestroy} from '@angular/core'; import {Component, OnDestroy} from '@angular/core';
import {AvatarModule} from 'primeng/avatar'; import {AvatarModule} from 'primeng/avatar';
import {Button} from 'primeng/button';
import {AuthorService} from '../../services/author.service';
import {Author} from '../../models/author'; import {Author} from '../../models/author';
import {JsonPipe} from '@angular/common';
import {Subscription} from 'rxjs'; import {Subscription} from 'rxjs';
import {MessageService} from 'primeng/api';
import {HeaderComponent} from '../../components/header/header.component'; import {HeaderComponent} from '../../components/header/header.component';
import {ToastModule} from 'primeng/toast'; import {ToastModule} from 'primeng/toast';
import {CookieService} from 'ngx-cookie-service';
import {PostService} from '../../services/post.service'; import {PostService} from '../../services/post.service';
import {Post} from '../../models/post';
import {PostHomeComponent} from '../../components/post-home/post-home.component'; import {PostHomeComponent} from '../../components/post-home/post-home.component';
import {AuthorWithPost} from '../../models/author-with-post'; import {AuthorWithPost} from '../../models/author-with-post';
import {FooterComponent} from '../../components/footer/footer.component'; import {FooterComponent} from '../../components/footer/footer.component';
import {AuthService} from '../../auth.service';
@Component({ @Component({
selector: 'app-home', selector: 'app-home',
@ -35,10 +30,12 @@ export class HomeComponent implements OnDestroy {
constructor( constructor(
private postService: PostService, private postService: PostService,
private cookieService: CookieService) { private authService: AuthService) {
if (this.cookieService.get('author')) { if (!(this.authService.isSessionExpired()) && this.authService.isAuthenticated()) {
this.actualAuthor = JSON.parse(this.cookieService.get('author')); this.actualAuthor = this.authService.getAuthenticatedAuthor();
} else {
this.authService.checkSessionExpiration();
} }
this.subs.push(this.postService.listWithAuthors() this.subs.push(this.postService.listWithAuthors()
.subscribe({ .subscribe({

View File

@ -5,6 +5,10 @@
align-items: center; align-items: center;
} }
.title {
text-align: center;
}
.form { .form {
width: 100%; width: 100%;
max-width: 50em; max-width: 50em;

View File

@ -1,4 +1,5 @@
<app-header></app-header> <app-header></app-header>
<h1 class="title">Se connecter</h1>
<div class="form-container"> <div class="form-container">
<div class="form"> <div class="form">
<label for="username">Nom d'utilisateur</label> <label for="username">Nom d'utilisateur</label>

View File

@ -1,4 +1,4 @@
import {ChangeDetectorRef, Component, CUSTOM_ELEMENTS_SCHEMA, OnDestroy} from '@angular/core'; import {Component, OnDestroy} from '@angular/core';
import {FormsModule} from '@angular/forms'; import {FormsModule} from '@angular/forms';
import {InputTextModule} from 'primeng/inputtext'; import {InputTextModule} from 'primeng/inputtext';
import {Button} from 'primeng/button'; import {Button} from 'primeng/button';
@ -7,10 +7,12 @@ import {ToastModule} from 'primeng/toast';
import {MessageService} from 'primeng/api'; import {MessageService} from 'primeng/api';
import {Author} from '../../models/author'; import {Author} from '../../models/author';
import {Subscription, switchMap} from 'rxjs'; import {Subscription, switchMap} from 'rxjs';
import { CookieService } from 'ngx-cookie-service'; import {CookieService} from 'ngx-cookie-service';
import {HeaderComponent} from '../../components/header/header.component'; import {HeaderComponent} from '../../components/header/header.component';
import {Router} from '@angular/router'; import {Router} from '@angular/router';
import {FooterComponent} from '../../components/footer/footer.component'; import {FooterComponent} from '../../components/footer/footer.component';
import {ConfigurationService} from '../../configuration.service';
import {DateTime} from 'luxon';
@Component({ @Component({
selector: 'app-login', selector: 'app-login',
@ -36,7 +38,8 @@ export class LoginComponent implements OnDestroy {
constructor(private authorService: AuthorService, constructor(private authorService: AuthorService,
private messageService: MessageService, private messageService: MessageService,
private cookieService: CookieService, private cookieService: CookieService,
private router: Router) {} private router: Router,
private configurationService: ConfigurationService,) {}
sendLogins(): void { sendLogins(): void {
if (this.password === this.confirmPassword) { if (this.password === this.confirmPassword) {
@ -44,13 +47,23 @@ export class LoginComponent implements OnDestroy {
( (
this.authorService.login(this.name, this.password).pipe( this.authorService.login(this.name, this.password).pipe(
switchMap((tokenObj: any) => { switchMap((tokenObj: any) => {
this.cookieService.set("token", tokenObj.token); this.cookieService.delete('token', '/', this.configurationService.getServerAddress())
this.cookieService.set("token", tokenObj.token, {
secure: true,
path: '/'
});
return this.authorService.me(tokenObj.token) return this.authorService.me(tokenObj.token)
})) }))
.subscribe({ .subscribe({
next: (author: Author) => { next: (author: Author) => {
console.log(author) this.cookieService.delete('author', '/', this.configurationService.getServerAddress())
this.cookieService.set("author", JSON.stringify(author), {path: '/'}); this.cookieService.set("author", JSON.stringify(author), {
secure : true,
path: '/' });
this.cookieService.set('token-expiration-date', DateTime.now().plus({millisecond: this.configurationService.getTokenTTL()}).toISO(), {
secure: true,
path: '/',
})
this.getAuthorCookie(); this.getAuthorCookie();
this.router.navigate(['/']).then(() => { this.router.navigate(['/']).then(() => {
this.successMessage('Connecté avec succès', 'Heureux de vous revoir ' + this.actualAuthor?.name) this.successMessage('Connecté avec succès', 'Heureux de vous revoir ' + this.actualAuthor?.name)

View File

@ -16,13 +16,18 @@ import {ConfigurationService} from '../../configuration.service';
}) })
export class LogoutComponent implements OnInit{ export class LogoutComponent implements OnInit{
constructor(private cookiesService: CookieService, constructor(private cookieService: CookieService,
private messageService: MessageService, private messageService: MessageService,
private router: Router, private router: Router,
private configurationService: ConfigurationService,) { } private configurationService: ConfigurationService,) { }
ngOnInit(): void { ngOnInit(): void {
this.cookiesService.delete('author', '/', this.configurationService.getServerAddress()) console.log(this.cookieService.getAll())
this.cookiesService.delete('token', '/', this.configurationService.getServerAddress()) const routes: string[] = ['/', '/login', '/register', '/logout', '/profile', '/post', '/new-post']
Object.keys(this.cookieService.getAll()).forEach(key => {
routes.forEach(route => {
this.cookieService.delete(key, route, this.configurationService.getServerAddress());
})
});
this.router.navigate(['/']).then(() => this.successMessage('Déconnexion', 'Vous avez été deconnecté avec succès')); this.router.navigate(['/']).then(() => this.successMessage('Déconnexion', 'Vous avez été deconnecté avec succès'));
} }

View File

@ -1,9 +1,8 @@
import {Component, OnDestroy} from '@angular/core'; import {Component, OnDestroy} from '@angular/core';
import {HeaderComponent} from '../../components/header/header.component'; import {HeaderComponent} from '../../components/header/header.component';
import {TableModule} from 'primeng/table'; import {TableModule} from 'primeng/table';
import {CookieService} from 'ngx-cookie-service';
import {AuthorService} from '../../services/author.service'; import {AuthorService} from '../../services/author.service';
import {ReplaySubject, Subscription} from 'rxjs'; import {Subscription} from 'rxjs';
import {Post} from '../../models/post'; import {Post} from '../../models/post';
import {Author} from '../../models/author'; import {Author} from '../../models/author';
import {MessageService} from 'primeng/api'; import {MessageService} from 'primeng/api';
@ -15,6 +14,7 @@ import {PostHomeComponent} from '../../components/post-home/post-home.component'
import {PostService} from '../../services/post.service'; import {PostService} from '../../services/post.service';
import {PostFormComponent} from "../../components/post-form/post-form.component"; import {PostFormComponent} from "../../components/post-form/post-form.component";
import {FooterComponent} from '../../components/footer/footer.component'; import {FooterComponent} from '../../components/footer/footer.component';
import {AuthService} from '../../auth.service';
@Component({ @Component({
selector: 'app-my-posts', selector: 'app-my-posts',
@ -39,14 +39,14 @@ export class MyPostsComponent implements OnDestroy {
updateDialogVisibility: boolean[] = []; updateDialogVisibility: boolean[] = [];
deleteDialogVisibility: boolean[] = []; deleteDialogVisibility: boolean[] = [];
posts: Post[] = []; posts: Post[] = [];
actualAuthor: Author | undefined; actualAuthor: Author;
constructor(private cookieService: CookieService, constructor(private authService: AuthService,
private postService: PostService, private postService: PostService,
private authorService: AuthorService, private authorService: AuthorService,
private messageService: MessageService) { private messageService: MessageService) {
this.actualAuthor = this.cookieService.get('author') ? JSON.parse(this.cookieService.get('author')) : undefined; this.actualAuthor = this.authService.getAuthenticatedAuthor();
this.updatePosts(); this.updatePosts();
} }
@ -61,17 +61,19 @@ export class MyPostsComponent implements OnDestroy {
} }
updatePosts(): void { updatePosts(): void {
if (this.cookieService.get('token')) { if (!(this.authService.isSessionExpired()) && this.authService.isAuthenticated()) {
this.authorService.getAuthorsPosts(this.actualAuthor?.id, this.cookieService.get('token')).subscribe({ this.authorService.getAuthorsPosts(this.actualAuthor?.id, this.authService.getAuthenticatedAuthorToken()).subscribe({
next: posts => this.posts = posts, next: posts => this.posts = posts,
error: error => this.failureMessage("Erreur", error.message), error: error => this.failureMessage("Erreur", error.message),
} }
) )
} else {
this.authService.checkSessionExpiration();
} }
} }
deletePost(id: bigint, rowIndex: number) { deletePost(id: bigint, rowIndex: number) {
this.postService.deletePost(id, this.cookieService.get('token')).subscribe({ this.postService.deletePost(id, this.authService.getAuthenticatedAuthorToken()).subscribe({
next: (_) => { next: (_) => {
this.updatePosts() this.updatePosts()
this.successMessage("Post supprimé", "Ce post a été supprimé avec succès") this.successMessage("Post supprimé", "Ce post a été supprimé avec succès")

View File

@ -1,13 +1,11 @@
import {Component, OnDestroy} from '@angular/core'; import {Component, EventEmitter, OnDestroy} from '@angular/core';
import {HeaderComponent} from '../../components/header/header.component'; import {HeaderComponent} from '../../components/header/header.component';
import {FormBuilder, FormControl, FormGroup, ReactiveFormsModule, ValidationErrors, Validators} from '@angular/forms'; import {FormBuilder, FormGroup, ReactiveFormsModule, Validators} from '@angular/forms';
import {InputTextModule} from 'primeng/inputtext'; import {InputTextModule} from 'primeng/inputtext';
import {InputTextareaModule} from 'primeng/inputtextarea'; import {InputTextareaModule} from 'primeng/inputtextarea';
import {FileSelectEvent, FileUploadModule} from 'primeng/fileupload'; import {FileSelectEvent, FileUploadModule} from 'primeng/fileupload';
import {mergeMap, Subscription, switchMap} from 'rxjs'; import {mergeMap, Subscription} from 'rxjs';
import {Post} from '../../models/post';
import {PostService} from '../../services/post.service'; import {PostService} from '../../services/post.service';
import {CookieService} from 'ngx-cookie-service';
import {MessageService} from 'primeng/api'; import {MessageService} from 'primeng/api';
import {EditorModule} from 'primeng/editor'; import {EditorModule} from 'primeng/editor';
import {AuthorService} from '../../services/author.service'; import {AuthorService} from '../../services/author.service';
@ -15,6 +13,7 @@ import {Author} from '../../models/author';
import {Router} from '@angular/router'; import {Router} from '@angular/router';
import {PostFormComponent} from '../../components/post-form/post-form.component'; import {PostFormComponent} from '../../components/post-form/post-form.component';
import {FooterComponent} from '../../components/footer/footer.component'; import {FooterComponent} from '../../components/footer/footer.component';
import {AuthService} from '../../auth.service';
@Component({ @Component({
selector: 'app-new-post', selector: 'app-new-post',
@ -33,6 +32,7 @@ import {FooterComponent} from '../../components/footer/footer.component';
styleUrl: './new-post.component.css' styleUrl: './new-post.component.css'
}) })
export class NewPostComponent implements OnDestroy { export class NewPostComponent implements OnDestroy {
isSessionExpired: EventEmitter<boolean> = new EventEmitter<boolean>();
subs: Subscription[] = [] subs: Subscription[] = []
actualAuthor: Author | undefined; actualAuthor: Author | undefined;
uploadedFile: File | undefined; uploadedFile: File | undefined;
@ -40,9 +40,9 @@ export class NewPostComponent implements OnDestroy {
constructor(private formBuilder: FormBuilder, constructor(private formBuilder: FormBuilder,
private postService: PostService, private postService: PostService,
private cookieService: CookieService,
private authorService: AuthorService, private authorService: AuthorService,
private messageService: MessageService, private messageService: MessageService,
private authService : AuthService,
private router: Router) { private router: Router) {
this.form = this.formBuilder.group({ this.form = this.formBuilder.group({
description: ['', [Validators.required, Validators.maxLength(512)]], description: ['', [Validators.required, Validators.maxLength(512)]],
@ -50,8 +50,10 @@ export class NewPostComponent implements OnDestroy {
body: ['', [Validators.required]], body: ['', [Validators.required]],
category: ['', [Validators.required, Validators.maxLength(50)]], category: ['', [Validators.required, Validators.maxLength(50)]],
}); });
if (this.cookieService.get("author")) { if (!(this.authService.isSessionExpired()) && this.authService.isAuthenticated()) {
this.actualAuthor = JSON.parse(this.cookieService.get("author")); this.actualAuthor = this.authService.getAuthenticatedAuthor();
} else {
this.authService.checkSessionExpiration();
} }
} }
@ -73,11 +75,11 @@ export class NewPostComponent implements OnDestroy {
}; };
this.subs.push( this.subs.push(
this.postService.createPost(postToPost, this.cookieService.get("token")).pipe( this.postService.createPost(postToPost, this.authService.getAuthenticatedAuthorToken()).pipe(
mergeMap(post => mergeMap(post =>
this.authorService.attributePost(this.actualAuthor?.id, post.id, this.cookieService.get("token")).pipe( this.authorService.attributePost(this.actualAuthor?.id, post.id, this.authService.getAuthenticatedAuthorToken()).pipe(
mergeMap((_) => mergeMap((_) =>
this.postService.changeIllustration(post.id, this.uploadedFile, this.cookieService.get("token")) this.postService.changeIllustration(post.id, this.uploadedFile, this.authService.getAuthenticatedAuthorToken()),
) )
) )
) )

View File

@ -11,12 +11,12 @@ import {Comment} from '../../models/comment';
import {AvatarModule} from 'primeng/avatar'; import {AvatarModule} from 'primeng/avatar';
import {CardModule} from 'primeng/card'; import {CardModule} from 'primeng/card';
import {SafeHtmlPipe} from '../../pipes/safe-html-pipe'; import {SafeHtmlPipe} from '../../pipes/safe-html-pipe';
import {CookieService} from 'ngx-cookie-service';
import {Author} from '../../models/author'; import {Author} from '../../models/author';
import {CommentFormComponent} from '../../components/comment-form/comment-form.component'; import {CommentFormComponent} from '../../components/comment-form/comment-form.component';
import {FooterComponent} from '../../components/footer/footer.component'; import {FooterComponent} from '../../components/footer/footer.component';
import {Button} from 'primeng/button'; import {Button} from 'primeng/button';
import {DialogModule} from 'primeng/dialog'; import {DialogModule} from 'primeng/dialog';
import {AuthService} from '../../auth.service';
@Component({ @Component({
selector: 'app-post', selector: 'app-post',
@ -47,10 +47,12 @@ export class PostComponent {
private postService: PostService, private postService: PostService,
private commentService: CommentService, private commentService: CommentService,
private messageService: MessageService, private messageService: MessageService,
private cookieService: CookieService,) { private authService: AuthService,) {
this.route.paramMap.subscribe(params => { this.route.paramMap.subscribe(params => {
if (this.cookieService.get('author')) { if (!(this.authService.isSessionExpired()) && this.authService.isAuthenticated()) {
this.actualAuthor = JSON.parse(this.cookieService.get('author')) this.actualAuthor = this.authService.getAuthenticatedAuthor();
} else {
this.authService.checkSessionExpiration();
} }
const postId = params.get('postId'); const postId = params.get('postId');
if (postId) { if (postId) {
@ -96,7 +98,7 @@ export class PostComponent {
} }
deleteComment(comment: Comment) { deleteComment(comment: Comment) {
const token = this.cookieService.get('token'); const token = this.authService.getAuthenticatedAuthorToken();
if (token) { if (token) {
this.subs.push( this.subs.push(
this.commentService.delete(comment.id, token).subscribe({ this.commentService.delete(comment.id, token).subscribe({

View File

@ -25,11 +25,6 @@
<app-update-profile (updatedAuthorEvent)="updateAuthor($event)" [authorId]="concernedAuthor.id" <app-update-profile (updatedAuthorEvent)="updateAuthor($event)" [authorId]="concernedAuthor.id"
[username]="concernedAuthor!.name"></app-update-profile> [username]="concernedAuthor!.name"></app-update-profile>
</p-dialog> </p-dialog>
<p-button label="Changer le mot de passe" (onClick)="changePasswordDialog=true"/>
<p-dialog header='Changer le mot de passe' [modal]="true"
[(visible)]="changePasswordDialog">
</p-dialog>
} }
} }
</div> </div>

View File

@ -1,7 +1,6 @@
import {Component, OnDestroy} from '@angular/core'; import {Component, OnDestroy} from '@angular/core';
import {HeaderComponent} from '../../components/header/header.component'; import {HeaderComponent} from '../../components/header/header.component';
import {ActivatedRoute} from '@angular/router'; import {ActivatedRoute} from '@angular/router';
import {CookieService} from 'ngx-cookie-service';
import {Author} from '../../models/author'; import {Author} from '../../models/author';
import {Subscription} from 'rxjs'; import {Subscription} from 'rxjs';
import {AuthorService} from '../../services/author.service'; import {AuthorService} from '../../services/author.service';
@ -11,6 +10,7 @@ import {Button} from 'primeng/button';
import {DialogModule} from 'primeng/dialog'; import {DialogModule} from 'primeng/dialog';
import {UpdateProfileFormComponent} from '../../components/update-profile-form/update-profile-form.component'; import {UpdateProfileFormComponent} from '../../components/update-profile-form/update-profile-form.component';
import {FooterComponent} from '../../components/footer/footer.component'; import {FooterComponent} from '../../components/footer/footer.component';
import {AuthService} from '../../auth.service';
@Component({ @Component({
selector: 'app-profile', selector: 'app-profile',
@ -37,15 +37,17 @@ export class ProfileComponent implements OnDestroy {
constructor(private route: ActivatedRoute, constructor(private route: ActivatedRoute,
private authorService: AuthorService, private authorService: AuthorService,
private cookieService: CookieService) { private authService: AuthService) {
this.route.paramMap.subscribe(params => { this.route.paramMap.subscribe(params => {
this.subs.push(this.authorService.getAuthor(params.get('authorId')).subscribe(author => { this.subs.push(this.authorService.getAuthor(params.get('authorId')).subscribe(author => {
this.concernedAuthor = author; this.concernedAuthor = author;
this.authorName = author.name; this.authorName = author.name;
})); }));
}) })
if (this.cookieService.get('author')) { if (!(this.authService.isSessionExpired()) && this.authService.isAuthenticated()) {
this.actualAuthor = JSON.parse(this.cookieService.get("author")); this.actualAuthor = this.authService.getAuthenticatedAuthor();
} else {
this.authService.checkSessionExpiration();
} }
} }

View File

@ -12,10 +12,11 @@
"skipLibCheck": true, "skipLibCheck": true,
"isolatedModules": true, "isolatedModules": true,
"esModuleInterop": true, "esModuleInterop": true,
"resolveJsonModule": true,
"sourceMap": true, "sourceMap": true,
"declaration": false, "declaration": false,
"experimentalDecorators": true, "experimentalDecorators": true,
"moduleResolution": "bundler", "moduleResolution": "node",
"importHelpers": true, "importHelpers": true,
"target": "ES2022", "target": "ES2022",
"module": "ES2022", "module": "ES2022",