Add frontend.

This commit is contained in:
Florian THIERRY
2024-03-27 10:28:33 +01:00
parent 431d365d20
commit 13c2cc8118
42 changed files with 13496 additions and 0 deletions

View File

@@ -0,0 +1,4 @@
export interface FormError {
fieldName: string;
errorMessage: string;
}

View File

@@ -0,0 +1,7 @@
export interface User {
id: string;
email: string;
pseudo: string;
photoId?: string;
roles: string[];
}

View File

@@ -0,0 +1,10 @@
export interface LoginRequest {
email?: string;
password?: string;
}
export interface LoginResponse {
tokenType: string,
accessToken: string,
refreshToken: string
}

View File

@@ -0,0 +1,15 @@
import { HttpClient } from "@angular/common/http";
import { Injectable, inject } from "@angular/core";
import { LoginRequest, LoginResponse } from "./model/login.model";
import { lastValueFrom } from "rxjs";
@Injectable({
providedIn: 'root'
})
export class UserRestService {
private httpClient = inject(HttpClient);
login(request: LoginRequest): Promise<LoginResponse> {
return lastValueFrom(this.httpClient.post<LoginResponse>('/api/users/login', request));
}
}

View File

@@ -0,0 +1,73 @@
import { Injectable } from "@angular/core";
import { User } from "../model/User";
const JWT_PARAM = 'jwt';
interface UserDetails {
sub: string;
exp: number;
email: string;
pseudo: string;
roles: string;
}
@Injectable({
providedIn: 'root'
})
export class AuthenticationService {
authenticate(token: string): void {
localStorage.setItem(JWT_PARAM, token);
}
unauthenticate(): void {
localStorage.removeItem(JWT_PARAM);
}
isAuthenticated(): boolean {
let result = false;
const userDetails = this.extractUserDetails();
if (userDetails) {
const authenticationExpiration = new Date(userDetails.exp * 1000);
result = authenticationExpiration > new Date();
}
return result;
}
private extractUserFromLocalStorage(): User | undefined {
let result: User | undefined = undefined;
const userDetails = this.extractUserDetails();
if (userDetails) {
const user = this.convertToUser(userDetails);
result = user;
}
return result;
}
private extractUserDetails(): UserDetails | undefined {
let result: UserDetails | undefined = undefined;
const token = localStorage.getItem(JWT_PARAM);
const tokenParts = token?.split('.');
if (tokenParts?.length === 3 && tokenParts[1].length) {
const userDetails: UserDetails = JSON.parse(tokenParts[1]);
result = userDetails;
}
return result;
}
private convertToUser(userDetails: UserDetails): User {
return {
id: userDetails.sub,
email: userDetails.email,
pseudo: userDetails.pseudo,
roles: userDetails.roles.split(',')
};
}
}

View File

@@ -0,0 +1,5 @@
export function copy<T>(object: T): T {
return JSON.parse(
JSON.stringify(object)
);
}