]> Untitled Git - lemmy.git/blob - ui/src/services/UserService.ts
Merge branch 'replies' into dev
[lemmy.git] / ui / src / services / UserService.ts
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';
5
6 export class UserService {
7
8   private static _instance: UserService;
9   public user: User;
10   public sub: Subject<{user: User, unreadCount: number}> = new Subject<{user: User, unreadCount: number}>();
11
12   private constructor() {
13     let jwt = Cookies.get("jwt");
14     if (jwt) {
15       this.setUser(jwt);
16     } else {
17       console.log('No JWT cookie found.');
18     }
19
20   }
21
22   public login(res: LoginResponse) {
23     this.setUser(res.jwt);
24     Cookies.set("jwt", res.jwt);
25     console.log("jwt cookie set");
26   }
27
28   public logout() {
29     this.user = undefined;
30     Cookies.remove("jwt");
31     console.log("Logged out.");
32     this.sub.next({user: undefined, unreadCount: 0});
33   }
34
35   public get auth(): string {
36     return Cookies.get("jwt");
37   }
38
39   private setUser(jwt: string) {
40     this.user = jwt_decode(jwt);
41     this.sub.next({user: this.user, unreadCount: 0});
42     console.log(this.user);
43   }
44
45   public static get Instance(){
46     return this._instance || (this._instance = new this());
47   }
48 }