summaryrefslogtreecommitdiffstats
path: root/ui/src/services/UserService.ts
blob: b6d8b768675d4cc70791529f8c6166710c9ef710 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
import * as Cookies from 'js-cookie';
import { User, LoginResponse } from '../interfaces';
import { setTheme } from '../utils';
import * as jwt_decode from 'jwt-decode';
import { Subject } from 'rxjs';

export class UserService {
  private static _instance: UserService;
  public user: User;
  public sub: Subject<{ user: User; unreadCount: number }> = new Subject<{
    user: User;
    unreadCount: number;
  }>();

  private constructor() {
    let jwt = Cookies.get('jwt');
    if (jwt) {
      this.setUser(jwt);
    } else {
      if (this.user.theme != 'darkly') {
        setTheme();
      }
      console.log('No JWT cookie found.');
    }
  }

  public login(res: LoginResponse) {
    this.setUser(res.jwt);
    Cookies.set('jwt', res.jwt, { expires: 365 });
    console.log('jwt cookie set');
  }

  public logout() {
    this.user = undefined;
    Cookies.remove('jwt');
    setTheme();
    this.sub.next({ user: undefined, unreadCount: 0 });
    console.log('Logged out.');
  }

  public get auth(): string {
    return Cookies.get('jwt');
  }

  private setUser(jwt: string) {
    this.user = jwt_decode(jwt);
    if (this.user.theme != 'darkly') {
      setTheme(this.user.theme);
    }
    this.sub.next({ user: this.user, unreadCount: 0 });
    console.log(this.user);
  }

  public static get Instance() {
    return this._instance || (this._instance = new this());
  }
}