stock-management-demo/src/stores/auth.js

49 lines
1.1 KiB
JavaScript

import { defineStore } from 'pinia';
import axios from 'axios';
export const useAuthStore = defineStore('auth', {
state: () => ({
isAuthenticated: false,
user: null,
loading: false, // Optional: track loading state
error: null, // Optional: track errors
}),
actions: {
async checkAuthStatus()
{
this.loading = true;
this.error = null;
try
{
const res = await axios.get('/auth/check-auth');
if (res.data.isAuthenticated)
{
this.isAuthenticated = true;
this.user = res.data.user;
}
else
{
this.isAuthenticated = false;
this.user = null;
}
}
catch (error)
{
console.error('Failed to check authentication status:', error);
this.error = 'Could not verify login status.';
this.isAuthenticated = false;
this.user = null;
}
finally
{
this.loading = false;
}
},
// Action to manually set user as logged out (e.g., after logout)
logout()
{
this.isAuthenticated = false;
this.user = null;
}
},
});