53 lines
1.5 KiB
TypeScript
53 lines
1.5 KiB
TypeScript
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);
|
|
}
|
|
}
|
|
}
|