Files
front-pc/utils/RefreshToken.ts

76 lines
2.5 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import type { AppMemberUserInfoRespVO } from "@/api/common/types";
export type onRefreshTokenResponse = (
data: AxiosResponse | boolean
) => { token: string; refreshToken: string } | false;
class RefreshToken {
static instance: RefreshToken;
static SOTRAGE_REFRESH_TOKEN_KEY = "kl-tk";
static SOTRAGE_TOKENKEY = "kl-rfk";
static SOTRAGE_USERID = "kl-userId";
static SOTRAGE_USERNAME = "kl-userName";
static SOTRAGE_USERINFO = "kl-userInfo";
public pending = false;
public callbacks: any[] = [];
protected constructor(config: TRefreshTokenConstructorConfig) {
RefreshToken.SOTRAGE_REFRESH_TOKEN_KEY = config?.refreshTokenKey || "kl-tk";
RefreshToken.SOTRAGE_TOKENKEY = config?.refreshTokenKey || "kl-rfk";
RefreshToken.SOTRAGE_USERID = config?.refreshTokenKey || "kl-userId";
}
// 设置token
static setToken(token: string, refreshToken: string) {
window.localStorage.setItem(RefreshToken.SOTRAGE_TOKENKEY, token);
window.localStorage.setItem(
RefreshToken.SOTRAGE_REFRESH_TOKEN_KEY,
refreshToken
);
}
// 清除token
static removeToken() {
window.localStorage.removeItem(RefreshToken.SOTRAGE_TOKENKEY);
window.localStorage.removeItem(RefreshToken.SOTRAGE_REFRESH_TOKEN_KEY);
//清除token一起把userID也清除了
window.localStorage.removeItem(RefreshToken.SOTRAGE_USERID);
window.localStorage.removeItem(RefreshToken.SOTRAGE_USERNAME);
window.localStorage.removeItem(RefreshToken.SOTRAGE_USERINFO);
}
//设置userID
static setUserId(userId: string) {
window.localStorage.setItem(RefreshToken.SOTRAGE_USERID, userId);
}
static setUserName(userName: string) {
window.localStorage.setItem(RefreshToken.SOTRAGE_USERNAME, userName);
}
static setUserInfo(userInfo: AppMemberUserInfoRespVO) {
window.localStorage.setItem(
RefreshToken.SOTRAGE_USERINFO,
JSON.stringify(userInfo)
);
}
// 获取token
static getToken() {
const token =
window.localStorage.getItem(RefreshToken.SOTRAGE_TOKENKEY) || "";
const refreshToken =
window.localStorage.getItem(RefreshToken.SOTRAGE_REFRESH_TOKEN_KEY) || "";
const userId =
window.localStorage.getItem(RefreshToken.SOTRAGE_USERID) || "";
const userName =
window.localStorage.getItem(RefreshToken.SOTRAGE_USERNAME) || "";
const userInfo =
window.localStorage.getItem(RefreshToken.SOTRAGE_USERINFO) || "";
return {
token,
refreshToken,
userId,
userName,
userInfo: userInfo ? JSON.parse(userInfo) : {},
};
}
}
export default RefreshToken;