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