1 import Cookies from 'js-cookie';
2 import { User, Claims, LoginResponse } from '../interfaces';
3 import { setTheme } from '../utils';
4 import jwt_decode from 'jwt-decode';
5 import { Subject, BehaviorSubject } from 'rxjs';
7 export class UserService {
8 private static _instance: UserService;
10 public claims: Claims;
11 public jwtSub: Subject<string> = new Subject<string>();
12 public unreadCountSub: BehaviorSubject<number> = new BehaviorSubject<number>(
16 private constructor() {
17 let jwt = Cookies.get('jwt');
22 console.log('No JWT cookie found.');
26 public login(res: LoginResponse) {
27 this.setClaims(res.jwt);
28 Cookies.set('jwt', res.jwt, { expires: 365 });
29 console.log('jwt cookie set');
33 this.claims = undefined;
34 this.user = undefined;
35 Cookies.remove('jwt');
37 this.jwtSub.next(undefined);
38 console.log('Logged out.');
41 public get auth(): string {
42 return Cookies.get('jwt');
45 private setClaims(jwt: string) {
46 this.claims = jwt_decode(jwt);
47 this.jwtSub.next(jwt);
50 public static get Instance() {
51 return this._instance || (this._instance = new this());