1 import { isAuthPath } from "@utils/app";
2 import { clearAuthCookie, isBrowser, setAuthCookie } from "@utils/browser";
3 import * as cookie from "cookie";
4 import jwt_decode from "jwt-decode";
5 import { LoginResponse, MyUserInfo } from "lemmy-js-client";
6 import { toast } from "../toast";
7 import { I18NextService } from "./I18NextService";
20 export class UserService {
21 static #instance: UserService;
22 public myUserInfo?: MyUserInfo;
23 public jwtInfo?: JwtInfo;
25 private constructor() {
36 const expires = new Date();
37 expires.setDate(expires.getDate() + 365);
39 if (isBrowser() && res.jwt) {
40 showToast && toast(I18NextService.i18n.t("logged_in"));
41 setAuthCookie(res.jwt);
47 this.jwtInfo = undefined;
48 this.myUserInfo = undefined;
54 if (isAuthPath(location.pathname)) {
55 location.replace("/");
61 public auth(throwErr = false): string | undefined {
62 const jwt = this.jwtInfo?.jwt;
67 const msg = "No JWT cookie found";
69 if (throwErr && isBrowser()) {
71 toast(I18NextService.i18n.t("not_logged_in"), "danger");
81 const { jwt } = cookie.parse(document.cookie);
84 this.jwtInfo = { jwt, claims: jwt_decode(jwt) };
89 public static get Instance() {
90 return this.#instance || (this.#instance = new this());