2025-09-09 23:19:17 +03:00
|
|
|
import { defineStore } from 'pinia';
|
|
|
|
|
import { computed, ref } from 'vue';
|
2025-09-10 23:29:27 +03:00
|
|
|
import { apiClient } from '@/services/apiClient';
|
|
|
|
|
import router from '@/router/index.js';
|
2025-09-09 23:19:17 +03:00
|
|
|
|
|
|
|
|
export const useAuthStore = defineStore('auth', () => {
|
|
|
|
|
// state
|
2025-09-10 23:29:27 +03:00
|
|
|
const accessToken = ref(null);
|
|
|
|
|
const user = ref(null);
|
2025-09-09 23:19:17 +03:00
|
|
|
|
|
|
|
|
// getters
|
2025-09-10 23:29:27 +03:00
|
|
|
const isAuthenticated = computed(() => !!accessToken.value);
|
2025-09-09 23:19:17 +03:00
|
|
|
|
|
|
|
|
// actions
|
2025-09-10 23:29:27 +03:00
|
|
|
const setToken = (token) => {
|
|
|
|
|
accessToken.value = token;
|
|
|
|
|
};
|
|
|
|
|
|
2025-09-09 23:19:17 +03:00
|
|
|
const login = async (email, password) => {
|
|
|
|
|
try {
|
2025-09-10 23:29:27 +03:00
|
|
|
const response = await apiClient.post('/user/auth/login', { email, password });
|
|
|
|
|
const { access_token, user: userData } = response;
|
|
|
|
|
|
|
|
|
|
setToken(access_token);
|
|
|
|
|
user.value = userData || null;
|
|
|
|
|
|
|
|
|
|
router.push('/');
|
|
|
|
|
} catch (error) {
|
|
|
|
|
console.error('Login error:', error);
|
|
|
|
|
}
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
const logout = async () => {
|
|
|
|
|
accessToken.value = null;
|
|
|
|
|
user.value = null;
|
|
|
|
|
try {
|
|
|
|
|
await apiClient.post('/user/auth/logout');
|
2025-09-09 23:19:17 +03:00
|
|
|
} catch (error) {
|
2025-09-10 23:29:27 +03:00
|
|
|
console.error('Logout error:', error);
|
2025-09-09 23:19:17 +03:00
|
|
|
}
|
2025-09-10 23:29:27 +03:00
|
|
|
router.push('/startPage');
|
|
|
|
|
};
|
2025-09-09 23:19:17 +03:00
|
|
|
|
2025-09-10 23:29:27 +03:00
|
|
|
const forceLogout = () => {
|
|
|
|
|
accessToken.value = null;
|
|
|
|
|
user.value = null;
|
|
|
|
|
router.push('/startPage');
|
|
|
|
|
};
|
2025-09-09 23:19:17 +03:00
|
|
|
|
|
|
|
|
return {
|
|
|
|
|
accessToken,
|
|
|
|
|
user,
|
|
|
|
|
isAuthenticated,
|
2025-09-10 23:29:27 +03:00
|
|
|
setToken,
|
2025-09-09 23:19:17 +03:00
|
|
|
login,
|
2025-09-10 23:29:27 +03:00
|
|
|
logout,
|
|
|
|
|
forceLogout,
|
|
|
|
|
};
|
|
|
|
|
});
|