feat: implement login
This commit is contained in:
@@ -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;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user