2020-01-06 16:22:51 +00:00
|
|
|
import Cookies from 'js-cookie';
|
2019-03-26 18:00:18 +00:00
|
|
|
import { User, LoginResponse } from '../interfaces';
|
2019-10-15 19:21:27 +00:00
|
|
|
import { setTheme } from '../utils';
|
2020-01-06 16:22:51 +00:00
|
|
|
import jwt_decode from 'jwt-decode';
|
2019-03-23 01:42:57 +00:00
|
|
|
import { Subject } from 'rxjs';
|
|
|
|
|
|
|
|
export class UserService {
|
|
|
|
private static _instance: UserService;
|
2019-04-03 20:59:37 +00:00
|
|
|
public user: User;
|
2020-02-11 15:14:09 +00:00
|
|
|
public sub: Subject<{ user: User }> = new Subject<{
|
2019-10-19 00:20:27 +00:00
|
|
|
user: User;
|
|
|
|
}>();
|
2019-03-23 01:42:57 +00:00
|
|
|
|
|
|
|
private constructor() {
|
2019-10-19 00:20:27 +00:00
|
|
|
let jwt = Cookies.get('jwt');
|
2019-03-23 01:42:57 +00:00
|
|
|
if (jwt) {
|
|
|
|
this.setUser(jwt);
|
|
|
|
} else {
|
2019-11-13 22:03:09 +00:00
|
|
|
setTheme();
|
2019-03-23 01:42:57 +00:00
|
|
|
console.log('No JWT cookie found.');
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2019-03-26 18:00:18 +00:00
|
|
|
public login(res: LoginResponse) {
|
|
|
|
this.setUser(res.jwt);
|
2019-10-19 00:20:27 +00:00
|
|
|
Cookies.set('jwt', res.jwt, { expires: 365 });
|
|
|
|
console.log('jwt cookie set');
|
2019-03-23 01:42:57 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
public logout() {
|
2019-04-09 21:21:19 +00:00
|
|
|
this.user = undefined;
|
2019-10-19 00:20:27 +00:00
|
|
|
Cookies.remove('jwt');
|
2019-10-15 19:21:27 +00:00
|
|
|
setTheme();
|
2020-02-11 15:14:09 +00:00
|
|
|
this.sub.next({ user: undefined });
|
2019-10-19 00:20:27 +00:00
|
|
|
console.log('Logged out.');
|
2019-03-23 01:42:57 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
public get auth(): string {
|
2019-10-19 00:20:27 +00:00
|
|
|
return Cookies.get('jwt');
|
2019-03-23 01:42:57 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
private setUser(jwt: string) {
|
|
|
|
this.user = jwt_decode(jwt);
|
2019-11-12 03:24:40 +00:00
|
|
|
if (this.user.theme != 'darkly') {
|
|
|
|
setTheme(this.user.theme);
|
|
|
|
}
|
2020-02-11 15:14:09 +00:00
|
|
|
this.sub.next({ user: this.user });
|
2019-03-29 04:56:23 +00:00
|
|
|
console.log(this.user);
|
|
|
|
}
|
|
|
|
|
2019-10-19 00:20:27 +00:00
|
|
|
public static get Instance() {
|
2019-03-23 01:42:57 +00:00
|
|
|
return this._instance || (this._instance = new this());
|
|
|
|
}
|
|
|
|
}
|