]> Untitled Git - lemmy-ui.git/blob - src/shared/services/UserService.ts
Add post, inbox, and user routes.
[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     let expires = new Date();
35     expires.setDate(expires.getDate() + 365);
36     IsomorphicCookie.save('jwt', res.jwt, { expires });
37     console.log('jwt cookie set');
38   }
39
40   public logout() {
41     this.claims = undefined;
42     this.user = undefined;
43     IsomorphicCookie.remove('jwt');
44     // setTheme();
45     this.jwtSub.next();
46     console.log('Logged out.');
47   }
48
49   public get auth(): string {
50     return IsomorphicCookie.load('jwt');
51   }
52
53   private setClaims(jwt: string) {
54     this.claims = jwt_decode(jwt);
55     this.jwtSub.next(jwt);
56   }
57
58   public static get Instance() {
59     return this._instance || (this._instance = new this());
60   }
61 }