1
This commit is contained in:
52
src/shared/auth.ts
Normal file
52
src/shared/auth.ts
Normal file
@@ -0,0 +1,52 @@
|
||||
const AUTH_TOKEN_KEY = 'token';
|
||||
const MOCK_TOKEN = 'mock-extension-token';
|
||||
|
||||
/** 获取当前登录 token。 */
|
||||
export async function getToken(): Promise<string | null> {
|
||||
const storage = getChromeStorage();
|
||||
|
||||
if (storage) {
|
||||
const result = await storage.get(AUTH_TOKEN_KEY);
|
||||
const value = result[AUTH_TOKEN_KEY];
|
||||
return typeof value === 'string' && value.length > 0 ? value : null;
|
||||
}
|
||||
|
||||
return window.localStorage.getItem(AUTH_TOKEN_KEY);
|
||||
}
|
||||
|
||||
/** 模拟登录,写入一个临时 token,方便后续替换真实登录逻辑。 */
|
||||
export async function mockLogin(): Promise<string> {
|
||||
await setToken(MOCK_TOKEN);
|
||||
return MOCK_TOKEN;
|
||||
}
|
||||
|
||||
/** 清除当前登录 token。 */
|
||||
export async function logout(): Promise<void> {
|
||||
const storage = getChromeStorage();
|
||||
|
||||
if (storage) {
|
||||
await storage.remove(AUTH_TOKEN_KEY);
|
||||
return;
|
||||
}
|
||||
|
||||
window.localStorage.removeItem(AUTH_TOKEN_KEY);
|
||||
}
|
||||
|
||||
async function setToken(token: string): Promise<void> {
|
||||
const storage = getChromeStorage();
|
||||
|
||||
if (storage) {
|
||||
await storage.set({ [AUTH_TOKEN_KEY]: token });
|
||||
return;
|
||||
}
|
||||
|
||||
window.localStorage.setItem(AUTH_TOKEN_KEY, token);
|
||||
}
|
||||
|
||||
function getChromeStorage(): chrome.storage.StorageArea | null {
|
||||
if (typeof chrome === 'undefined' || !chrome.storage?.local) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return chrome.storage.local;
|
||||
}
|
||||
Reference in New Issue
Block a user