feat:添加登录功能
This commit is contained in:
@@ -1,5 +1,7 @@
|
||||
import { defineStore } from 'pinia';
|
||||
|
||||
const STORAGE_KEY = 'ai-bill/auth-session';
|
||||
|
||||
type AuthStatus = 'authenticated' | 'guest';
|
||||
|
||||
interface UserProfile {
|
||||
@@ -30,12 +32,47 @@ export const useAuthStore = defineStore('auth', {
|
||||
this.accessToken = tokens.accessToken;
|
||||
this.refreshToken = tokens.refreshToken;
|
||||
this.profile = profile;
|
||||
if (typeof window !== 'undefined') {
|
||||
localStorage.setItem(
|
||||
STORAGE_KEY,
|
||||
JSON.stringify({
|
||||
status: 'authenticated',
|
||||
accessToken: tokens.accessToken,
|
||||
refreshToken: tokens.refreshToken,
|
||||
profile
|
||||
})
|
||||
);
|
||||
}
|
||||
},
|
||||
clearSession() {
|
||||
this.status = 'guest';
|
||||
this.accessToken = undefined;
|
||||
this.refreshToken = undefined;
|
||||
this.profile = undefined;
|
||||
if (typeof window !== 'undefined') {
|
||||
localStorage.removeItem(STORAGE_KEY);
|
||||
}
|
||||
},
|
||||
initialize() {
|
||||
if (typeof window === 'undefined') {
|
||||
return;
|
||||
}
|
||||
const raw = localStorage.getItem(STORAGE_KEY);
|
||||
if (!raw) {
|
||||
return;
|
||||
}
|
||||
try {
|
||||
const stored = JSON.parse(raw) as { status: AuthStatus; accessToken: string; refreshToken: string; profile: UserProfile };
|
||||
if (stored.status === 'authenticated' && stored.accessToken && stored.refreshToken && stored.profile) {
|
||||
this.status = stored.status;
|
||||
this.accessToken = stored.accessToken;
|
||||
this.refreshToken = stored.refreshToken;
|
||||
this.profile = stored.profile;
|
||||
}
|
||||
} catch (error) {
|
||||
console.warn('Failed to restore auth session', error);
|
||||
localStorage.removeItem(STORAGE_KEY);
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user