fix auth
This commit is contained in:
@@ -1,9 +1,11 @@
|
||||
import { defineStore } from 'pinia'
|
||||
import axios from 'axios'
|
||||
import { inject, ref } from 'vue'
|
||||
import { useAuthStore } from './auth'
|
||||
|
||||
export const useAPIStore = defineStore('api', () => {
|
||||
const API_BASE_URL = inject('apiBaseURL')
|
||||
const authStore = useAuthStore()
|
||||
|
||||
const token = ref()
|
||||
const gameQueryParameters = ref({
|
||||
@@ -16,16 +18,35 @@ export const useAPIStore = defineStore('api', () => {
|
||||
},
|
||||
})
|
||||
|
||||
const resetExpiryOnSuccess = (response) => {
|
||||
if (authStore.isLoggedIn && !authStore.isTokenAlmostExpired()) {
|
||||
authStore.resetTokenExpiry()
|
||||
}
|
||||
return response
|
||||
}
|
||||
|
||||
axios.interceptors.response.use(resetExpiryOnSuccess)
|
||||
|
||||
const initializeAxiosHeaders = () => {
|
||||
const storedToken = localStorage.getItem('token')
|
||||
if (storedToken) {
|
||||
axios.defaults.headers.common['Authorization'] = `Bearer ${storedToken}`
|
||||
}
|
||||
}
|
||||
|
||||
initializeAxiosHeaders()
|
||||
|
||||
const postLogin = async (credentials) => {
|
||||
const response = await axios.post(`${API_BASE_URL}/login`, credentials)
|
||||
const response = await axios.post(`${API_BASE_URL}/login`, credentials)
|
||||
|
||||
if (!response.data.token) throw response
|
||||
if (!response.data.token) throw response
|
||||
|
||||
token.value = response.data.token
|
||||
axios.defaults.headers.common['Authorization'] = `Bearer ${token.value}`
|
||||
token.value = response.data.token
|
||||
axios.defaults.headers.common['Authorization'] = `Bearer ${token.value}`
|
||||
|
||||
return response
|
||||
}
|
||||
|
||||
return response
|
||||
}
|
||||
const postLogout = async () => {
|
||||
await axios.post(`${API_BASE_URL}/logout`)
|
||||
token.value = undefined
|
||||
|
||||
Reference in New Issue
Block a user