lemmy/ui/src/services/UserService.ts

52 lines
1.2 KiB
TypeScript
Raw Normal View History

import * as Cookies from 'js-cookie';
import { User, LoginResponse } from '../interfaces';
import { setTheme } from '../utils';
import * as jwt_decode from 'jwt-decode';
import { Subject } from 'rxjs';
export class UserService {
2019-04-20 18:17:00 +00:00
private static _instance: UserService;
public user: User;
2019-04-20 18:17:00 +00:00
public sub: Subject<{user: User, unreadCount: number}> = new Subject<{user: User, unreadCount: number}>();
private constructor() {
let jwt = Cookies.get("jwt");
if (jwt) {
this.setUser(jwt);
} else {
setTheme();
console.log('No JWT cookie found.');
}
}
public login(res: LoginResponse) {
this.setUser(res.jwt);
2019-08-19 22:22:05 +00:00
Cookies.set("jwt", res.jwt, { expires: 365 });
console.log("jwt cookie set");
}
public logout() {
2019-04-09 21:21:19 +00:00
this.user = undefined;
Cookies.remove("jwt");
setTheme();
2019-04-20 18:17:00 +00:00
this.sub.next({user: undefined, unreadCount: 0});
console.log("Logged out.");
}
public get auth(): string {
return Cookies.get("jwt");
}
private setUser(jwt: string) {
this.user = jwt_decode(jwt);
setTheme(this.user.theme);
2019-04-20 18:17:00 +00:00
this.sub.next({user: this.user, unreadCount: 0});
2019-03-29 04:56:23 +00:00
console.log(this.user);
}
public static get Instance(){
return this._instance || (this._instance = new this());
}
}