Compare commits

..

5 Commits
master ... dev

44 changed files with 464 additions and 230 deletions

View File

@ -2,7 +2,6 @@
## Liste des améliorations
- [ ] Faire du sessionStorage à la place d'un stockage avec cookie
- [ ] Bouton "Voir les posts de l'utilisateur" à enlever (un seul écrivain donc inutile...)
- [ ] Bug CSS concernant le footer
- [ ] Mauvaise actualisation du pseudo quand on se renomme
@ -11,10 +10,10 @@
- [ ] Garder l'avatar de l'utilisateur quand il met à jour uniquement son pseudo
- [ ] Ne pas avoir à confirmer son mot de passe lors de la connexion
- [ ] Pouvoir modifier son commentaire
- [ ] L'avatar s'affiche pas quand on upload un commentaire (il faut recharger la page)
- [x] L'avatar s'affiche pas quand on upload un commentaire (il faut recharger la page)
- [ ] Faire des meilleurs modal
- [ ] Terminer l'interface admin
- [ ] Bug (de temps en temps) pour stocker les cookies utilisateur
- [x] Bug (de temps en temps) pour stocker les données utilisateur
pour run le docker :
```

View File

@ -28,14 +28,10 @@
}
],
"styles": [
"@angular/material/prebuilt-themes/azure-blue.css",
"src/styles.css"
],
"scripts": [],
"server": "src/main.server.ts",
"prerender": true,
"ssr": {
"entry": "server.ts"
}
"scripts": []
},
"configurations": {
"production": {
@ -97,6 +93,7 @@
}
],
"styles": [
"@angular/material/prebuilt-themes/magenta-violet.css",
"src/styles.css"
],
"scripts": []

View File

@ -12,20 +12,23 @@
"private": true,
"dependencies": {
"@angular/animations": "^18.2.0",
"@angular/cdk": "^18.2.14",
"@angular/common": "^18.2.0",
"@angular/compiler": "^18.2.0",
"@angular/core": "^18.2.0",
"@angular/forms": "^18.2.0",
"@angular/material": "^18.2.14",
"@angular/platform-browser": "^18.2.0",
"@angular/platform-browser-dynamic": "^18.2.0",
"@angular/platform-server": "^18.2.0",
"@angular/router": "^18.2.0",
"@angular/ssr": "^18.2.12",
"@angular/ssr": "^18.2.18",
"@primeng/themes": "^19.1.0",
"express": "^4.18.2",
"luxon": "^3.5.0",
"ngx-cookie-service": "^18.0.0",
"primeicons": "^7.0.0",
"primeng": "^17.18.10",
"primeng": "^18.0.2",
"quill": "^2.0.3",
"review-front": "file:",
"rxjs": "~7.8.0",
@ -33,8 +36,8 @@
"zone.js": "~0.14.10"
},
"devDependencies": {
"@angular-devkit/build-angular": "^18.2.12",
"@angular/cli": "^18.2.12",
"@angular-devkit/build-angular": "^18.2.18",
"@angular/cli": "^18.2.18",
"@angular/compiler-cli": "^18.2.0",
"@types/express": "^4.17.17",
"@types/jasmine": "~5.1.0",

View File

@ -1,5 +1,5 @@
<router-outlet></router-outlet>
@if (isBrowser()) {
@if (isBrowser() && (authService.isSessionExpired() && authService.isAuthenticated())) {
<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">

View File

@ -7,12 +7,12 @@ 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';
import {Router, RouterOutlet} from '@angular/router';
@Component({
selector: 'app-root',
standalone: true,
imports: [MenubarModule, FloatLabelModule, ToastModule, DialogModule, Button],
imports: [MenubarModule, FloatLabelModule, ToastModule, DialogModule, Button, RouterOutlet],
providers: [
MessageService,
],
@ -23,17 +23,18 @@ export class AppComponent implements OnInit {
isSessionExpired: boolean = false;
constructor(@Inject(PLATFORM_ID) private platformId: object,
private authService: AuthService,
private cookieService: CookieService) {
protected authService: AuthService,
private router: Router,) {
}
isBrowser(): boolean {
return isPlatformBrowser(this.platformId);
return isPlatformBrowser(this.platformId)
}
setSessionExpiredFalse(): void {
this.isSessionExpired = false;
this.authService.setSessionExpired(false);
this.router.navigate(['/logout']);
}
ngOnInit(): void {

View File

@ -1,10 +1,12 @@
import {ApplicationConfig, importProvidersFrom, provideZoneChangeDetection} from '@angular/core';
import {provideRouter} from '@angular/router';
import {routes} from './app.routes';
import {provideClientHydration} from '@angular/platform-browser';
import {provideHttpClient, withFetch} from '@angular/common/http';
import {BrowserAnimationsModule} from '@angular/platform-browser/animations';
import {provideAnimationsAsync} from '@angular/platform-browser/animations/async';
import {providePrimeNG} from 'primeng/config';
import {myPreset} from './preset'
export const appConfig: ApplicationConfig = {
providers: [
@ -12,5 +14,14 @@ export const appConfig: ApplicationConfig = {
provideRouter(routes),
provideClientHydration(),
provideHttpClient(withFetch()),
importProvidersFrom([BrowserAnimationsModule])]
provideAnimationsAsync(),
providePrimeNG({
theme: {
preset: myPreset,
options: {
darkModeSelector: '.my-app-dark' // class css pour activer le dark mode
}
}
}),
importProvidersFrom([BrowserAnimationsModule]), provideAnimationsAsync()]
};

View File

@ -1,7 +1,6 @@
import { Injectable } from '@angular/core';
import { CookieService } from 'ngx-cookie-service';
import { Author } from './models/author';
import { BehaviorSubject } from 'rxjs';
import {Injectable} from '@angular/core';
import {Author} from './models/author';
import {BehaviorSubject} from 'rxjs';
import {DateTime} from 'luxon';
@Injectable({
@ -11,33 +10,38 @@ export class AuthService {
private sessionExpiredSubject = new BehaviorSubject<boolean>(false);
sessionExpired$ = this.sessionExpiredSubject.asObservable();
constructor(private cookieService: CookieService) {
constructor() {
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") !== '';
return sessionStorage.getItem("author") !== null &&
sessionStorage.getItem("token") !== null &&
sessionStorage.getItem("token-expiration-date") !== null;
}
getTokenExpirationDate(): DateTime {
return DateTime.fromISO(this.cookieService.get("token-expiration-date"));
getTokenExpirationDate(): string | null {
return sessionStorage.getItem("token-expiration-date");
}
isSessionExpired(): boolean {
return this.getTokenExpirationDate() < DateTime.now() && this.isAuthenticated();
const tokenExpirationDate = this.getTokenExpirationDate();
if (tokenExpirationDate) {
return DateTime.fromISO(tokenExpirationDate) < DateTime.now() && this.isAuthenticated();
}
return true
}
getAuthenticatedAuthor(): Author {
return JSON.parse(this.cookieService.get('author'));
getAuthenticatedAuthor(): Author | null {
const authorStr = sessionStorage.getItem('author')
if (authorStr) {
return JSON.parse(authorStr);
}
return null;
}
getAuthenticatedAuthorToken(): string {
return this.cookieService.get('token');
getAuthenticatedAuthorToken(): string | null{
return sessionStorage.getItem('token');
}
setSessionExpired(expired: boolean) {

View File

@ -1,21 +1,19 @@
import {Component, EventEmitter, Input, Output} from '@angular/core';
import {FormControl, FormGroup, ReactiveFormsModule, Validators} from '@angular/forms';
import {InputTextareaModule} from 'primeng/inputtextarea';
import {Button} from 'primeng/button';
import {CommentService} from '../../services/comment.service';
import {Author} from '../../models/author';
import {Subscription} from 'rxjs';
import {Subscription, switchMap} from 'rxjs';
import {Comment} from '../../models/comment';
import {MessageService} from 'primeng/api';
import {NgStyle} from '@angular/common';
import {AuthService} from '../../auth.service';
import {AuthorService} from '../../services/author.service';
@Component({
selector: 'app-comment-form',
standalone: true,
imports: [
ReactiveFormsModule,
InputTextareaModule,
Button,
NgStyle
],
@ -29,25 +27,36 @@ export class CommentFormComponent {
@Input({required: true}) postId: bigint = BigInt(1);
@Output() commentToEmit = new EventEmitter<Comment>();
subs: Subscription[] = [];
createdComment: Comment = {} as Comment;
constructor(private commentService: CommentService,
private messageService: MessageService,
private authService: AuthService,) {
private authService: AuthService,
private authorService: AuthorService) {
}
onSubmit() {
let token: string = this.authService.getAuthenticatedAuthorToken();
let author: Author = this.authService.getAuthenticatedAuthor();
let token = this.authService.getAuthenticatedAuthorToken();
let author = this.authService.getAuthenticatedAuthor();
if (this.commentForm.valid && author && token && this.commentForm.value.content) {
// 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({
next: (comment: Comment) => {
comment.authorId = author.id;
comment.authorName = author.name;
comment.profilePicture = author.profilePicture;
comment.authorRole = author.role;
this.subs.push(this.commentService.create(this.commentForm.value.content, this.postId, author.id, token).pipe(
switchMap((comment: Comment) => {
this.createdComment.authorId = author.id;
this.createdComment.content = comment.content;
this.createdComment.id = comment.id;
this.createdComment.commentDate = comment.commentDate;
this.createdComment.authorName = author.name;
this.createdComment.authorRole = author.role;
this.commentForm.value.content = "";
this.commentToEmit.emit(comment);
return this.authorService.getAvatar(author?.id)
})
).subscribe({
next: (profilePicture: string) => {
this.createdComment.profilePicture = profilePicture; // c'est de la merde
this.commentForm.value.content = "";
this.commentToEmit.emit(this.createdComment);
console.log(this.createdComment)
this.successMessage("Succès", "Commentaire créé avec succès");
},
error: (error) => {

View File

@ -25,8 +25,9 @@ export class HeaderComponent {
}
private initializeMenu(): void {
if (!(this.authService.isSessionExpired()) && this.authService.isAuthenticated()) {
this.actualAuthor = this.authService.getAuthenticatedAuthor();
const authenticatedAuthor = this.authService.getAuthenticatedAuthor();
if (!(this.authService.isSessionExpired()) && this.authService.isAuthenticated() && authenticatedAuthor) {
this.actualAuthor = authenticatedAuthor;
}
if (this.actualAuthor) {

View File

@ -0,0 +1,24 @@
div {
margin-top: 10em;
display: flex;
justify-content: center;
align-items: center;
}
img {
animation-name: spin;
animation-duration: 2000ms;
animation-iteration-count: infinite;
animation-timing-function: linear;
max-width: 40%;
max-height: 40%;
}
@keyframes spin {
from {
transform:rotate(0deg);
}
to {
transform:rotate(360deg);
}
}

View File

@ -0,0 +1,3 @@
<div>
<img src="./assets/icon.jpg" alt="loadign">
</div>

View File

@ -0,0 +1,15 @@
import { Component } from '@angular/core';
import {NgOptimizedImage} from '@angular/common';
@Component({
selector: 'app-loading',
standalone: true,
imports: [
NgOptimizedImage
],
templateUrl: './loading.component.html',
styleUrl: './loading.component.css'
})
export class LoadingComponent {
}

View File

@ -0,0 +1,15 @@
@if (post) {
<p-dialog class="preview-dialog"
header='Prévisualisation de "{{ post.title }}"'
[modal]="true"
[(visible)]="opened"
[closable]="true">
<app-post-home [title]="post.title"
[description]="post.description"
[category]="post.category"
[date]="post.publicationDate"
[illustration]="post.illustration"
[authorProfilePicture]="profilePicture"
[username]="username"/>
</p-dialog>
}

View File

@ -0,0 +1,21 @@
import {Component, Input} from '@angular/core';
import {Dialog} from 'primeng/dialog';
import {PostHomeComponent} from '../../post-home/post-home.component';
import {Post} from '../../../models/post';
@Component({
selector: 'app-preview-modal',
standalone: true,
imports: [
Dialog,
PostHomeComponent
],
templateUrl: './preview-modal.component.html',
styleUrl: './preview-modal.component.css'
})
export class PreviewModalComponent {
opened: boolean = true;
@Input({required: true}) post: Post | undefined;
@Input() username: string = '';
@Input() profilePicture: string = '';
}

View File

@ -0,0 +1,15 @@
@if (post) {
<p-dialog header='Modifier "{{ post.title }}"'
[modal]="true"
[closable]="true"
[(visible)]="opened">
<app-post-form [actualAuthor]="actualAuthor"
[postId]="post.id"
[isUpdateMode]="true"
[title]="post.title"
[category]="post.category"
[description]="post.description"
[body]="post.body"
(postUpdate)="onSubmit(post)"/>
</p-dialog>
}

View File

@ -0,0 +1,33 @@
import {Component, EventEmitter, Input, Output} from '@angular/core';
import {Dialog} from 'primeng/dialog';
import {PostFormComponent} from '../../post-form/post-form.component';
import {Post} from '../../../models/post';
import {AuthService} from '../../../auth.service';
import {Author} from '../../../models/author';
@Component({
selector: 'app-update-modal',
standalone: true,
imports: [
Dialog,
PostFormComponent
],
templateUrl: './update-modal.component.html',
styleUrl: './update-modal.component.css'
})
export class UpdateModalComponent {
actualAuthor: Author | undefined;
opened: boolean = true;
@Input({required: true}) post: Post | undefined;
@Output() updatedPost: EventEmitter<Post> = new EventEmitter<Post>();
constructor(private authService: AuthService) {
this.authService.getAuthenticatedAuthor();
}
onSubmit(updatedPost: Post) {
this.updatedPost.emit(updatedPost);
this.opened = false
}
}

View File

@ -1,13 +1,20 @@
<div>
<form [formGroup]="form" (ngSubmit)="onSubmit()">
<label for="title">Titre du post</label>
<input [(ngModel)]="title" id="title" type="text" pInputText formControlName="title" />
<p-floatlabel variant="on">
<input [(ngModel)]="title" id="title" type="text" pInputText formControlName="title"/>
<label for="title">Titre du post</label>
</p-floatlabel>
<label for="category">Catégorie du post</label>
<input [(ngModel)]="category" pInputText id="category" formControlName="category" type="text" />
<p-floatlabel variant="on">
<input [(ngModel)]="category" pInputText id="category" formControlName="category" type="text"/>
<label for="category">Catégorie du post</label>
</p-floatlabel>
<p-floatlabel variant="on">
<textarea pTextarea id="desc" rows="5" cols="30" pSize="large" formControlName="description"></textarea>
<label for="desc">Description du post</label>
</p-floatlabel>
<label for="desc">Description du post</label>
<textarea [(ngModel)]="description" formControlName="description" id="desc" pInputTextarea></textarea>
<label>Image descriptive du post</label>
<p-fileUpload
@ -28,7 +35,43 @@
</p-fileUpload>
<label>Contenu du post</label>
<p-editor [(ngModel)]="body" formControlName="body" [modules]="editorModules" [style]="{ height: '320px' }">
<p-editor [(ngModel)]="body" formControlName="body" [style]="{ height: '320px' }">
<ng-template #header>
<span class="ql-formats">
<!-- <button type="button" class="ql-list" value="ordered"></button>-->
<!-- <button type="button" class="ql-bullet" value="bullet"></button>-->
<select class="ql-header">
<option value="1">Titre 1</option>
<option value="2">Titre 2</option>
<option value="3">Titre 3</option>
<option value="4">Titre 4</option>
<option value="5">Titre 5</option>
<option value="6">Titre 6</option>
<option value="">Normal</option>
</select>
<button class="ql-bold"></button>
<button class="ql-italic"></button>
<button class="ql-underline"></button>
<button class="ql-strike"></button>
<span class="ql-formats">
<select class="ql-color"></select>
<select class="ql-background"></select>
</span>
<span class="ql-formats">
<button class="ql-script" value="sub"></button>
<button class="ql-script" value="super"></button>
</span>
<span class="ql-formats">
<button class="ql-blockquote"></button>
<button class="ql-code-block"></button>
</span>
<button type="button" class="ql-list" value="bullet"></button>
<button type="button" class="ql-list" value="ordered"></button>
<button type="button" class="ql-link" aria-label="Link"></button>
<button type="button" class="ql-image" aria-label="Image"></button>
<button type="button" class="ql-video" aria-label="Video"></button>
</span>
</ng-template>
</p-editor>
<p-button

View File

@ -1,7 +1,6 @@
import {Component, Input, OnDestroy} from '@angular/core';
import {Component, EventEmitter, Input, OnDestroy, Output} from '@angular/core';
import {FormBuilder, FormGroup, ReactiveFormsModule, Validators} from '@angular/forms';
import {InputTextModule} from 'primeng/inputtext';
import {InputTextareaModule} from 'primeng/inputtextarea';
import {FileSelectEvent, FileUploadModule} from 'primeng/fileupload';
import {mergeMap, Subscription} from 'rxjs';
import {PostService} from '../../services/post.service';
@ -11,6 +10,10 @@ import {Router} from '@angular/router';
import {Author} from '../../models/author';
import {AuthorService} from '../../services/author.service';
import {AuthService} from '../../auth.service';
import {Button} from 'primeng/button';
import {Textarea} from 'primeng/textarea';
import {FloatLabel} from 'primeng/floatlabel';
import {Post} from '../../models/post';
@Component({
selector: 'app-post-form',
@ -18,9 +21,11 @@ import {AuthService} from '../../auth.service';
imports: [
ReactiveFormsModule,
InputTextModule,
InputTextareaModule,
FileUploadModule,
EditorModule
EditorModule,
Button,
Textarea,
FloatLabel
],
templateUrl: './post-form.component.html',
styleUrls: ['./post-form.component.css']
@ -33,17 +38,10 @@ export class PostFormComponent implements OnDestroy {
@Input() category: string = '';
@Input() description: string = '';
@Input() body: string = '';
@Output() postUpdate: EventEmitter<Post> = new EventEmitter();
subs: Subscription[] = [];
form: FormGroup;
uploadedFile: File | undefined;
editorModules = {
toolbar: [
['bold', 'italic', 'underline', 'code'], // Styles de texte
[{header: [2, false]}], // Permet d'ajouter un `<h2>`
[{list: 'ordered'}, {list: 'bullet'}], // Listes
['link', 'image', 'video'], // Ajout de liens et images
],
};
constructor(
private formBuilder: FormBuilder,
@ -105,12 +103,13 @@ export class PostFormComponent implements OnDestroy {
if (this.isUpdateMode && this.postId) {
this.subs.push(
this.postService.updatePost(this.postId, postData, this.authService.getAuthenticatedAuthorToken()).pipe(
this.postService.updatePost(this.postId, postData, this.authService.getAuthenticatedAuthorToken()!).pipe(
mergeMap((_) => {
return this.postService.changeIllustration(this.postId, this.uploadedFile, this.authService.getAuthenticatedAuthorToken());
return this.postService.changeIllustration(this.postId, this.uploadedFile, this.authService.getAuthenticatedAuthorToken()!);
})
).subscribe({
next: (_) => {
this.postUpdate.emit(_);
this.successMessage('Succès', 'Post mis à jour avec succès')
},
error: (err) => this.failureMessage('Erreur', err.error.message)
@ -118,11 +117,11 @@ export class PostFormComponent implements OnDestroy {
);
} else {
this.subs.push(
this.postService.createPost(postData, this.authService.getAuthenticatedAuthorToken()).pipe(
this.postService.createPost(postData, this.authService.getAuthenticatedAuthorToken()!).pipe(
mergeMap(post =>
this.authorService.attributePost(this.actualAuthor?.id, post.id, this.authService.getAuthenticatedAuthorToken()).pipe(
this.authorService.attributePost(this.actualAuthor?.id, post.id, this.authService.getAuthenticatedAuthorToken()!).pipe(
mergeMap((_) =>
this.postService.changeIllustration(post.id, this.uploadedFile, this.authService.getAuthenticatedAuthorToken()),
this.postService.changeIllustration(post.id, this.uploadedFile, this.authService.getAuthenticatedAuthorToken()!),
)
)
)
@ -140,6 +139,7 @@ export class PostFormComponent implements OnDestroy {
}
private transformYouTubeLinksToIframes(html: string): string {
// Magie noire
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) => {
return `<iframe width="560" height="315" src="https://www.youtube.com/embed/${videoId}" frameborder="0" allowfullscreen></iframe>`;

View File

@ -5,7 +5,7 @@
<span>{{ category }}</span>
<em>Publié le {{ date | date : "dd/MM/yyyy à HH:mm" }}</em>
<span class="desc">{{ description }}</span>
<p-button routerLink="post/{{ postId }}" label="Lire la suite"/>
<p-button routerLink="post/{{ postId }}" >Lire la suite</p-button>
<a routerLink="/profile/{{ authorId }}" class="user-profile">
@if (authorProfilePicture) {
<p-avatar image="data:image/jpeg;base64,{{ authorProfilePicture }}" shape="circle" styleClass="mr-2"

View File

@ -4,16 +4,17 @@ import {CardModule} from 'primeng/card';
import {DatePipe} from '@angular/common';
import {RouterLink} from '@angular/router';
import {AvatarModule} from 'primeng/avatar';
import {MatButton, MatFabButton} from '@angular/material/button';
@Component({
selector: 'app-post-home',
standalone: true,
imports: [
Button,
CardModule,
DatePipe,
RouterLink,
AvatarModule
AvatarModule,
Button,
],
templateUrl: './post-home.component.html',
styleUrl: './post-home.component.css'

View File

@ -37,7 +37,7 @@ export class RegisterFormComponent implements OnDestroy {
];
subs: Subscription[] = [];
form: FormGroup;
actualAuthor: Author | undefined;
actualAuthor: string | undefined;
constructor(private formBuilder: FormBuilder,
private authorService: AuthorService,
@ -45,8 +45,9 @@ export class RegisterFormComponent implements OnDestroy {
private messageService: MessageService,
private authService: AuthService,
) {
if (!(this.authService.isSessionExpired()) && this.authService.isAuthenticated()) {
this.actualAuthor = this.authService.getAuthenticatedAuthor();
const authenticatedAuthor = this.authService.getAuthenticatedAuthorToken();
if (!(this.authService.isSessionExpired()) && this.authService.isAuthenticated() && authenticatedAuthor) {
this.actualAuthor = authenticatedAuthor;
}
this.form = this.formBuilder.group({
username: ['', [Validators.required, Validators.maxLength(255)]],
@ -83,7 +84,7 @@ export class RegisterFormComponent implements OnDestroy {
this.username,
this.password,
this.role,
this.authService.getAuthenticatedAuthorToken()).subscribe({
this.authService.getAuthenticatedAuthorToken()!).subscribe({
next: (author: Author) => {
this.successMessage('Succès', `Auteur ${author.name} créé avec succès`);
this.createdAuthor.emit(author);

View File

@ -7,7 +7,6 @@ import {Subscription, switchMap} from 'rxjs';
import {AuthorService} from '../../services/author.service';
import {MessageService} from 'primeng/api';
import {FileSelectEvent, FileUploadModule} from 'primeng/fileupload';
import {CookieService} from 'ngx-cookie-service';
import {Author} from '../../models/author';
import {Router} from '@angular/router';
import {AuthService} from '../../auth.service';
@ -38,7 +37,6 @@ export class UpdateProfileFormComponent implements OnDestroy {
constructor(private formBuilder: FormBuilder,
private authorService: AuthorService,
private messageService: MessageService,
private cookieService: CookieService,
private authService: AuthService,
private router: Router,
) {
@ -80,7 +78,7 @@ export class UpdateProfileFormComponent implements OnDestroy {
}
onSubmit() {
const token: string = this.authService.getAuthenticatedAuthorToken();
const token = this.authService.getAuthenticatedAuthorToken();
if (this.form.valid && token && this.password === this.passwordConfirm) {
const newUsername = this.form.value.username;
if (this.uploadedFile) {
@ -92,7 +90,7 @@ export class UpdateProfileFormComponent implements OnDestroy {
next: (author: Author) => {
this.successMessage("Mise à jour réussie", "Profil mit à jour avec succès");
this.updatedAuthorEvent.emit(author);
this.cookieService.set('author', JSON.stringify(author));
sessionStorage.setItem('author', JSON.stringify(author));
this.router.navigate(['/']);
},
error: (err) => {
@ -104,7 +102,7 @@ export class UpdateProfileFormComponent implements OnDestroy {
next: (author: Author) => {
this.successMessage("Mise à jour réussie", "Profil mit à jour avec succès");
this.updatedAuthorEvent.emit(author);
this.cookieService.set('author', JSON.stringify(author));
sessionStorage.setItem('author', JSON.stringify(author));
this.router.navigate(['/']);
},
error: (err) => {

View File

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

View File

@ -1,11 +1,9 @@
import {CanActivateFn, Router} from '@angular/router';
import {inject} from '@angular/core';
import {CookieService} from 'ngx-cookie-service';
export const authGuard: CanActivateFn = (route, state) => {
const router = inject(Router);
const cookieService = inject(CookieService);
if (cookieService.check("author") || cookieService.check("token")) {
if (sessionStorage.getItem("author") !== null || sessionStorage.getItem("token") !== null) {
router.navigate(['/']);
}

View File

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

View File

@ -33,7 +33,7 @@
</td>
<td>{{ author.role }}</td>
<td>
<p-button icon="pi pi-pencil" (click)="openDialog(updateDialogVisibility, rowIndex)" severity="warning"
<p-button icon="pi pi-pencil" (click)="openDialog(updateDialogVisibility, rowIndex)" severity="warn"
label="Modifier"/>
<p-dialog header='Modifier "{{ author.name }}"' [modal]="true" [(visible)]="updateDialogVisibility[rowIndex]">
<app-register-form [adminForm]="true" [username]="author.name">

View File

@ -13,6 +13,6 @@
[authorProfilePicture]="post.authorProfilePicture"/>
}
} @else {
<h1>Aucun post n'a été créé pour l'instant</h1>
<app-loading></app-loading>
}
</div>

View File

@ -8,6 +8,7 @@ import {PostService} from '../../services/post.service';
import {PostHomeComponent} from '../../components/post-home/post-home.component';
import {AuthorWithPost} from '../../models/author-with-post';
import {AuthService} from '../../auth.service';
import {LoadingComponent} from '../../components/loading/loading.component';
@Component({
selector: 'app-home',
@ -17,6 +18,7 @@ import {AuthService} from '../../auth.service';
HeaderComponent,
ToastModule,
PostHomeComponent,
LoadingComponent,
],
templateUrl: './home.component.html',
styleUrl: './home.component.css'
@ -29,9 +31,9 @@ export class HomeComponent implements OnDestroy {
constructor(
private postService: PostService,
private authService: AuthService) {
if (!(this.authService.isSessionExpired()) && this.authService.isAuthenticated()) {
this.actualAuthor = this.authService.getAuthenticatedAuthor();
const authenticatedAuthor = this.authService.getAuthenticatedAuthor();
if (!(this.authService.isSessionExpired()) && this.authService.isAuthenticated() && authenticatedAuthor) {
this.actualAuthor = authenticatedAuthor;
} else {
this.authService.checkSessionExpiration();
}

View File

@ -5,10 +5,7 @@
<label for="username">Nom d'utilisateur</label>
<input type="text" id="username" pInputText [(ngModel)]="name"/>
<label for="password">Mot de passe</label>
<input type="password" id="password" pInputText [(ngModel)]="password"/>
<label for="confirm-password">Confirmez le mot de passe</label>
<input type="password" id="confirm-password" pInputText
[(ngModel)]="confirmPassword" (keyup.enter)="sendLogins()"/>
<input type="password" id="password" pInputText [(ngModel)]="password" (keyup.enter)="sendLogins()"/>
<p-button
class="send-button"
label="Se connecter"

View File

@ -7,7 +7,6 @@ import {ToastModule} from 'primeng/toast';
import {MessageService} from 'primeng/api';
import {Author} from '../../models/author';
import {Subscription, switchMap} from 'rxjs';
import {CookieService} from 'ngx-cookie-service';
import {HeaderComponent} from '../../components/header/header.component';
import {Router} from '@angular/router';
import {ConfigurationService} from '../../configuration.service';
@ -30,56 +29,43 @@ 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,
private configurationService: ConfigurationService,) {}
private configurationService: ConfigurationService,) {
}
sendLogins(): void {
if (this.password === this.confirmPassword) {
this.subs.push
(
this.authorService.login(this.name, this.password).pipe(
switchMap((tokenObj: any) => {
this.cookieService.delete('token', '/', this.configurationService.getDomain())
this.cookieService.set("token", tokenObj.token, {
domain: this.configurationService.getDomain(),
secure: true,
path: '/'
this.subs.push
(
this.authorService.login(this.name, this.password).pipe(
switchMap((tokenObj: any) => {
// sessionStorage.removeItem('token');
sessionStorage.setItem('token', tokenObj.token);
return this.authorService.me(tokenObj.token)
}))
.subscribe({
next: (author: Author) => {
// sessionStorage.removeItem('author');
sessionStorage.setItem('author', JSON.stringify(author));
sessionStorage.setItem('token-expiration-date', DateTime.now().plus({millisecond: this.configurationService.getTokenTTL()}).toISO())
this.getAuthorCookie();
this.router.navigate(['/']).then(() => {
this.successMessage('Connecté avec succès', 'Heureux de vous revoir ' + this.actualAuthor?.name)
});
return this.authorService.me(tokenObj.token)
}))
.subscribe({
next: (author: Author) => {
this.cookieService.delete('author', '/', this.configurationService.getDomain())
this.cookieService.set("author", JSON.stringify(author), {
domain: this.configurationService.getDomain(),
secure : true,
path: '/' });
this.cookieService.set('token-expiration-date', DateTime.now().plus({millisecond: this.configurationService.getTokenTTL()}).toISO(), {
domain: this.configurationService.getDomain(),
secure: true,
path: '/',
})
this.getAuthorCookie();
this.router.navigate(['/']).then(() => {
this.successMessage('Connecté avec succès', 'Heureux de vous revoir ' + this.actualAuthor?.name)
});
},
error: (err) => this.failureMessage('Erreur de connexion', err.error.message)
})
);
} else {
this.failureMessage('Erreur de connexion', 'Les deux mots de passe ne correspondent pas')
}
},
error: (err) => this.failureMessage('Erreur de connexion', err.error.message)
})
);
}
getAuthorCookie(): void {
this.actualAuthor = JSON.parse(this.cookieService.get("author"));
const authorStr = sessionStorage.getItem('author');
if (authorStr) {
this.actualAuthor = JSON.parse(authorStr);
}
}
successMessage(summary: string, detail: string): void {

View File

@ -1,9 +1,7 @@
import {Component, OnInit} from '@angular/core';
import {CookieService} from 'ngx-cookie-service';
import {HeaderComponent} from '../../components/header/header.component';
import {Router} from '@angular/router';
import {MessageService} from 'primeng/api';
import {ConfigurationService} from '../../configuration.service';
@Component({
selector: 'app-logout',
@ -14,19 +12,16 @@ import {ConfigurationService} from '../../configuration.service';
templateUrl: './logout.component.html',
styleUrl: './logout.component.css'
})
export class LogoutComponent implements OnInit{
export class LogoutComponent implements OnInit {
constructor(private messageService: MessageService,
private router: Router) {
}
constructor(private cookieService: CookieService,
private messageService: MessageService,
private router: Router,
private configurationService: ConfigurationService,) { }
ngOnInit(): void {
const routes: string[] = ['/', '/login', '/register', '/logout', '/profile', '/post', '/new-post', '/admin']
Object.keys(this.cookieService.getAll()).forEach(key => {
routes.forEach(route => {
this.cookieService.delete(key, route, this.configurationService.getDomain());
})
});
sessionStorage.removeItem("author");
sessionStorage.removeItem("token");
sessionStorage.removeItem("token-expiration-date");
this.router.navigate(['/']).then(() => this.successMessage('Déconnexion', 'Vous avez été deconnecté avec succès'));
}

View File

@ -23,29 +23,10 @@
<td>{{ post.publicationDate | date: "dd/MM/yyyy à HH:mm" }}</td>
<td>{{ post.description }}</td>
<td>
<p-button icon="pi pi-eye" (click)="openDialog(previewDialogVisibility, rowIndex)" severity="info"
label="Prévisualiser"/>
<p-dialog class="preview-dialog" header='Prévisualisation de "{{ post.title }}"' [modal]="true"
[(visible)]="previewDialogVisibility[rowIndex]">
<app-post-home [title]="post.title"
[description]="post.description"
[category]="post.category"
[date]="post.publicationDate"
[illustration]="post.illustration"/>
</p-dialog>
<p-button icon="pi pi-eye" (click)="openDialogPreview(post)" severity="info" label="Prévisualiser"/>
</td>
<td>
<p-button icon="pi pi-pencil" (click)="openDialog(updateDialogVisibility, rowIndex)" severity="warning"
label="Modifier"/>
<p-dialog header='Modifier "{{ post.title }}"' [modal]="true" [(visible)]="updateDialogVisibility[rowIndex]">
<app-post-form [actualAuthor]="actualAuthor"
[postId]="post.id"
[isUpdateMode]="true"
[title]="post.title"
[category]="post.category"
[description]="post.description"
[body]="post.body"/>
</p-dialog>
<p-button icon="pi pi-pencil" (click)="openDialogUpdate(post)" severity="warn" label="Modifier"/>
</td>
<td>
<p-button icon="pi pi-trash" (click)="openDialog(deleteDialogVisibility, rowIndex)" severity="danger"

View File

@ -1,4 +1,4 @@
import {Component, OnDestroy} from '@angular/core';
import {Component, OnDestroy, ViewContainerRef} from '@angular/core';
import {HeaderComponent} from '../../components/header/header.component';
import {TableModule} from 'primeng/table';
import {AuthorService} from '../../services/author.service';
@ -14,6 +14,8 @@ import {PostHomeComponent} from '../../components/post-home/post-home.component'
import {PostService} from '../../services/post.service';
import {PostFormComponent} from "../../components/post-form/post-form.component";
import {AuthService} from '../../auth.service';
import {PreviewModalComponent} from '../../components/modal/preview-modal/preview-modal.component';
import {UpdateModalComponent} from '../../components/modal/update-modal/update-modal.component';
@Component({
selector: 'app-my-posts',
@ -33,18 +35,22 @@ import {AuthService} from '../../auth.service';
})
export class MyPostsComponent implements OnDestroy {
subs: Subscription[] = [];
previewDialogVisibility: boolean[] = [];
updateDialogVisibility: boolean[] = [];
deleteDialogVisibility: boolean[] = [];
posts: Post[] = [];
actualAuthor: Author;
actualAuthor: Author | undefined;
constructor(private authService: AuthService,
private postService: PostService,
private viewContainer: ViewContainerRef,
private authorService: AuthorService,
private messageService: MessageService) {
this.actualAuthor = this.authService.getAuthenticatedAuthor();
const authenticatedAuthor = this.authService.getAuthenticatedAuthor();
if (authenticatedAuthor) {
this.actualAuthor = authenticatedAuthor;
this.authorService.getAuthorAvatar(this.actualAuthor.id).subscribe(avatar => this.actualAuthor!.profilePicture = avatar);
}
this.updatePosts();
}
@ -59,8 +65,9 @@ export class MyPostsComponent implements OnDestroy {
}
updatePosts(): void {
if (!(this.authService.isSessionExpired()) && this.authService.isAuthenticated()) {
this.authorService.getAuthorsPosts(this.actualAuthor?.id, this.authService.getAuthenticatedAuthorToken()).subscribe({
const authorToken = this.authService.getAuthenticatedAuthorToken()
if (!(this.authService.isSessionExpired()) && this.authService.isAuthenticated() && authorToken) {
this.authorService.getAuthorsPosts(this.actualAuthor?.id, authorToken).subscribe({
next: posts => this.posts = posts,
error: error => this.failureMessage("Erreur", error.error.message),
}
@ -71,13 +78,16 @@ export class MyPostsComponent implements OnDestroy {
}
deletePost(id: bigint, rowIndex: number) {
this.postService.deletePost(id, this.authService.getAuthenticatedAuthorToken()).subscribe({
next: (_) => {
this.updatePosts()
this.successMessage("Post supprimé", "Ce post a été supprimé avec succès")
},
error: error => this.failureMessage("Erreur", error.error.message),
});
const authorToken = this.authService.getAuthenticatedAuthorToken()
if (authorToken) {
this.postService.deletePost(id, authorToken).subscribe({
next: (_) => {
this.updatePosts()
this.successMessage("Post supprimé", "Ce post a été supprimé avec succès")
},
error: error => this.failureMessage("Erreur", error.error.message),
});
}
this.closeDialog(this.deleteDialogVisibility, rowIndex)
}
@ -91,6 +101,24 @@ export class MyPostsComponent implements OnDestroy {
});
}
openDialogPreview(post: Post): void {
const modalInstance = this.viewContainer.createComponent(PreviewModalComponent);
modalInstance.setInput("post", post)
modalInstance.setInput("username", this.actualAuthor?.name)
modalInstance.setInput("profilePicture", this.actualAuthor?.profilePicture)
}
openDialogUpdate(post: Post): void {
const modalInstance = this.viewContainer.createComponent(UpdateModalComponent);
modalInstance.setInput("post", post)
modalInstance.instance.updatedPost.subscribe(post => {
console.log(this.posts.map(a => a.id).indexOf(post.id))
this.posts[this.posts.map(a => a.id).indexOf(post.id)] = post
this.posts = [... this.posts]
modalInstance.destroy();
});
}
openDialog(dialogBooleanTab: boolean[], index: number) {
dialogBooleanTab[index] = true;
}

View File

@ -2,7 +2,6 @@ import {Component, EventEmitter, OnDestroy} from '@angular/core';
import {HeaderComponent} from '../../components/header/header.component';
import {FormBuilder, FormGroup, ReactiveFormsModule, Validators} from '@angular/forms';
import {InputTextModule} from 'primeng/inputtext';
import {InputTextareaModule} from 'primeng/inputtextarea';
import {FileSelectEvent, FileUploadModule} from 'primeng/fileupload';
import {mergeMap, Subscription} from 'rxjs';
import {PostService} from '../../services/post.service';
@ -21,7 +20,6 @@ import {AuthService} from '../../auth.service';
HeaderComponent,
ReactiveFormsModule,
InputTextModule,
InputTextareaModule,
FileUploadModule,
EditorModule,
PostFormComponent,
@ -30,7 +28,6 @@ import {AuthService} from '../../auth.service';
styleUrl: './new-post.component.css'
})
export class NewPostComponent implements OnDestroy {
isSessionExpired: EventEmitter<boolean> = new EventEmitter<boolean>();
subs: Subscription[] = []
actualAuthor: Author | undefined;
uploadedFile: File | undefined;
@ -40,7 +37,7 @@ export class NewPostComponent implements OnDestroy {
private postService: PostService,
private authorService: AuthorService,
private messageService: MessageService,
private authService : AuthService,
private authService: AuthService,
private router: Router) {
this.form = this.formBuilder.group({
description: ['', [Validators.required, Validators.maxLength(512)]],
@ -49,7 +46,10 @@ export class NewPostComponent implements OnDestroy {
category: ['', [Validators.required, Validators.maxLength(50)]],
});
if (!(this.authService.isSessionExpired()) && this.authService.isAuthenticated()) {
this.actualAuthor = this.authService.getAuthenticatedAuthor();
const authenticatedAuthor = this.authService.getAuthenticatedAuthor();
if (authenticatedAuthor) {
this.actualAuthor = authenticatedAuthor;
}
} else {
this.authService.checkSessionExpiration();
}
@ -72,26 +72,31 @@ export class NewPostComponent implements OnDestroy {
category: formData.category as string
};
this.subs.push(
this.postService.createPost(postToPost, this.authService.getAuthenticatedAuthorToken()).pipe(
mergeMap(post =>
this.authorService.attributePost(this.actualAuthor?.id, post.id, this.authService.getAuthenticatedAuthorToken()).pipe(
mergeMap((_) =>
this.postService.changeIllustration(post.id, this.uploadedFile, this.authService.getAuthenticatedAuthorToken()),
const authenticatedAuthor = this.authService.getAuthenticatedAuthorToken();
if (authenticatedAuthor) {
this.subs.push(
this.postService.createPost(postToPost, authenticatedAuthor).pipe(
mergeMap(post =>
this.authorService.attributePost(this.actualAuthor?.id, post.id, authenticatedAuthor).pipe(
mergeMap((_) =>
this.postService.changeIllustration(post.id, this.uploadedFile, authenticatedAuthor),
)
)
)
)
).subscribe({
next: () => {
this.router.navigate(['/']).then(() => {
this.successMessage('Succès', 'Post créé avec succès')
});
},
error: (err) => {
this.failureMessage('Erreur', err.error.message);
}
})
);
).subscribe({
next: () => {
this.router.navigate(['/']).then(() => {
this.successMessage('Succès', 'Post créé avec succès')
});
},
error: (err) => {
this.failureMessage('Erreur', err.error.message);
}
})
);
} else {
console.error("Profil mal chargé")
}
}
}

View File

@ -49,7 +49,12 @@ export class PostComponent {
private authService: AuthService,) {
this.route.paramMap.subscribe(params => {
if (!(this.authService.isSessionExpired()) && this.authService.isAuthenticated()) {
this.actualAuthor = this.authService.getAuthenticatedAuthor();
const authenticatedAuthor = this.authService.getAuthenticatedAuthor();
if (authenticatedAuthor) {
this.actualAuthor = authenticatedAuthor;
} else {
console.error('Profil mal chargé');
}
} else {
this.authService.checkSessionExpiration();
}

View File

@ -30,5 +30,5 @@
</div>
</div>
} @else {
<h1>Loading...</h1>
<app-loading></app-loading>
}

View File

@ -10,6 +10,7 @@ import {Button} from 'primeng/button';
import {DialogModule} from 'primeng/dialog';
import {UpdateProfileFormComponent} from '../../components/update-profile-form/update-profile-form.component';
import {AuthService} from '../../auth.service';
import {LoadingComponent} from '../../components/loading/loading.component';
@Component({
selector: 'app-profile',
@ -21,6 +22,7 @@ import {AuthService} from '../../auth.service';
Button,
DialogModule,
UpdateProfileFormComponent,
LoadingComponent,
],
templateUrl: './profile.component.html',
styleUrl: './profile.component.css'
@ -43,7 +45,12 @@ export class ProfileComponent implements OnDestroy {
}));
})
if (!(this.authService.isSessionExpired()) && this.authService.isAuthenticated()) {
this.actualAuthor = this.authService.getAuthenticatedAuthor();
const authenticatedAuthor = this.authService.getAuthenticatedAuthor();
if (authenticatedAuthor) {
this.actualAuthor = authenticatedAuthor;
} else {
console.error("Profil mal chargé");
}
} else {
this.authService.checkSessionExpiration();
}

21
src/app/preset.ts Normal file
View File

@ -0,0 +1,21 @@
import {definePreset} from '@primeng/themes';
import Aura from '@primeng/themes/aura';
export const myPreset = definePreset(Aura, {
semantic: {
primary: {
50: '{indigo.50}',
100: '{indigo.100}',
200: '{indigo.200}',
300: '{indigo.300}',
400: '{indigo.400}',
500: '{indigo.500}',
600: '{indigo.600}',
700: '{indigo.700}',
800: '{indigo.800}',
900: '{indigo.900}',
950: '{indigo.950}'
}
}
});

View File

@ -62,6 +62,11 @@ export class AuthorService {
}
}
getAvatar(id: string): Observable<string> {
return this.httpClient.get(`${this.apiUrl}/${id}/avatar`, { responseType: 'text' });
}
getAuthor(id: string | null): Observable<Author> {
if (id) {
return this.httpClient.get<Author>(`${this.apiUrl}/${id}`);
@ -89,6 +94,14 @@ export class AuthorService {
'Authorization': `Bearer ${token}`
})
}
return this.httpClient.post<Author>(`${this.apiUrl}/register/admin`, {name: username, password: password, role: role}, httpOptions);
return this.httpClient.post<Author>(`${this.apiUrl}/register/admin`, {
name: username,
password: password,
role: role
}, httpOptions);
}
getAuthorAvatar(id: string) {
return this.httpClient.get<string>(`${this.apiUrl}/${id}/avatar`);
}
}

BIN
src/assets/icon.jpg Normal file

Binary file not shown.

After

(image error) Size: 32 KiB

View File

@ -7,9 +7,11 @@
<base href="/">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="icon" type="image/x-icon" href="icon.jpg">
<link href="https://fonts.googleapis.com/css2?family=Roboto:wght@300;400;500&display=swap" rel="stylesheet">
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
</head>
<body>
<body class="mat-typography">
<app-root></app-root>
<footer class="footer">
<p class="footer-creator">Site web réalisé par <strong>Guams</strong>.</p>

View File

@ -1,4 +1,4 @@
@import '../node_modules/primeng/resources/themes/lara-light-indigo/theme.css';
/*@import '../node_modules/primeng/resources/themes/lara-light-indigo/theme.css';*/
@import '../node_modules/primeicons/primeicons.css';
@import '../node_modules/quill/dist/quill.bubble.css';
@import '../node_modules/quill/dist/quill.snow.css';
@ -53,3 +53,6 @@ app-root {
.footer-link:hover {
text-decoration: underline;
}
html, body { height: 100%; }
body { margin: 0; font-family: Roboto, "Helvetica Neue", sans-serif; }