]> Untitled Git - lemmy-ui.git/blob - src/shared/services/UserService.ts
3757e2369604da65cb19c9cbe2a3b3f087059cdf
[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 * as cookie from "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 (isBrowser() && res.jwt) {
35       toast(I18NextService.i18n.t("logged_in"));
36       document.cookie = cookie.serialize("jwt", res.jwt, {
37         expires,
38         secure: isHttps(),
39         domain: location.hostname,
40         sameSite: true,
41         path: "/",
42       });
43       this.#setJwtInfo();
44     }
45   }
46
47   public logout() {
48     this.jwtInfo = undefined;
49     this.myUserInfo = undefined;
50     if (isBrowser()) {
51       document.cookie = cookie.serialize("jwt", "", {
52         maxAge: 0,
53         path: "/",
54         domain: location.hostname,
55         sameSite: true,
56       });
57     }
58     if (isAuthPath(location.pathname)) {
59       location.replace("/");
60     } else {
61       location.reload();
62     }
63   }
64
65   public auth(throwErr = false): string | undefined {
66     const jwt = this.jwtInfo?.jwt;
67     if (jwt) {
68       return jwt;
69     } else {
70       const msg = "No JWT cookie found";
71       if (throwErr && isBrowser()) {
72         console.error(msg);
73         toast(I18NextService.i18n.t("not_logged_in"), "danger");
74       }
75       return undefined;
76       // throw msg;
77     }
78   }
79
80   #setJwtInfo() {
81     if (isBrowser()) {
82       const { jwt } = cookie.parse(document.cookie);
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 }