]> Untitled Git - lemmy-ui.git/blob - src/shared/services/UserService.ts
Updating deps.
[lemmy-ui.git] / src / shared / services / UserService.ts
1 // import Cookies from 'js-cookie';
2 import IsomorphicCookie from 'isomorphic-cookie';
3 import { User, LoginResponse } from 'lemmy-js-client';
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     if (this.auth) {
23       this.setClaims(this.auth);
24     } else {
25       // setTheme();
26       console.log('No JWT cookie found.');
27     }
28   }
29
30   public login(res: LoginResponse) {
31     let expires = new Date();
32     expires.setDate(expires.getDate() + 365);
33     IsomorphicCookie.save('jwt', res.jwt, { expires, secure: false });
34     console.log('jwt cookie set');
35     this.setClaims(res.jwt);
36   }
37
38   public logout() {
39     IsomorphicCookie.remove('jwt', { secure: false });
40     this.claims = undefined;
41     this.user = undefined;
42     // setTheme();
43     this.jwtSub.next();
44     console.log('Logged out.');
45   }
46
47   public get auth(): string {
48     return IsomorphicCookie.load('jwt');
49   }
50
51   private setClaims(jwt: string) {
52     this.claims = jwt_decode(jwt) as Claims;
53     this.jwtSub.next(jwt);
54   }
55
56   public static get Instance() {
57     return this._instance || (this._instance = new this());
58   }
59 }