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.

89 lines
2.8 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;
removeAccessToken();
1 year ago
}
}
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;
removeAccessToken();
1 year ago
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.id = data.currentUser.id;
user.userName = data.currentUser.userName;
1 year ago
user.email = data.currentUser.email;
user.phoneNumber = data.currentUser.phoneNumber;
1 year ago
user.roles = data.currentUser.roles;
user.permissions = data.auth.policies;
user.localization = data.localization;
1 year ago
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 accessTokenKey = "access_token";
const getAccessToken = () => localStorage.getItem(accessTokenKey);
const setAccessToken = (token) => localStorage.setItem(accessTokenKey, token);
const removeAccessToken = () => localStorage.removeItem(accessTokenKey);
1 year ago
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, getAccessToken, setAccessToken, setRefreshToken, getUser, hasPermission };