]> Untitled Git - lemmy.git/blob - ui/src/services/UserService.ts
Remove extra jwt claims (for user settings) (#1025)
[lemmy.git] / ui / src / services / UserService.ts
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';
6
7 export class UserService {
8   private static _instance: UserService;
9   public user: User;
10   public claims: Claims;
11   public jwtSub: Subject<string> = new Subject<string>();
12   public unreadCountSub: BehaviorSubject<number> = new BehaviorSubject<number>(
13     0
14   );
15
16   private constructor() {
17     let jwt = Cookies.get('jwt');
18     if (jwt) {
19       this.setClaims(jwt);
20     } else {
21       setTheme();
22       console.log('No JWT cookie found.');
23     }
24   }
25
26   public login(res: LoginResponse) {
27     this.setClaims(res.jwt);
28     Cookies.set('jwt', res.jwt, { expires: 365 });
29     console.log('jwt cookie set');
30   }
31
32   public logout() {
33     this.claims = undefined;
34     this.user = undefined;
35     Cookies.remove('jwt');
36     setTheme();
37     this.jwtSub.next(undefined);
38     console.log('Logged out.');
39   }
40
41   public get auth(): string {
42     return Cookies.get('jwt');
43   }
44
45   private setClaims(jwt: string) {
46     this.claims = jwt_decode(jwt);
47     this.jwtSub.next(jwt);
48   }
49
50   public static get Instance() {
51     return this._instance || (this._instance = new this());
52   }
53 }