]> Untitled Git - lemmy-ui.git/blob - src/shared/services/UserService.ts
Adding new site setup fields. (#840)
[lemmy-ui.git] / src / shared / services / UserService.ts
1 // import Cookies from 'js-cookie';
2 import { Err, None, Ok, Option, Result, Some } from "@sniptt/monads";
3 import IsomorphicCookie from "isomorphic-cookie";
4 import jwt_decode from "jwt-decode";
5 import { LoginResponse, MyUserInfo } from "lemmy-js-client";
6 import { BehaviorSubject } from "rxjs";
7 import { isHttps } from "../env";
8 import { i18n } from "../i18next";
9 import { isBrowser, toast } from "../utils";
10
11 interface Claims {
12   sub: number;
13   iss: string;
14   iat: number;
15 }
16
17 interface JwtInfo {
18   claims: Claims;
19   jwt: string;
20 }
21
22 export class UserService {
23   private static _instance: UserService;
24   public myUserInfo: Option<MyUserInfo> = None;
25   public jwtInfo: Option<JwtInfo> = None;
26   public unreadInboxCountSub: BehaviorSubject<number> =
27     new BehaviorSubject<number>(0);
28   public unreadReportCountSub: BehaviorSubject<number> =
29     new BehaviorSubject<number>(0);
30   public unreadApplicationCountSub: BehaviorSubject<number> =
31     new BehaviorSubject<number>(0);
32
33   private constructor() {
34     this.setJwtInfo();
35   }
36
37   public login(res: LoginResponse) {
38     let expires = new Date();
39     expires.setDate(expires.getDate() + 365);
40     res.jwt.match({
41       some: jwt => {
42         toast(i18n.t("logged_in"));
43         IsomorphicCookie.save("jwt", jwt, { expires, secure: isHttps });
44         this.setJwtInfo();
45       },
46       none: void 0,
47     });
48   }
49
50   public logout() {
51     this.jwtInfo = None;
52     this.myUserInfo = None;
53     IsomorphicCookie.remove("jwt"); // TODO is sometimes unreliable for some reason
54     document.cookie = "jwt=; Max-Age=0; path=/; domain=" + location.hostname;
55     location.reload();
56   }
57
58   public auth(throwErr = true): Result<string, string> {
59     // Can't use match to convert to result for some reason
60     let jwt = this.jwtInfo.map(j => j.jwt);
61     if (jwt.isSome()) {
62       return Ok(jwt.unwrap());
63     } else {
64       let msg = "No JWT cookie found";
65       if (throwErr && isBrowser()) {
66         console.log(msg);
67         toast(i18n.t("not_logged_in"), "danger");
68       }
69       return Err(msg);
70     }
71   }
72
73   private setJwtInfo() {
74     let jwt = IsomorphicCookie.load("jwt");
75
76     if (jwt) {
77       let jwtInfo: JwtInfo = { jwt, claims: jwt_decode(jwt) };
78       this.jwtInfo = Some(jwtInfo);
79     }
80   }
81
82   public static get Instance() {
83     return this._instance || (this._instance = new this());
84   }
85 }