admin-vben5/packages/stores/src/setup.ts
Netfan aa27a2f7a1
feat: encrypt the privacy data when it is persisted (#6056)
* 对私密数据持久化时执行加密
* 将锁屏密码合并到accessStore中进行加密
2025-04-27 20:59:10 +08:00

61 lines
1.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 { Pinia } from 'pinia';
import type { App } from 'vue';
import { createPinia } from 'pinia';
import SecureLS from 'secure-ls';
let pinia: Pinia;
export interface InitStoreOptions {
/**
* @zh_CN 应用名,由于 @vben/stores 是公用的后续可能有多个app为了防止多个app缓存冲突可在这里配置应用名,应用名将被用于持久化的前缀
*/
namespace: string;
}
/**
* @zh_CN 初始化pinia
*/
export async function initStores(app: App, options: InitStoreOptions) {
const { createPersistedState } = await import('pinia-plugin-persistedstate');
pinia = createPinia();
const { namespace } = options;
const ls = new SecureLS({
encodingType: 'aes',
encryptionSecret: import.meta.env.VITE_APP_STORE_SECURE_KEY,
isCompression: true,
// @ts-ignore secure-ls does not have a type definition for this
metaKey: `${namespace}-secure-meta`,
});
pinia.use(
createPersistedState({
// key $appName-$store.id
key: (storeKey) => `${namespace}-${storeKey}`,
storage: import.meta.env.DEV
? localStorage
: {
getItem(key) {
return ls.get(key);
},
setItem(key, value) {
ls.set(key, value);
},
},
}),
);
app.use(pinia);
return pinia;
}
export function resetAllStores() {
if (!pinia) {
console.error('Pinia is not installed');
return;
}
const allStores = (pinia as any)._s;
for (const [_key, store] of allStores) {
store.$reset();
}
}