1 // import Cookies from 'js-cookie';
2 import { Err, None, Ok, Option, Result, Some } from "@sniptt/monads";
3 import IsomorphicCookie from "isomorphic-cookie";
4 import jwt_decode from "jwt-decode";
5 import { LoginResponse, MyUserInfo } from "lemmy-js-client";
6 import { BehaviorSubject } from "rxjs";
7 import { isHttps } from "../env";
8 import { i18n } from "../i18next";
9 import { isBrowser, toast } from "../utils";
22 export class UserService {
23 private static _instance: UserService;
24 public myUserInfo: Option<MyUserInfo> = None;
25 public jwtInfo: Option<JwtInfo> = None;
26 public unreadInboxCountSub: BehaviorSubject<number> =
27 new BehaviorSubject<number>(0);
28 public unreadReportCountSub: BehaviorSubject<number> =
29 new BehaviorSubject<number>(0);
30 public unreadApplicationCountSub: BehaviorSubject<number> =
31 new BehaviorSubject<number>(0);
33 private constructor() {
37 public login(res: LoginResponse) {
38 let expires = new Date();
39 expires.setDate(expires.getDate() + 365);
42 toast(i18n.t("logged_in"));
43 IsomorphicCookie.save("jwt", jwt, { expires, secure: isHttps });
53 this.myUserInfo = None;
54 IsomorphicCookie.remove("jwt"); // TODO is sometimes unreliable for some reason
55 document.cookie = "jwt=; Max-Age=0; path=/; domain=" + location.host;
59 public auth(throwErr = true): Result<string, string> {
60 // Can't use match to convert to result for some reason
61 let jwt = this.jwtInfo.map(j => j.jwt);
63 return Ok(jwt.unwrap());
65 let msg = "No JWT cookie found";
66 if (throwErr && isBrowser()) {
68 toast(i18n.t("not_logged_in"), "danger");
74 private setJwtInfo() {
75 let jwt = IsomorphicCookie.load("jwt");
78 let jwtInfo: JwtInfo = { jwt, claims: jwt_decode(jwt) };
79 this.jwtInfo = Some(jwtInfo);
83 public static get Instance() {
84 return this._instance || (this._instance = new this());