]> Untitled Git - lemmy.git/blobdiff - ui/src/services/UserService.ts
routes.api: fix get_captcha endpoint (#1135)
[lemmy.git] / ui / src / services / UserService.ts
index ac4d485059c8d991460d3f9a8afd5ed882bfa31b..513ba608079ea29e115b562141cb0d8e32d84879 100644 (file)
@@ -1,19 +1,27 @@
-import * as Cookies from 'js-cookie';
-import { User, LoginResponse } from '../interfaces';
+import Cookies from 'js-cookie';
+import { User, LoginResponse } from 'lemmy-js-client';
 import { setTheme } from '../utils';
-import * as jwt_decode from 'jwt-decode';
-import { Subject } from 'rxjs';
+import jwt_decode from 'jwt-decode';
+import { Subject, BehaviorSubject } from 'rxjs';
 
-export class UserService {
+interface Claims {
+  id: number;
+  iss: string;
+}
 
+export class UserService {
   private static _instance: UserService;
   public user: User;
-  public sub: Subject<{user: User, unreadCount: number}> = new Subject<{user: User, unreadCount: number}>();
+  public claims: Claims;
+  public jwtSub: Subject<string> = new Subject<string>();
+  public unreadCountSub: BehaviorSubject<number> = new BehaviorSubject<number>(
+    0
+  );
 
   private constructor() {
-    let jwt = Cookies.get("jwt");
+    let jwt = Cookies.get('jwt');
     if (jwt) {
-      this.setUser(jwt);
+      this.setClaims(jwt);
     } else {
       setTheme();
       console.log('No JWT cookie found.');
@@ -21,31 +29,30 @@ export class UserService {
   }
 
   public login(res: LoginResponse) {
-    this.setUser(res.jwt);
-    Cookies.set("jwt", res.jwt, { expires: 365 });
-    console.log("jwt cookie set");
+    this.setClaims(res.jwt);
+    Cookies.set('jwt', res.jwt, { expires: 365 });
+    console.log('jwt cookie set');
   }
 
   public logout() {
+    this.claims = undefined;
     this.user = undefined;
-    Cookies.remove("jwt");
+    Cookies.remove('jwt');
     setTheme();
-    this.sub.next({user: undefined, unreadCount: 0});
-    console.log("Logged out.");
+    this.jwtSub.next();
+    console.log('Logged out.');
   }
 
   public get auth(): string {
-    return Cookies.get("jwt");
+    return Cookies.get('jwt');
   }
 
-  private setUser(jwt: string) {
-    this.user = jwt_decode(jwt);
-    setTheme(this.user.theme);
-    this.sub.next({user: this.user, unreadCount: 0});
-    console.log(this.user);
+  private setClaims(jwt: string) {
+    this.claims = jwt_decode(jwt);
+    this.jwtSub.next(jwt);
   }
 
-  public static get Instance(){
+  public static get Instance() {
     return this._instance || (this._instance = new this());
   }
 }