]> Untitled Git - lemmy-ui.git/blob - src/shared/services/UserService.ts
Merge pull request #221 from LemmyNet/split_user_table
[lemmy-ui.git] / src / shared / services / UserService.ts
1 // import Cookies from 'js-cookie';
2 import IsomorphicCookie from "isomorphic-cookie";
3 import { LocalUserSettingsView, LoginResponse } from "lemmy-js-client";
4 import jwt_decode from "jwt-decode";
5 import { Subject, BehaviorSubject } from "rxjs";
6
7 interface Claims {
8   sub: number;
9   iss: string;
10   iat: number;
11 }
12
13 export class UserService {
14   private static _instance: UserService;
15   public localUserView: LocalUserSettingsView;
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     if (this.auth) {
24       this.setClaims(this.auth);
25     } else {
26       // setTheme();
27       console.log("No JWT cookie found.");
28     }
29   }
30
31   public login(res: LoginResponse) {
32     let expires = new Date();
33     expires.setDate(expires.getDate() + 365);
34     IsomorphicCookie.save("jwt", res.jwt, { expires, secure: false });
35     console.log("jwt cookie set");
36     this.setClaims(res.jwt);
37   }
38
39   public logout() {
40     IsomorphicCookie.remove("jwt", { secure: false });
41     this.claims = undefined;
42     this.localUserView = undefined;
43     // setTheme();
44     this.jwtSub.next();
45     console.log("Logged out.");
46   }
47
48   public get auth(): string {
49     return IsomorphicCookie.load("jwt");
50   }
51
52   private setClaims(jwt: string) {
53     this.claims = jwt_decode(jwt);
54     this.jwtSub.next(jwt);
55   }
56
57   public static get Instance() {
58     return this._instance || (this._instance = new this());
59   }
60 }