]> Untitled Git - lemmy-ui.git/blob - src/shared/services/UserService.ts
Redirect fomr pages that require auth on logout
[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 { BehaviorSubject } from "rxjs";
6 import { isHttps } from "../env";
7 import { i18n } from "../i18next";
8 import { isBrowser, toast } from "../utils";
9
10 interface Claims {
11   sub: number;
12   iss: string;
13   iat: number;
14 }
15
16 interface JwtInfo {
17   claims: Claims;
18   jwt: string;
19 }
20
21 export class UserService {
22   private static _instance: UserService;
23   public myUserInfo?: MyUserInfo;
24   public jwtInfo?: JwtInfo;
25   public unreadInboxCountSub: BehaviorSubject<bigint> =
26     new BehaviorSubject<bigint>(0n);
27   public unreadReportCountSub: BehaviorSubject<bigint> =
28     new BehaviorSubject<bigint>(0n);
29   public unreadApplicationCountSub: BehaviorSubject<bigint> =
30     new BehaviorSubject<bigint>(0n);
31
32   private constructor() {
33     this.setJwtInfo();
34   }
35
36   public login(res: LoginResponse) {
37     let expires = new Date();
38     expires.setDate(expires.getDate() + 365);
39     if (res.jwt) {
40       toast(i18n.t("logged_in"));
41       IsomorphicCookie.save("jwt", res.jwt, { expires, secure: isHttps() });
42       this.setJwtInfo();
43     }
44   }
45
46   public logout() {
47     this.jwtInfo = undefined;
48     this.myUserInfo = undefined;
49     IsomorphicCookie.remove("jwt"); // TODO is sometimes unreliable for some reason
50     document.cookie = "jwt=; Max-Age=0; path=/; domain=" + location.hostname;
51     if (
52       /create_.*|inbox|settings|setup|admin|reports|registration_applications/g.test(
53         location.pathname
54       )
55     ) {
56       location.replace("/");
57     } else {
58       location.reload();
59     }
60   }
61
62   public auth(throwErr = true): string | undefined {
63     let jwt = this.jwtInfo?.jwt;
64     if (jwt) {
65       return jwt;
66     } else {
67       let msg = "No JWT cookie found";
68       if (throwErr && isBrowser()) {
69         console.error(msg);
70         toast(i18n.t("not_logged_in"), "danger");
71       }
72       return undefined;
73       // throw msg;
74     }
75   }
76
77   private setJwtInfo() {
78     let jwt: string | undefined = IsomorphicCookie.load("jwt");
79
80     if (jwt) {
81       this.jwtInfo = { jwt, claims: jwt_decode(jwt) };
82     }
83   }
84
85   public static get Instance() {
86     return this._instance || (this._instance = new this());
87   }
88 }