]> Untitled Git - lemmy-ui.git/blob - src/shared/services/UserService.ts
fix merge conflicts
[lemmy-ui.git] / src / shared / services / UserService.ts
1 // import Cookies from 'js-cookie';
2 import { isAuthPath } from "@utils/app";
3 import { isBrowser } from "@utils/browser";
4 import { isHttps } from "@utils/env";
5 import IsomorphicCookie from "isomorphic-cookie";
6 import jwt_decode from "jwt-decode";
7 import { LoginResponse, MyUserInfo } from "lemmy-js-client";
8 import { toast } from "../toast";
9 import { I18NextService } from "./I18NextService";
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   static #instance: UserService;
24   public myUserInfo?: MyUserInfo;
25   public jwtInfo?: JwtInfo;
26
27   private constructor() {
28     this.#setJwtInfo();
29   }
30
31   public login(res: LoginResponse) {
32     const expires = new Date();
33     expires.setDate(expires.getDate() + 365);
34     if (res.jwt) {
35       toast(I18NextService.i18n.t("logged_in"));
36       IsomorphicCookie.save("jwt", res.jwt, { expires, secure: isHttps() });
37       this.#setJwtInfo();
38     }
39   }
40
41   public logout() {
42     this.jwtInfo = undefined;
43     this.myUserInfo = undefined;
44     IsomorphicCookie.remove("jwt"); // TODO is sometimes unreliable for some reason
45     document.cookie = "jwt=; Max-Age=0; path=/; domain=" + location.hostname;
46     if (isAuthPath(location.pathname)) {
47       location.replace("/");
48     } else {
49       location.reload();
50     }
51   }
52
53   public auth(throwErr = false): string | undefined {
54     const jwt = this.jwtInfo?.jwt;
55     if (jwt) {
56       return jwt;
57     } else {
58       const msg = "No JWT cookie found";
59       if (throwErr && isBrowser()) {
60         console.error(msg);
61         toast(I18NextService.i18n.t("not_logged_in"), "danger");
62       }
63       return undefined;
64       // throw msg;
65     }
66   }
67
68   #setJwtInfo() {
69     const jwt: string | undefined = IsomorphicCookie.load("jwt");
70
71     if (jwt) {
72       this.jwtInfo = { jwt, claims: jwt_decode(jwt) };
73     }
74   }
75
76   public static get Instance() {
77     return this.#instance || (this.#instance = new this());
78   }
79 }