1 // import Cookies from 'js-cookie';
2 import { isBrowser } from "@utils/browser";
3 import IsomorphicCookie from "isomorphic-cookie";
4 import jwt_decode from "jwt-decode";
5 import { LoginResponse, MyUserInfo } from "lemmy-js-client";
6 import { isHttps } from "../env";
7 import { i18n } from "../i18next";
8 import { isAuthPath, toast } from "../utils";
21 export class UserService {
22 static #instance: UserService;
23 public myUserInfo?: MyUserInfo;
24 public jwtInfo?: JwtInfo;
26 private constructor() {
30 public login(res: LoginResponse) {
31 const expires = new Date();
32 expires.setDate(expires.getDate() + 365);
34 toast(i18n.t("logged_in"));
35 IsomorphicCookie.save("jwt", res.jwt, { expires, secure: isHttps() });
41 this.jwtInfo = undefined;
42 this.myUserInfo = undefined;
43 IsomorphicCookie.remove("jwt"); // TODO is sometimes unreliable for some reason
44 document.cookie = "jwt=; Max-Age=0; path=/; domain=" + location.hostname;
45 if (isAuthPath(location.pathname)) {
46 location.replace("/");
52 public auth(throwErr = false): string | undefined {
53 const jwt = this.jwtInfo?.jwt;
57 const msg = "No JWT cookie found";
58 if (throwErr && isBrowser()) {
60 toast(i18n.t("not_logged_in"), "danger");
68 const jwt: string | undefined = IsomorphicCookie.load("jwt");
71 this.jwtInfo = { jwt, claims: jwt_decode(jwt) };
75 public static get Instance() {
76 return this.#instance || (this.#instance = new this());