import { get , post } from "../api" ; import { ActionTree , Module } from "vuex" ; import { AuthState , IntervalType , RootState } from "./types" ; const AUTH_REFRESH_INTERVAL = 1000 * 60 * 15 ; export const AuthStore = { namespaced : true , state : { apiKey : null , loadedInitialAuth : false , authRefreshInterval : null , userId : null , } , actions : { async loadInitialAuth ( { dispatch , commit , state } ) { if ( state . loadedInitialAuth ) return ; const storedKey = localStorage . getItem ( "apiKey" ) ; if ( storedKey ) { try { const result = await post ( "auth/validate-key" , { key : storedKey } ) ; if ( result . valid ) { await dispatch ( "setApiKey" , { key : storedKey , userId : result . userId } ) ; return ; } } catch { } console . log ( "Unable to validate key, removing from localStorage" ) ; localStorage . removeItem ( "apiKey" ) ; } commit ( "markInitialAuthLoaded" ) ; } , setApiKey ( { commit , state , dispatch } , { key , userId } ) { localStorage . setItem ( "apiKey" , key ) ; commit ( "setApiKey" , { key , userId } ) ; dispatch ( "startAuthAutoRefresh" ) ; } , async startAuthAutoRefresh ( { commit , state , dispatch } ) { await dispatch ( "endAuthAutoRefresh" ) ; const refreshInterval = setInterval ( async ( ) => { await post ( "auth/refresh" , { key : state . apiKey } ) ; } , AUTH_REFRESH_INTERVAL ) ; commit ( "setAuthRefreshInterval" , refreshInterval ) ; } , endAuthAutoRefresh ( { commit , state } ) { if ( state . authRefreshInterval ) { window . clearInterval ( state . authRefreshInterval ) ; } commit ( "setAuthRefreshInterval" , null ) ; } , async clearApiKey ( { commit , dispatch } ) { await dispatch ( "endAuthAutoRefresh" ) ; localStorage . removeItem ( "apiKey" ) ; commit ( "setApiKey" , { key : null , userId : null } ) ; } , async logout ( { dispatch } ) { await post ( "auth/logout" ) ; await dispatch ( "clearApiKey" ) ; } , async expiredLogin ( { dispatch } ) { await dispatch ( "clearApiKey" ) ; window . location . assign ( "/?error=expiredLogin" ) ; } , } , mutations : { setApiKey ( state , { key , userId } ) { state . apiKey = key ; state . userId = userId ; } , setAuthRefreshInterval ( state , interval ) { state . authRefreshInterval = interval ; } , markInitialAuthLoaded ( state ) { state . loadedInitialAuth = true ; } , } , } ;