1 // import Cookies from 'js-cookie';
2 import IsomorphicCookie from 'isomorphic-cookie';
3 import { User_, LoginResponse } from 'lemmy-js-client';
4 import jwt_decode from 'jwt-decode';
5 import { Subject, BehaviorSubject } from 'rxjs';
6 import { i18n } from '../i18next';
7 import { toast } from '../utils';
14 export class UserService {
15 private static _instance: UserService;
17 public claims: Claims;
18 public jwtSub: Subject<string> = new Subject<string>();
19 public unreadCountSub: BehaviorSubject<number> = new BehaviorSubject<number>(
23 private constructor() {
25 this.setClaims(this.auth);
28 console.log('No JWT cookie found.');
32 public login(res: LoginResponse) {
33 let expires = new Date();
34 expires.setDate(expires.getDate() + 365);
35 IsomorphicCookie.save('jwt', res.jwt, { expires, secure: false });
36 console.log('jwt cookie set');
37 this.setClaims(res.jwt);
41 IsomorphicCookie.remove('jwt', { secure: false });
42 this.claims = undefined;
43 this.user = undefined;
46 console.log('Logged out.');
49 public get auth(): string {
50 return IsomorphicCookie.load('jwt');
53 public authField(throwErr: boolean = true): string {
54 if (this.auth == null && throwErr) {
55 toast(i18n.t('not_logged_in'), 'danger');
56 throw 'Not logged in';
62 private setClaims(jwt: string) {
63 this.claims = jwt_decode(jwt);
64 this.jwtSub.next(jwt);
67 public static get Instance() {
68 return this._instance || (this._instance = new this());