68 lines
1.7 KiB
TypeScript
68 lines
1.7 KiB
TypeScript
import CryptoJS from 'crypto-js';
|
|
import { APP_CONFIG } from '@/config';
|
|
|
|
interface StorageEnvelope<T> {
|
|
value: T;
|
|
expiresAt: number;
|
|
}
|
|
|
|
const encrypt = (value: unknown) => {
|
|
return CryptoJS.AES.encrypt(JSON.stringify(value), APP_CONFIG.STORAGE_ENCRYPTION_KEY).toString();
|
|
};
|
|
|
|
const decrypt = <T>(value: string): T | null => {
|
|
try {
|
|
const decrypted = CryptoJS.AES.decrypt(value, APP_CONFIG.STORAGE_ENCRYPTION_KEY)
|
|
.toString(CryptoJS.enc.Utf8);
|
|
return decrypted ? JSON.parse(decrypted) as T : null;
|
|
} catch (error) {
|
|
return null;
|
|
}
|
|
};
|
|
|
|
export const encryptedStorage = {
|
|
set<T>(key: string, value: T, expiresInSeconds = 0) {
|
|
const envelope: StorageEnvelope<T> = {
|
|
value,
|
|
expiresAt: expiresInSeconds > 0 ? Date.now() + expiresInSeconds * 1000 : 0
|
|
};
|
|
uni.setStorageSync(key, encrypt(envelope));
|
|
},
|
|
|
|
get<T>(key: string): T | null {
|
|
const encryptedValue = uni.getStorageSync(key);
|
|
if (typeof encryptedValue !== 'string' || !encryptedValue) return null;
|
|
|
|
const envelope = decrypt<StorageEnvelope<T>>(encryptedValue);
|
|
if (!envelope || typeof envelope !== 'object' || !('value' in envelope)) {
|
|
uni.removeStorageSync(key);
|
|
return null;
|
|
}
|
|
|
|
if (envelope.expiresAt > 0 && envelope.expiresAt <= Date.now()) {
|
|
uni.removeStorageSync(key);
|
|
return null;
|
|
}
|
|
|
|
return envelope.value;
|
|
},
|
|
|
|
remove(key: string) {
|
|
uni.removeStorageSync(key);
|
|
}
|
|
};
|
|
|
|
export const authStorage = {
|
|
getToken() {
|
|
return encryptedStorage.get<string>(APP_CONFIG.STORAGE_TOKEN_KEY) || '';
|
|
},
|
|
|
|
setToken(token: string, expiresInSeconds = 0) {
|
|
encryptedStorage.set(APP_CONFIG.STORAGE_TOKEN_KEY, token, expiresInSeconds);
|
|
},
|
|
|
|
clearToken() {
|
|
encryptedStorage.remove(APP_CONFIG.STORAGE_TOKEN_KEY);
|
|
}
|
|
};
|