You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

81 lines
2.4 KiB

1 year ago
import router from "../router/index.js";
import { get, post } from "../request/index.js";
import jwt_decode from "../lib/jwt-decode/jwt-decode.esm.js";
import qs from "../lib/qs/shim.js";
import { useAppStore } from "../store/index.js";
import { refreshRouter } from "../router/index.js";
import Enumerable from "linq";
import { connection } from "../signalr/index.js";
const isLogin = async () => {
const appStore = useAppStore();
// 有 token,判断是否过期,失败设置 token 为 null
if (appStore.token) {
const exp = new Date(jwt_decode(appStore.token).exp * 1000);
if (exp > new Date()) {
return true;
} else {
appStore.token = null;
}
}
return false;
};
const login = async (data) => {
const url = "connect-token";
const appStore = useAppStore();
const result = await post(url, data, { headers: { "Content-Type": "application/x-www-form-urlencoded" } }, true);
if (!result.errors) {
appStore.token = result.data.access_token;
setRefreshToken(result.data.refresh_token);
appStore.user = await getUser();
await refreshRouter();
const redirect = router.currentRoute.value.query?.redirect ?? "/";
router.push(redirect);
}
return result;
};
const logout = () => {
const appStore = useAppStore();
appStore.token = null;
removeRefreshToken();
router.push({ path: "/login", query: { redirect: router.currentRoute.value.fullPath } });
};
const getUser = async () => {
const result = await get("abp/application-configuration");
const data = result.data;
const user = {};
user.name = data.currentUser.userName;
user.email = data.currentUser.email;
user.roles = data.currentUser.roles;
const menus = (await get("base/role-menus")).data;
user.permissions = menus.items;
return user;
};
const hasPermission = (to) => {
const appStore = useAppStore();
const permission = to.meta?.permission;
if (permission) {
const hasPermission = Enumerable.from(appStore.user.permissions).any((o) => o.number === permission);
return hasPermission;
} else {
return true;
}
};
const refreshTokenKey = "refresh_token";
const getRefreshToken = () => localStorage.getItem(refreshTokenKey);
const setRefreshToken = (refreshToken) => localStorage.setItem(refreshTokenKey, refreshToken);
const removeRefreshToken = () => {
localStorage.removeItem(refreshTokenKey);
connection.stop();
};
export { isLogin, login, logout, getUser, hasPermission };