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