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 {
8 private static _instance: UserService;
10 public sub: Subject<{ user: User; unreadCount: number }> = new Subject<{
15 private constructor() {
16 let jwt = Cookies.get('jwt');
20 if (this.user.theme != 'darkly') {
23 console.log('No JWT cookie found.');
27 public login(res: LoginResponse) {
28 this.setUser(res.jwt);
29 Cookies.set('jwt', res.jwt, { expires: 365 });
30 console.log('jwt cookie set');
34 this.user = undefined;
35 Cookies.remove('jwt');
37 this.sub.next({ user: undefined, unreadCount: 0 });
38 console.log('Logged out.');
41 public get auth(): string {
42 return Cookies.get('jwt');
45 private setUser(jwt: string) {
46 this.user = jwt_decode(jwt);
47 if (this.user.theme != 'darkly') {
48 setTheme(this.user.theme);
50 this.sub.next({ user: this.user, unreadCount: 0 });
51 console.log(this.user);
54 public static get Instance() {
55 return this._instance || (this._instance = new this());