1 import Cookies from 'js-cookie';
2 import { User, LoginResponse } from '../interfaces';
3 import { setTheme } from '../utils';
4 import jwt_decode from 'jwt-decode';
5 import { Subject } from 'rxjs';
7 export class UserService {
8 private static _instance: UserService;
10 public sub: Subject<{ user: User }> = new Subject<{
14 private constructor() {
15 let jwt = Cookies.get('jwt');
20 console.log('No JWT cookie found.');
24 public login(res: LoginResponse) {
25 this.setUser(res.jwt);
26 Cookies.set('jwt', res.jwt, { expires: 365 });
27 console.log('jwt cookie set');
31 this.user = undefined;
32 Cookies.remove('jwt');
34 this.sub.next({ user: undefined });
35 console.log('Logged out.');
38 public get auth(): string {
39 return Cookies.get('jwt');
42 private setUser(jwt: string) {
43 this.user = jwt_decode(jwt);
44 if (this.user.theme != 'darkly') {
45 setTheme(this.user.theme);
47 this.sub.next({ user: this.user });
48 console.log(this.user);
51 public static get Instance() {
52 return this._instance || (this._instance = new this());