]> Untitled Git - lemmy-ui.git/blob - src/shared/services/UserService.ts
Private instances (#523)
[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   public unreadApplicationCountSub: BehaviorSubject<number> =
24     new BehaviorSubject<number>(0);
25
26   private constructor() {
27     if (this.auth) {
28       this.setClaims(this.auth);
29     } else {
30       // setTheme();
31       console.log("No JWT cookie found.");
32     }
33   }
34
35   public login(res: LoginResponse) {
36     let expires = new Date();
37     expires.setDate(expires.getDate() + 365);
38     IsomorphicCookie.save("jwt", res.jwt, { expires, secure: isHttps });
39     console.log("jwt cookie set");
40     this.setClaims(res.jwt);
41   }
42
43   public logout() {
44     this.claims = undefined;
45     this.myUserInfo = undefined;
46     // setTheme();
47     this.jwtSub.next("");
48     IsomorphicCookie.remove("jwt"); // TODO is sometimes unreliable for some reason
49     document.cookie = "jwt=; Max-Age=0; path=/; domain=" + location.host;
50     console.log("Logged out.");
51   }
52
53   public get auth(): string {
54     return IsomorphicCookie.load("jwt");
55   }
56
57   private setClaims(jwt: string) {
58     this.claims = jwt_decode(jwt);
59     this.jwtSub.next(jwt);
60   }
61
62   public static get Instance() {
63     return this._instance || (this._instance = new this());
64   }
65 }