2021-11-11 10:35:11 +00:00
|
|
|
import { AxiosResponse } from 'axios';
|
2021-05-25 14:13:15 +00:00
|
|
|
import { defineStore } from 'pinia';
|
|
|
|
import { api } from '../internal';
|
2021-11-11 10:35:11 +00:00
|
|
|
import { isAxiosError, useMainStore } from '.';
|
2021-05-25 14:13:15 +00:00
|
|
|
|
|
|
|
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) {
|
2021-11-11 10:35:11 +00:00
|
|
|
// Ignore 401, as this means we are already logged out, throw all other
|
|
|
|
if (!isAxiosError(error, 401)) throw error;
|
2021-05-25 14:13:15 +00:00
|
|
|
}
|
|
|
|
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;
|
|
|
|
}
|
|
|
|
},
|
|
|
|
},
|
|
|
|
});
|