1 // import Cookies from 'js-cookie';
2 import { isAuthPath } from "@utils/app";
3 import { isBrowser } from "@utils/browser";
4 import { isHttps } from "@utils/env";
5 import * as cookie from "cookie";
6 import jwt_decode from "jwt-decode";
7 import { LoginResponse, MyUserInfo } from "lemmy-js-client";
8 import { toast } from "../toast";
9 import { I18NextService } from "./I18NextService";
22 export class UserService {
23 static #instance: UserService;
24 public myUserInfo?: MyUserInfo;
25 public jwtInfo?: JwtInfo;
27 private constructor() {
31 public login(res: LoginResponse) {
32 const expires = new Date();
33 expires.setDate(expires.getDate() + 365);
34 if (isBrowser() && res.jwt) {
35 toast(I18NextService.i18n.t("logged_in"));
36 document.cookie = cookie.serialize("jwt", res.jwt, {
39 domain: location.hostname,
47 this.jwtInfo = undefined;
48 this.myUserInfo = undefined;
50 document.cookie = cookie.serialize("jwt", "", {
53 domain: location.hostname,
57 if (isAuthPath(location.pathname)) {
58 location.replace("/");
64 public auth(throwErr = false): string | undefined {
65 const jwt = this.jwtInfo?.jwt;
69 const msg = "No JWT cookie found";
70 if (throwErr && isBrowser()) {
72 toast(I18NextService.i18n.t("not_logged_in"), "danger");
81 const { jwt } = cookie.parse(document.cookie);
83 this.jwtInfo = { jwt, claims: jwt_decode(jwt) };
88 public static get Instance() {
89 return this.#instance || (this.#instance = new this());