]> Untitled Git - lemmy-ui.git/blob - src/shared/services/UserService.ts
First pass at v2_api
[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 import { i18n } from '../i18next';
7 import { toast } from '../utils';
8
9 interface Claims {
10   id: number;
11   iss: string;
12 }
13
14 export class UserService {
15   private static _instance: UserService;
16   public user: User_;
17   public claims: Claims;
18   public jwtSub: Subject<string> = new Subject<string>();
19   public unreadCountSub: BehaviorSubject<number> = new BehaviorSubject<number>(
20     0
21   );
22
23   private constructor() {
24     if (this.auth) {
25       this.setClaims(this.auth);
26     } else {
27       // setTheme();
28       console.log('No JWT cookie found.');
29     }
30   }
31
32   public login(res: LoginResponse) {
33     let expires = new Date();
34     expires.setDate(expires.getDate() + 365);
35     IsomorphicCookie.save('jwt', res.jwt, { expires, secure: false });
36     console.log('jwt cookie set');
37     this.setClaims(res.jwt);
38   }
39
40   public logout() {
41     IsomorphicCookie.remove('jwt', { secure: false });
42     this.claims = undefined;
43     this.user = undefined;
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   public authField(throwErr: boolean = true): string {
54     if (this.auth == null && throwErr) {
55       toast(i18n.t('not_logged_in'), 'danger');
56       throw 'Not logged in';
57     } else {
58       return this.auth;
59     }
60   }
61
62   private setClaims(jwt: string) {
63     this.claims = jwt_decode(jwt);
64     this.jwtSub.next(jwt);
65   }
66
67   public static get Instance() {
68     return this._instance || (this._instance = new this());
69   }
70 }