sprinklers3/client/state/TokenStore.ts

49 lines
1.2 KiB
TypeScript
Raw Normal View History

2018-08-13 15:11:36 +03:00
import { action, observable } from "mobx";
2018-08-07 21:21:26 +03:00
import { Token } from "@client/state/Token";
2018-08-11 20:35:34 +03:00
import { AccessToken, RefreshToken } from "@common/TokenClaims";
const LOCAL_STORAGE_KEY = "TokenStore";
export class TokenStore {
2018-08-11 20:35:34 +03:00
@observable accessToken: Token<AccessToken> = new Token();
@observable refreshToken: Token<RefreshToken> = new Token();
2018-08-13 15:11:36 +03:00
@action
2018-08-28 05:34:23 -06:00
clearAccessToken() {
this.accessToken.token = null;
this.saveLocalStorage();
}
@action
clearAll() {
2018-07-08 13:44:46 -06:00
this.accessToken.token = null;
this.refreshToken.token = null;
this.saveLocalStorage();
}
2018-08-13 15:11:36 +03:00
@action
saveLocalStorage() {
window.localStorage.setItem(LOCAL_STORAGE_KEY, JSON.stringify(this.toJSON()));
}
2018-08-13 15:11:36 +03:00
@action
loadLocalStorage() {
const data = window.localStorage.getItem(LOCAL_STORAGE_KEY);
if (data) {
const data2 = JSON.parse(data);
this.updateFromJson(data2);
}
}
toJSON() {
2018-07-08 07:16:17 -06:00
return { accessToken: this.accessToken.toJSON(), refreshToken: this.refreshToken.toJSON() };
}
2018-08-13 15:11:36 +03:00
@action
updateFromJson(json: any) {
this.accessToken.token = json.accessToken;
this.refreshToken.token = json.refreshToken;
}
}