1 // import Cookies from 'js-cookie';
2 import IsomorphicCookie from 'isomorphic-cookie';
3 import { UserSafeSettings, LoginResponse } from 'lemmy-js-client';
4 import jwt_decode from 'jwt-decode';
5 import { Subject, BehaviorSubject } from 'rxjs';
12 export class UserService {
13 private static _instance: UserService;
14 public user: UserSafeSettings;
15 public claims: Claims;
16 public jwtSub: Subject<string> = new Subject<string>();
17 public unreadCountSub: BehaviorSubject<number> = new BehaviorSubject<number>(
21 private constructor() {
23 this.setClaims(this.auth);
26 console.log('No JWT cookie found.');
30 public login(res: LoginResponse) {
31 let expires = new Date();
32 expires.setDate(expires.getDate() + 365);
33 IsomorphicCookie.save('jwt', res.jwt, { expires, secure: false });
34 console.log('jwt cookie set');
35 this.setClaims(res.jwt);
39 IsomorphicCookie.remove('jwt', { secure: false });
40 this.claims = undefined;
41 this.user = undefined;
44 console.log('Logged out.');
47 public get auth(): string {
48 return IsomorphicCookie.load('jwt');
51 private setClaims(jwt: string) {
52 this.claims = jwt_decode(jwt);
53 this.jwtSub.next(jwt);
56 public static get Instance() {
57 return this._instance || (this._instance = new this());