homebox/frontend/stores/auth.ts

50 lines
1.2 KiB
TypeScript
Raw Normal View History

import { defineStore } from "pinia";
import { useLocalStorage } from "@vueuse/core";
import { UserApi } from "~~/lib/api/user";
import { UserOut } from "~~/lib/api/types/data-contracts";
2022-09-01 22:32:03 +00:00
export const useAuthStore = defineStore("auth", {
2022-09-01 22:32:03 +00:00
state: () => ({
token: useLocalStorage("pinia/auth/token", ""),
expires: useLocalStorage("pinia/auth/expires", ""),
self: null as UserOut | null,
2022-09-01 22:32:03 +00:00
}),
getters: {
2022-09-03 09:17:57 +00:00
isTokenExpired: state => {
2022-09-01 22:32:03 +00:00
if (!state.expires) {
return true;
}
if (typeof state.expires === "string") {
2022-09-01 22:32:03 +00:00
return new Date(state.expires) < new Date();
}
return state.expires < new Date();
},
},
actions: {
async logout(api: UserApi) {
const result = await api.logout();
if (result.error) {
return result;
}
this.token = "";
this.expires = "";
this.self = null;
2022-09-01 22:32:03 +00:00
return result;
},
2022-09-04 06:19:13 +00:00
/**
* clearSession is used when the user cannot be logged out via the API and
* must clear it's local session, usually when a 401 is received.
*/
clearSession() {
this.token = "";
this.expires = "";
navigateTo("/");
2022-09-04 06:19:13 +00:00
},
2022-09-01 22:32:03 +00:00
},
});