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 { isHttps } from "../env";
6 import { i18n } from "../i18next";
7 import { isAuthPath, isBrowser, toast } from "../utils";
20 export class UserService {
21 static #instance: UserService;
22 public myUserInfo?: MyUserInfo;
23 public jwtInfo?: JwtInfo;
25 private constructor() {
29 public login(res: LoginResponse) {
30 const expires = new Date();
31 expires.setDate(expires.getDate() + 365);
33 toast(i18n.t("logged_in"));
34 IsomorphicCookie.save("jwt", res.jwt, { expires, secure: isHttps() });
40 this.jwtInfo = undefined;
41 this.myUserInfo = undefined;
42 IsomorphicCookie.remove("jwt"); // TODO is sometimes unreliable for some reason
43 document.cookie = "jwt=; Max-Age=0; path=/; domain=" + location.hostname;
44 if (isAuthPath(location.pathname)) {
45 location.replace("/");
51 public auth(throwErr = false): string | undefined {
52 const jwt = this.jwtInfo?.jwt;
56 const msg = "No JWT cookie found";
57 if (throwErr && isBrowser()) {
59 toast(i18n.t("not_logged_in"), "danger");
67 const jwt: string | undefined = IsomorphicCookie.load("jwt");
70 this.jwtInfo = { jwt, claims: jwt_decode(jwt) };
74 public static get Instance() {
75 return this.#instance || (this.#instance = new this());