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