70 lines
1.8 KiB
TypeScript
70 lines
1.8 KiB
TypeScript
|
import { AxiosError, AxiosResponse } from 'axios';
|
||
|
import { defineStore } from 'pinia';
|
||
|
import { api } from '../internal';
|
||
|
import { useMainStore } from '.';
|
||
|
|
||
|
export const useSessionStore = defineStore({
|
||
|
id: 'sessions',
|
||
|
|
||
|
state: () => ({}),
|
||
|
|
||
|
getters: {},
|
||
|
|
||
|
actions: {
|
||
|
async getSession(token: string) {
|
||
|
return await api
|
||
|
.get(`/auth/${token}`)
|
||
|
.then(({ data }: AxiosResponse<FG.Session>) => data)
|
||
|
.catch(() => null);
|
||
|
},
|
||
|
|
||
|
async getSessions() {
|
||
|
try {
|
||
|
const { data } = await api.get<FG.Session[]>('/auth');
|
||
|
data.forEach((session) => {
|
||
|
session.expires = new Date(session.expires);
|
||
|
});
|
||
|
|
||
|
const mainStore = useMainStore();
|
||
|
const currentSession = data.find((session) => {
|
||
|
return session.token === mainStore.session?.token;
|
||
|
});
|
||
|
if (currentSession) {
|
||
|
mainStore.session = currentSession;
|
||
|
}
|
||
|
return data;
|
||
|
} catch (error) {
|
||
|
return [] as FG.Session[];
|
||
|
}
|
||
|
},
|
||
|
|
||
|
async deleteSession(token: string) {
|
||
|
const mainStore = useMainStore();
|
||
|
if (token === mainStore.session?.token) return mainStore.logout();
|
||
|
|
||
|
try {
|
||
|
await api.delete(`/auth/${token}`);
|
||
|
return true;
|
||
|
} catch (error) {
|
||
|
if (!error || !('response' in error) || (<AxiosError>error).response?.status != 401)
|
||
|
throw error;
|
||
|
}
|
||
|
return false;
|
||
|
},
|
||
|
|
||
|
async updateSession(lifetime: number, token: string) {
|
||
|
try {
|
||
|
const { data } = await api.put<FG.Session>(`auth/${token}`, { value: lifetime });
|
||
|
data.expires = new Date(data.expires);
|
||
|
|
||
|
const mainStore = useMainStore();
|
||
|
if (mainStore.session?.token == data.token) mainStore.session = data;
|
||
|
|
||
|
return true;
|
||
|
} catch (error) {
|
||
|
return false;
|
||
|
}
|
||
|
},
|
||
|
},
|
||
|
});
|