]> Untitled Git - lemmy.git/blob - ui/src/services/UserService.ts
Adding post editing.
[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 = null;
29     Cookies.remove("jwt");
30     console.log("Logged out.");
31     this.sub.next(null);
32   }
33
34   public get loggedIn(): boolean {
35     return this.user !== undefined;
36   }
37
38   public get auth(): string {
39     return Cookies.get("jwt");
40   }
41
42   private setUser(jwt: string) {
43     this.user = jwt_decode(jwt);
44     this.sub.next(this.user);
45     console.log(this.user);
46   }
47
48   public static get Instance(){
49     return this._instance || (this._instance = new this());
50   }
51 }