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 { isAuthPath, isBrowser, toast } from "../utils";
21 export class UserService {
22 private static _instance: UserService;
23 public myUserInfo?: MyUserInfo;
24 public jwtInfo?: JwtInfo;
25 public unreadInboxCountSub: BehaviorSubject<number> =
26 new BehaviorSubject<number>(0);
27 public unreadReportCountSub: BehaviorSubject<number> =
28 new BehaviorSubject<number>(0);
29 public unreadApplicationCountSub: BehaviorSubject<number> =
30 new BehaviorSubject<number>(0);
32 private constructor() {
36 public login(res: LoginResponse) {
37 let expires = new Date();
38 expires.setDate(expires.getDate() + 365);
40 toast(i18n.t("logged_in"));
41 IsomorphicCookie.save("jwt", res.jwt, { expires, secure: isHttps() });
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 (isAuthPath(location.pathname)) {
52 location.replace("/");
58 public auth(throwErr = true): string | undefined {
59 let jwt = this.jwtInfo?.jwt;
63 let msg = "No JWT cookie found";
64 if (throwErr && isBrowser()) {
66 toast(i18n.t("not_logged_in"), "danger");
73 private setJwtInfo() {
74 let jwt: string | undefined = IsomorphicCookie.load("jwt");
77 this.jwtInfo = { jwt, claims: jwt_decode(jwt) };
81 public static get Instance() {
82 return this._instance || (this._instance = new this());