]> Untitled Git - lemmy-ui.git/blob - src/shared/services/UserService.ts
Attempt to fix inability to logout from some instances (subdomains) (#1809)
[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(res: LoginResponse) {
30     const expires = new Date();
31     expires.setDate(expires.getDate() + 365);
32
33     if (isBrowser() && res.jwt) {
34       toast(I18NextService.i18n.t("logged_in"));
35       setAuthCookie(res.jwt);
36       this.#setJwtInfo();
37     }
38   }
39
40   public logout() {
41     this.jwtInfo = undefined;
42     this.myUserInfo = undefined;
43
44     if (isBrowser()) {
45       clearAuthCookie();
46     }
47
48     if (isAuthPath(location.pathname)) {
49       location.replace("/");
50     } else {
51       location.reload();
52     }
53   }
54
55   public auth(throwErr = false): string | undefined {
56     const jwt = this.jwtInfo?.jwt;
57
58     if (jwt) {
59       return jwt;
60     } else {
61       const msg = "No JWT cookie found";
62
63       if (throwErr && isBrowser()) {
64         console.error(msg);
65         toast(I18NextService.i18n.t("not_logged_in"), "danger");
66       }
67
68       return undefined;
69       // throw msg;
70     }
71   }
72
73   #setJwtInfo() {
74     if (isBrowser()) {
75       const { jwt } = cookie.parse(document.cookie);
76
77       if (jwt) {
78         this.jwtInfo = { jwt, claims: jwt_decode(jwt) };
79       }
80     }
81   }
82
83   public static get Instance() {
84     return this.#instance || (this.#instance = new this());
85   }
86 }