106 lines
2.8 KiB
TypeScript
106 lines
2.8 KiB
TypeScript
import { inject, Injectable } from "@angular/core";
|
|
import { User } from "../model/User";
|
|
import { UserRestService } from "../rest-services/user/user.rest-service";
|
|
import { RefreshTokenRequest } from "../rest-services/user/model/refresh-token.model";
|
|
|
|
const JWT_PARAM = 'jwt';
|
|
const REFRESH_TOKEN_PARAM = 'refresh-token';
|
|
|
|
interface UserDetails {
|
|
sub: string;
|
|
exp: number;
|
|
email: string;
|
|
pseudo: string;
|
|
roles: string;
|
|
}
|
|
|
|
@Injectable({
|
|
providedIn: 'root'
|
|
})
|
|
export class AuthenticationService {
|
|
|
|
authenticate(token: string, refreshToken: string): void {
|
|
localStorage.setItem(JWT_PARAM, token);
|
|
localStorage.setItem(REFRESH_TOKEN_PARAM, refreshToken);
|
|
}
|
|
|
|
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;
|
|
}
|
|
|
|
getAuthenticatedUser(): User | undefined {
|
|
return this.extractUserFromLocalStorage();
|
|
}
|
|
|
|
getToken(): string | undefined {
|
|
return localStorage.getItem(JWT_PARAM) ?? undefined;
|
|
}
|
|
|
|
getRefreshToken(): string | undefined {
|
|
return localStorage.getItem(REFRESH_TOKEN_PARAM) ?? undefined;
|
|
}
|
|
|
|
isTokenExpired(): boolean {
|
|
let result = false;
|
|
|
|
const userDetails = this.extractUserDetails();
|
|
|
|
if (userDetails) {
|
|
const expirationDate = new Date(userDetails.exp * 1000);
|
|
const now = new Date();
|
|
|
|
result = expirationDate < now;
|
|
}
|
|
|
|
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 decodedTokenPart = atob(tokenParts[1]);
|
|
const userDetails: UserDetails = JSON.parse(decodedTokenPart);
|
|
result = userDetails;
|
|
}
|
|
|
|
return result;
|
|
}
|
|
|
|
private convertToUser(userDetails: UserDetails): User {
|
|
return {
|
|
id: userDetails.sub,
|
|
email: userDetails.email,
|
|
pseudo: userDetails.pseudo,
|
|
roles: userDetails.roles.split(',')
|
|
};
|
|
}
|
|
} |