1 import * as Cookies from 'js-cookie';
2 import { User, LoginResponse } from '../interfaces';
3 import * as jwt_decode from 'jwt-decode';
4 import { Subject } from 'rxjs';
6 export class UserService {
8 private static _instance: UserService;
10 public sub: Subject<{user: User, unreadCount: number}> = new Subject<{user: User, unreadCount: number}>();
12 private constructor() {
13 let jwt = Cookies.get("jwt");
17 console.log('No JWT cookie found.');
21 public login(res: LoginResponse) {
22 this.setUser(res.jwt);
23 Cookies.set("jwt", res.jwt, { expires: 365 });
24 console.log("jwt cookie set");
28 this.user = undefined;
29 Cookies.remove("jwt");
30 console.log("Logged out.");
31 this.sub.next({user: undefined, unreadCount: 0});
34 public get auth(): string {
35 return Cookies.get("jwt");
38 private setUser(jwt: string) {
39 this.user = jwt_decode(jwt);
40 this.sub.next({user: this.user, unreadCount: 0});
41 console.log(this.user);
44 public static get Instance(){
45 return this._instance || (this._instance = new this());