Add frontend.
This commit is contained in:
@@ -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(',')
|
||||
};
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user