]> Untitled Git - lemmy-ui.git/blob - src/shared/services/UserService.ts
Fixing nav-link
[lemmy-ui.git] / src / shared / services / UserService.ts
1 // import Cookies from 'js-cookie';
2 import IsomorphicCookie from "isomorphic-cookie";
3 import jwt_decode from "jwt-decode";
4 import { LoginResponse, MyUserInfo } from "lemmy-js-client";
5 import { BehaviorSubject, Subject } from "rxjs";
6 import { isHttps } from "../env";
7
8 interface Claims {
9   sub: number;
10   iss: string;
11   iat: number;
12 }
13
14 export class UserService {
15   private static _instance: UserService;
16   public myUserInfo: MyUserInfo;
17   public claims: Claims;
18   public jwtSub: Subject<string> = new Subject<string>();
19   public unreadInboxCountSub: BehaviorSubject<number> =
20     new BehaviorSubject<number>(0);
21   public unreadReportCountSub: BehaviorSubject<number> =
22     new BehaviorSubject<number>(0);
23
24   private constructor() {
25     if (this.auth) {
26       this.setClaims(this.auth);
27     } else {
28       // setTheme();
29       console.log("No JWT cookie found.");
30     }
31   }
32
33   public login(res: LoginResponse) {
34     let expires = new Date();
35     expires.setDate(expires.getDate() + 365);
36     IsomorphicCookie.save("jwt", res.jwt, { expires, secure: isHttps });
37     console.log("jwt cookie set");
38     this.setClaims(res.jwt);
39   }
40
41   public logout() {
42     this.claims = undefined;
43     this.myUserInfo = undefined;
44     // setTheme();
45     this.jwtSub.next("");
46     IsomorphicCookie.remove("jwt"); // TODO is sometimes unreliable for some reason
47     document.cookie = "jwt=; Max-Age=0; path=/; domain=" + location.host;
48     console.log("Logged out.");
49   }
50
51   public get auth(): string {
52     return IsomorphicCookie.load("jwt");
53   }
54
55   private setClaims(jwt: string) {
56     this.claims = jwt_decode(jwt);
57     this.jwtSub.next(jwt);
58   }
59
60   public static get Instance() {
61     return this._instance || (this._instance = new this());
62   }
63 }