]> Untitled Git - lemmy-ui.git/blob - src/shared/services/UserService.ts
Adding JWT secure flag. (#426)
[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 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: isHttps });
36     console.log("jwt cookie set");
37     this.setClaims(res.jwt);
38   }
39
40   public logout() {
41     this.claims = undefined;
42     this.myUserInfo = undefined;
43     // setTheme();
44     this.jwtSub.next("");
45     IsomorphicCookie.remove("jwt"); // TODO is sometimes unreliable for some reason
46     document.cookie = "jwt=; Max-Age=0; path=/; domain=" + location.host;
47     console.log("Logged out.");
48   }
49
50   public get auth(): string {
51     return IsomorphicCookie.load("jwt");
52   }
53
54   private setClaims(jwt: string) {
55     this.claims = jwt_decode(jwt);
56     this.jwtSub.next(jwt);
57   }
58
59   public static get Instance() {
60     return this._instance || (this._instance = new this());
61   }
62 }