ppob-frontend/src/store/authentication.js
2021-12-09 23:06:16 +07:00

65 lines
1.3 KiB
JavaScript

import {makeAutoObservable, runInAction} from "mobx";
import {TokenUtil} from "../utils/token";
import {http} from "../utils/http";
export class Authentication {
isLoggedIn = false;
isLoginLoading = false;
ctx;
accessToken = '';
constructor(ctx) {
this.ctx = ctx;
makeAutoObservable(this);
}
get isLoggedIn() {
return !!this.accessToken;
}
get userData() {
const defaultValue = {
role: '',
user_id: '',
username: '',
};
try {
console.log(JSON.parse(atob(this.accessToken.split('.')[1])), "isi jwt")
return JSON.parse(atob(this.accessToken.split('.')[1]));
} catch (err) {
return defaultValue;
}
}
async login({username, password}) {
runInAction(() => {
this.isLoginLoading = true;
});
try {
const result = await http.post('/auth/login').send({username, password});
TokenUtil.setAccessToken(result.body.access_token);
TokenUtil.persistToken();
runInAction(() => {
this.isLoginLoading = false;
this.isLoggedIn = true;
});
} catch (e) {
runInAction(() => {
this.isLoginLoading = false;
});
console.error(e);
throw e;
}
}
logout() {
TokenUtil.clearAccessToken();
TokenUtil.persistToken();
this.isLoggedIn = false;
}
}