]> Untitled Git - lemmy-ui.git/blob - src/shared/services/UserService.ts
break out browser and helper methods
[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 { isHttps } from "../env";
6 import { i18n } from "../i18next";
7 import { isAuthPath, toast } from "../utils";
8 import { isBrowser } from "../utils/browser/is-browser";
9
10 interface Claims {
11   sub: number;
12   iss: string;
13   iat: number;
14 }
15
16 interface JwtInfo {
17   claims: Claims;
18   jwt: string;
19 }
20
21 export class UserService {
22   static #instance: UserService;
23   public myUserInfo?: MyUserInfo;
24   public jwtInfo?: JwtInfo;
25
26   private constructor() {
27     this.#setJwtInfo();
28   }
29
30   public login(res: LoginResponse) {
31     const expires = new Date();
32     expires.setDate(expires.getDate() + 365);
33     if (res.jwt) {
34       toast(i18n.t("logged_in"));
35       IsomorphicCookie.save("jwt", res.jwt, { expires, secure: isHttps() });
36       this.#setJwtInfo();
37     }
38   }
39
40   public logout() {
41     this.jwtInfo = undefined;
42     this.myUserInfo = undefined;
43     IsomorphicCookie.remove("jwt"); // TODO is sometimes unreliable for some reason
44     document.cookie = "jwt=; Max-Age=0; path=/; domain=" + location.hostname;
45     if (isAuthPath(location.pathname)) {
46       location.replace("/");
47     } else {
48       location.reload();
49     }
50   }
51
52   public auth(throwErr = false): string | undefined {
53     const jwt = this.jwtInfo?.jwt;
54     if (jwt) {
55       return jwt;
56     } else {
57       const msg = "No JWT cookie found";
58       if (throwErr && isBrowser()) {
59         console.error(msg);
60         toast(i18n.t("not_logged_in"), "danger");
61       }
62       return undefined;
63       // throw msg;
64     }
65   }
66
67   #setJwtInfo() {
68     const jwt: string | undefined = IsomorphicCookie.load("jwt");
69
70     if (jwt) {
71       this.jwtInfo = { jwt, claims: jwt_decode(jwt) };
72     }
73   }
74
75   public static get Instance() {
76     return this.#instance || (this.#instance = new this());
77   }
78 }