up
This commit is contained in:
Executable
+53
@@ -0,0 +1,53 @@
|
||||
/**
|
||||
* 用户ID管理工具
|
||||
* 为每个匿名用户生成永久userid并存储到localStorage
|
||||
*/
|
||||
|
||||
const USER_ID_KEY = 'a_stock_tracker_user_id';
|
||||
|
||||
/**
|
||||
* 获取或生成用户ID
|
||||
* 如果localStorage中已有则返回,否则生成新的UUID
|
||||
*/
|
||||
export function getUserId(): string {
|
||||
if (typeof window === 'undefined') {
|
||||
return '';
|
||||
}
|
||||
|
||||
let userId = localStorage.getItem(USER_ID_KEY);
|
||||
|
||||
if (!userId) {
|
||||
// 生成UUID v4
|
||||
userId = crypto.randomUUID ? crypto.randomUUID() : generateUUID();
|
||||
localStorage.setItem(USER_ID_KEY, userId);
|
||||
}
|
||||
|
||||
return userId;
|
||||
}
|
||||
|
||||
/**
|
||||
* 手动生成UUID v4(兼容不支持crypto.randomUUID的环境)
|
||||
*/
|
||||
function generateUUID(): string {
|
||||
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (c) => {
|
||||
const r = Math.random() * 16 | 0;
|
||||
const v = c === 'x' ? r : (r & 0x3 | 0x8);
|
||||
return v.toString(16);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 更新最后访问时间
|
||||
*/
|
||||
export function updateLastAccessed(collectionId: number): void {
|
||||
const key = `last_accessed_${collectionId}`;
|
||||
localStorage.setItem(key, new Date().toISOString());
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取最后访问时间
|
||||
*/
|
||||
export function getLastAccessed(collectionId: number): string | null {
|
||||
const key = `last_accessed_${collectionId}`;
|
||||
return localStorage.getItem(key);
|
||||
}
|
||||
Reference in New Issue
Block a user