]> Untitled Git - lemmy.git/blob - ui/src/services/UserService.ts
routes.api: fix get_captcha endpoint (#1135)
[lemmy.git] / ui / src / services / UserService.ts
1 import Cookies from 'js-cookie';
2 import { User, LoginResponse } from 'lemmy-js-client';
3 import { setTheme } from '../utils';
4 import jwt_decode from 'jwt-decode';
5 import { Subject, BehaviorSubject } from 'rxjs';
6
7 interface Claims {
8   id: number;
9   iss: string;
10 }
11
12 export class UserService {
13   private static _instance: UserService;
14   public user: User;
15   public claims: Claims;
16   public jwtSub: Subject<string> = new Subject<string>();
17   public unreadCountSub: BehaviorSubject<number> = new BehaviorSubject<number>(
18     0
19   );
20
21   private constructor() {
22     let jwt = Cookies.get('jwt');
23     if (jwt) {
24       this.setClaims(jwt);
25     } else {
26       setTheme();
27       console.log('No JWT cookie found.');
28     }
29   }
30
31   public login(res: LoginResponse) {
32     this.setClaims(res.jwt);
33     Cookies.set('jwt', res.jwt, { expires: 365 });
34     console.log('jwt cookie set');
35   }
36
37   public logout() {
38     this.claims = undefined;
39     this.user = undefined;
40     Cookies.remove('jwt');
41     setTheme();
42     this.jwtSub.next();
43     console.log('Logged out.');
44   }
45
46   public get auth(): string {
47     return Cookies.get('jwt');
48   }
49
50   private setClaims(jwt: string) {
51     this.claims = jwt_decode(jwt);
52     this.jwtSub.next(jwt);
53   }
54
55   public static get Instance() {
56     return this._instance || (this._instance = new this());
57   }
58 }