1 // import Cookies from 'js-cookie';
2 import IsomorphicCookie from "isomorphic-cookie";
3 import jwt_decode from "jwt-decode";
4 import { LocalUserSettingsView, LoginResponse } from "lemmy-js-client";
5 import { BehaviorSubject, Subject } from "rxjs";
13 export class UserService {
14 private static _instance: UserService;
15 public localUserView: LocalUserSettingsView;
16 public claims: Claims;
17 public jwtSub: Subject<string> = new Subject<string>();
18 public unreadCountSub: BehaviorSubject<number> = new BehaviorSubject<number>(
22 private constructor() {
24 this.setClaims(this.auth);
27 console.log("No JWT cookie found.");
31 public login(res: LoginResponse) {
32 let expires = new Date();
33 expires.setDate(expires.getDate() + 365);
34 IsomorphicCookie.save("jwt", res.jwt, { expires, secure: false });
35 console.log("jwt cookie set");
36 this.setClaims(res.jwt);
40 IsomorphicCookie.remove("jwt", { secure: false });
41 this.claims = undefined;
42 this.localUserView = undefined;
45 console.log("Logged out.");
48 public get auth(): string {
49 return IsomorphicCookie.load("jwt");
52 private setClaims(jwt: string) {
53 this.claims = jwt_decode(jwt);
54 this.jwtSub.next(jwt);
57 public static get Instance() {
58 return this._instance || (this._instance = new this());