feat: implement login

This commit is contained in:
caturbgs
2021-12-09 23:00:56 +07:00
parent b346e1fdbd
commit 84d3085c0c
8 changed files with 124 additions and 152 deletions

View File

@@ -1,27 +1,63 @@
import {makeAutoObservable} from "mobx";
import {makeAutoObservable, runInAction} from "mobx";
import {TokenUtil} from "../utils/token";
import {http} from "../utils/http";
export class Authentication {
isLoggedIn = false;
isLoginLoading = false;
ctx;
accessToken = '';
refreshToken = '';
constructor(ctx) {
this.ctx = ctx;
makeAutoObservable(this);
}
get isLoggedIn() {
return !!this.refreshToken;
return !!this.accessToken;
}
setInitialToken(accessToken, refreshToken) {
this.setToken(accessToken, refreshToken);
get userData() {
const defaultValue = {
role: '',
user_id: '',
username: '',
};
try {
return JSON.parse(atob(this.accessToken.split('.')[1]));
} catch (err) {
return defaultValue;
}
}
setToken(accessToken, refreshToken) {
this.accessToken = accessToken;
this.refreshToken = refreshToken;
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;
}
}

View File

@@ -4,6 +4,7 @@ import {User} from "./user";
import {Membership} from "./membership";
import {Product} from "./product";
import {Categories} from "./categories";
import {TokenUtil} from "../utils/token";
export class Store {
ui = new UI(this);
@@ -14,5 +15,9 @@ export class Store {
categories = new Categories(this);
constructor() {
TokenUtil.loadToken();
if (TokenUtil.accessToken) {
this.authentication.isLoggedIn = true;
}
}
}

View File

@@ -6,7 +6,7 @@ export class User {
@action
async getData() {
this.data = (await http.get('/product')).body.data;
this.data = (await http.get('/user')).body.data;
}
}