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 { BehaviorSubject, Subject } from "rxjs";
6 import { isHttps } from "../env";
14 export class UserService {
15 private static _instance: UserService;
16 public myUserInfo: MyUserInfo;
17 public claims: Claims;
18 public jwtSub: Subject<string> = new Subject<string>();
19 public unreadInboxCountSub: BehaviorSubject<number> =
20 new BehaviorSubject<number>(0);
21 public unreadReportCountSub: BehaviorSubject<number> =
22 new BehaviorSubject<number>(0);
23 public unreadApplicationCountSub: BehaviorSubject<number> =
24 new BehaviorSubject<number>(0);
26 private constructor() {
28 this.setClaims(this.auth);
31 console.log("No JWT cookie found.");
35 public login(res: LoginResponse) {
36 let expires = new Date();
37 expires.setDate(expires.getDate() + 365);
38 IsomorphicCookie.save("jwt", res.jwt, { expires, secure: isHttps });
39 console.log("jwt cookie set");
40 this.setClaims(res.jwt);
44 this.claims = undefined;
45 this.myUserInfo = undefined;
48 IsomorphicCookie.remove("jwt"); // TODO is sometimes unreliable for some reason
49 document.cookie = "jwt=; Max-Age=0; path=/; domain=" + location.host;
50 console.log("Logged out.");
53 public get auth(): string {
54 return IsomorphicCookie.load("jwt");
57 private setClaims(jwt: string) {
58 this.claims = jwt_decode(jwt);
59 this.jwtSub.next(jwt);
62 public static get Instance() {
63 return this._instance || (this._instance = new this());