1 import * as Cookies from 'js-cookie';
2 import { User, LoginResponse } from '../interfaces';
3 import { setTheme } from '../utils';
4 import * as jwt_decode from 'jwt-decode';
5 import { Subject } from 'rxjs';
7 export class UserService {
9 private static _instance: UserService;
11 public sub: Subject<{user: User, unreadCount: number}> = new Subject<{user: User, unreadCount: number}>();
13 private constructor() {
14 let jwt = Cookies.get("jwt");
19 console.log('No JWT cookie found.');
23 public login(res: LoginResponse) {
24 this.setUser(res.jwt);
25 Cookies.set("jwt", res.jwt, { expires: 365 });
26 console.log("jwt cookie set");
30 this.user = undefined;
31 Cookies.remove("jwt");
33 this.sub.next({user: undefined, unreadCount: 0});
34 console.log("Logged out.");
37 public get auth(): string {
38 return Cookies.get("jwt");
41 private setUser(jwt: string) {
42 this.user = jwt_decode(jwt);
43 setTheme(this.user.theme);
44 this.sub.next({user: this.user, unreadCount: 0});
45 console.log(this.user);
48 public static get Instance(){
49 return this._instance || (this._instance = new this());