modified: begushiybashkir/bbvue/src/main.js
modified: begushiybashkir/bbvue/src/stores/auth.js new file: begushiybashkir/bbvue/src/stores/helpers/api.js new file: begushiybashkir/bbvue/src/stores/index.js new file: begushiybashkir/bbvue/src/stores/plugins/persistence.js modified: begushiybashkir/bbvue/src/stores/user.js modified: serv_nginx/api_bb/internal/models/user.go new file: serv_nginx/api_bb/internal/models/workout.go fix save store, add helpers, add new models
This commit is contained in:
@@ -1,57 +1,45 @@
|
||||
// stores/auth.js
|
||||
import { defineStore } from 'pinia'
|
||||
import { ref, computed } from 'vue'
|
||||
import axios from 'axios'
|
||||
|
||||
const AUTH_API_URL = 'https://begushiybashkir.ru/api/v1/auth'
|
||||
import { apiClient, withLoading } from './helpers/api'
|
||||
|
||||
export const useAuthStore = defineStore('auth', () => {
|
||||
// State
|
||||
const user = ref(null)
|
||||
const token = ref(localStorage.getItem('auth_token') || '')
|
||||
const loading = ref(false)
|
||||
const error = ref('')
|
||||
const initialized = ref(false)
|
||||
|
||||
// Computed свойства
|
||||
// Getters
|
||||
const isAuthenticated = computed(() => !!token.value && !!user.value)
|
||||
const userFullName = computed(() => {
|
||||
if (!user.value) return ''
|
||||
return `${user.value.firstName} ${user.value.lastName}`
|
||||
})
|
||||
const userFullName = computed(() =>
|
||||
user.value ? `${user.value.firstName} ${user.value.lastName}` : ''
|
||||
)
|
||||
|
||||
// Установка токена
|
||||
// Actions
|
||||
const setToken = (newToken) => {
|
||||
token.value = newToken
|
||||
localStorage.setItem('auth_token', newToken)
|
||||
// Устанавливаем токен в заголовки axios по умолчанию
|
||||
axios.defaults.headers.common['Authorization'] = `Bearer ${newToken}`
|
||||
}
|
||||
|
||||
// Очистка токена
|
||||
const clearToken = () => {
|
||||
const clearAuth = () => {
|
||||
token.value = ''
|
||||
user.value = null
|
||||
localStorage.removeItem('auth_token')
|
||||
delete axios.defaults.headers.common['Authorization']
|
||||
}
|
||||
|
||||
// Установка пользователя
|
||||
const setUser = (userData) => {
|
||||
user.value = userData
|
||||
}
|
||||
|
||||
// Очистка пользователя
|
||||
const clearUser = () => {
|
||||
user.value = null
|
||||
}
|
||||
|
||||
// Регистрация
|
||||
const register = async (userData) => {
|
||||
loading.value = true
|
||||
error.value = ''
|
||||
|
||||
try {
|
||||
const response = await axios.post(`${AUTH_API_URL}/register`, userData)
|
||||
|
||||
// После успешной регистрации автоматически логинимся
|
||||
const loginResponse = await axios.post(`${AUTH_API_URL}/login`, {
|
||||
// Передаем store объект с loading и error
|
||||
return withLoading({ loading, error }, async () => {
|
||||
await apiClient.post('/auth/register', userData)
|
||||
|
||||
// Auto-login after registration
|
||||
const loginResponse = await apiClient.post('/auth/login', {
|
||||
email: userData.email,
|
||||
password: userData.password
|
||||
})
|
||||
@@ -60,89 +48,62 @@ export const useAuthStore = defineStore('auth', () => {
|
||||
setToken(authToken)
|
||||
setUser(userInfo)
|
||||
|
||||
return { success: true, data: response.data }
|
||||
} catch (err) {
|
||||
error.value = err.response?.data?.message || err.message || 'Ошибка регистрации'
|
||||
return { success: false, error: error.value }
|
||||
} finally {
|
||||
loading.value = false
|
||||
}
|
||||
return { success: true }
|
||||
})
|
||||
}
|
||||
|
||||
// Логин
|
||||
const login = async (credentials) => {
|
||||
loading.value = true
|
||||
error.value = ''
|
||||
|
||||
try {
|
||||
const response = await axios.post(`${AUTH_API_URL}/login`, credentials)
|
||||
return withLoading({ loading, error }, async () => {
|
||||
const response = await apiClient.post('/auth/login', credentials)
|
||||
const { token: authToken, user: userInfo } = response.data
|
||||
console.log("authToken: " + authToken + "userInfo: " + userInfo)
|
||||
|
||||
setToken(authToken)
|
||||
setUser(userInfo)
|
||||
|
||||
return { success: true, data: response.data }
|
||||
} catch (err) {
|
||||
error.value = err.response?.data?.message || 'Ошибка входа'
|
||||
return { success: false, error: error.value }
|
||||
} finally {
|
||||
loading.value = false
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// Выход
|
||||
const logout = async () => {
|
||||
loading.value = true
|
||||
|
||||
try {
|
||||
await axios.post(`${AUTH_API_URL}/logout`, {}, {
|
||||
headers: {
|
||||
'Authorization': `Bearer ${token.value}`
|
||||
}
|
||||
})
|
||||
} catch (err) {
|
||||
console.error('Ошибка при выходе:', err)
|
||||
} finally {
|
||||
clearToken()
|
||||
clearUser()
|
||||
loading.value = false
|
||||
}
|
||||
return withLoading({ loading, error }, async () => {
|
||||
try {
|
||||
await apiClient.post('/auth/logout')
|
||||
} catch (err) {
|
||||
console.error('Logout error:', err)
|
||||
} finally {
|
||||
clearAuth()
|
||||
}
|
||||
return { success: true }
|
||||
})
|
||||
}
|
||||
|
||||
// Получение профиля
|
||||
const fetchProfile = async () => {
|
||||
loading.value = true
|
||||
error.value = ''
|
||||
|
||||
try {
|
||||
const response = await axios.get(`${AUTH_API_URL}/profile`)
|
||||
return withLoading({ loading, error }, async () => {
|
||||
const response = await apiClient.get('/user/profile')
|
||||
setUser(response.data)
|
||||
return { success: true, data: response.data }
|
||||
} catch (err) {
|
||||
error.value = err.response?.data?.message || err.message || 'Ошибка загрузки профиля'
|
||||
clearToken()
|
||||
clearUser()
|
||||
return { success: false, error: error.value }
|
||||
} finally {
|
||||
loading.value = false
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
const updateProfile = async (profileData) => {
|
||||
return withLoading({ loading, error }, async () => {
|
||||
const response = await apiClient.post('/user/editProfile', profileData)
|
||||
setUser(response.data)
|
||||
return { success: true, data: response.data }
|
||||
})
|
||||
}
|
||||
|
||||
// Инициализация при загрузке приложения
|
||||
const initializeAuth = async () => {
|
||||
if (token.value) {
|
||||
// Восстанавливаем заголовок авторизации
|
||||
axios.defaults.headers.common['Authorization'] = `Bearer ${token.value}`
|
||||
try {
|
||||
// Загружаем данные пользователя
|
||||
await fetchProfile()
|
||||
} catch (error) {
|
||||
console.error('Ошибка инициализации авторизации:', error)
|
||||
// Если токен невалидный, очищаем его
|
||||
clearToken()
|
||||
clearUser()
|
||||
}
|
||||
if (initialized.value || !token.value) return
|
||||
|
||||
initialized.value = true
|
||||
|
||||
try {
|
||||
await fetchProfile()
|
||||
console.log('Auth restored successfully')
|
||||
} catch (err) {
|
||||
console.error('Auth restoration failed:', err)
|
||||
clearAuth()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -152,6 +113,7 @@ export const useAuthStore = defineStore('auth', () => {
|
||||
token,
|
||||
loading,
|
||||
error,
|
||||
initialized,
|
||||
|
||||
// Getters
|
||||
isAuthenticated,
|
||||
@@ -162,9 +124,8 @@ export const useAuthStore = defineStore('auth', () => {
|
||||
login,
|
||||
logout,
|
||||
fetchProfile,
|
||||
updateProfile,
|
||||
initializeAuth,
|
||||
setToken,
|
||||
clearToken,
|
||||
clearUser
|
||||
clearAuth
|
||||
}
|
||||
})
|
||||
Reference in New Issue
Block a user