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() {
29 public login(res: LoginResponse) {
30 const expires = new Date();
31 expires.setDate(expires.getDate() + 365);
33 if (isBrowser() && res.jwt) {
34 toast(I18NextService.i18n.t("logged_in"));
35 setAuthCookie(res.jwt);
41 this.jwtInfo = undefined;
42 this.myUserInfo = undefined;
48 if (isAuthPath(location.pathname)) {
49 location.replace("/");
55 public auth(throwErr = false): string | undefined {
56 const jwt = this.jwtInfo?.jwt;
61 const msg = "No JWT cookie found";
63 if (throwErr && isBrowser()) {
65 toast(I18NextService.i18n.t("not_logged_in"), "danger");
75 const { jwt } = cookie.parse(document.cookie);
78 this.jwtInfo = { jwt, claims: jwt_decode(jwt) };
83 public static get Instance() {
84 return this.#instance || (this.#instance = new this());