]> Untitled Git - lemmy-ui.git/blob - src/shared/services/UserService.ts
fix toaster upon user settings change (#1802)
[lemmy-ui.git] / src / shared / services / UserService.ts
1 import { isAuthPath } from "@utils/app";
2 import { clearAuthCookie, isBrowser, setAuthCookie } from "@utils/browser";
3 import * as cookie from "cookie";
4 import jwt_decode from "jwt-decode";
5 import { LoginResponse, MyUserInfo } from "lemmy-js-client";
6 import { toast } from "../toast";
7 import { I18NextService } from "./I18NextService";
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({
30     res,
31     showToast = true,
32   }: {
33     res: LoginResponse;
34     showToast?: boolean;
35   }) {
36     const expires = new Date();
37     expires.setDate(expires.getDate() + 365);
38
39     if (isBrowser() && res.jwt) {
40       showToast && toast(I18NextService.i18n.t("logged_in"));
41       setAuthCookie(res.jwt);
42       this.#setJwtInfo();
43     }
44   }
45
46   public logout() {
47     this.jwtInfo = undefined;
48     this.myUserInfo = undefined;
49
50     if (isBrowser()) {
51       clearAuthCookie();
52     }
53
54     if (isAuthPath(location.pathname)) {
55       location.replace("/");
56     } else {
57       location.reload();
58     }
59   }
60
61   public auth(throwErr = false): string | undefined {
62     const jwt = this.jwtInfo?.jwt;
63
64     if (jwt) {
65       return jwt;
66     } else {
67       const msg = "No JWT cookie found";
68
69       if (throwErr && isBrowser()) {
70         console.error(msg);
71         toast(I18NextService.i18n.t("not_logged_in"), "danger");
72       }
73
74       return undefined;
75       // throw msg;
76     }
77   }
78
79   #setJwtInfo() {
80     if (isBrowser()) {
81       const { jwt } = cookie.parse(document.cookie);
82
83       if (jwt) {
84         this.jwtInfo = { jwt, claims: jwt_decode(jwt) };
85       }
86     }
87   }
88
89   public static get Instance() {
90     return this.#instance || (this.#instance = new this());
91   }
92 }