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