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