]> Untitled Git - lemmy-ui.git/blob - src/shared/services/UserService.ts
Somewhat working webpack. Sponsors and communities pages done.
[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 { setTheme } from '../utils';
5 import jwt_decode from 'jwt-decode';
6 import { Subject, BehaviorSubject } from 'rxjs';
7
8 interface Claims {
9   id: number;
10   iss: string;
11 }
12
13 export class UserService {
14   private static _instance: UserService;
15   public user: User;
16   public claims: Claims;
17   public jwtSub: Subject<string> = new Subject<string>();
18   public unreadCountSub: BehaviorSubject<number> = new BehaviorSubject<number>(
19     0
20   );
21
22   private constructor() {
23     let jwt = IsomorphicCookie.load('jwt');
24     if (jwt) {
25       this.setClaims(jwt);
26     } else {
27       // setTheme();
28       console.log('No JWT cookie found.');
29     }
30   }
31
32   public login(res: LoginResponse) {
33     this.setClaims(res.jwt);
34     IsomorphicCookie.save('jwt', res.jwt, { expires: 365 });
35     console.log('jwt cookie set');
36   }
37
38   public logout() {
39     this.claims = undefined;
40     this.user = undefined;
41     IsomorphicCookie.remove('jwt');
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);
53     this.jwtSub.next(jwt);
54   }
55
56   public static get Instance() {
57     return this._instance || (this._instance = new this());
58   }
59 }