wpw-final/frontend/src/stores/auth.ts
2022-12-02 20:40:23 +07:00

73 lines
1.8 KiB
TypeScript

import { defineStore } from 'pinia';
import /* * as */structs from '@thriftgen/structs_types';
import { deleteCookie, getCookie, setCookie } from '@/utils/cookie';
import { CookieKeyAuthToken, CookieKeyTrackToken } from '@/hub/hub';
import { RemovableRef, useLocalStorage } from '@vueuse/core';
export type Auth = {
trkToken: string;
token: string;
profile?: structs.User;
};
type AuthState = {
trkToken: RemovableRef<string>;
token: RemovableRef<string>;
profile?: structs.User;
};
export function isValidToken(token: string): boolean {
return token != '' && token != undefined && token != 'undefined';
}
export const useAuth = defineStore({
id: 'user',
state: () =>
<AuthState>{
trkToken: useLocalStorage('trkToken', ''),
token: useLocalStorage('token', ''),
profile: undefined,
},
getters: {
hasProfile(state): boolean {
return state.profile != null;
},
hasToken(state): boolean {
return isValidToken(this.trackToken);
},
isLoggedIn(state): boolean {
return this.hasToken && this.hasProfile;
},
trackToken(state): string {
return state.trkToken;
},
authToken(state): string {
return state.token;
},
},
actions: {
setTrackToken(token?: string) {
if (!token) return;
console.log('set track token:', token);
setCookie(CookieKeyTrackToken, token);
this.trkToken = token;
},
setAuthToken(token?: string) {
if (!token) return;
console.log('set auth token:', token);
setCookie(CookieKeyAuthToken, token);
this.token = token;
},
setProfile(profile: structs.User) {
this.profile = profile;
},
logout() {
deleteCookie(CookieKeyAuthToken);
deleteCookie(CookieKeyTrackToken);
this.profile = undefined;
this.token = '';
this.trkToken = '';
},
},
});