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; } }