yalarba.ru front set new auth.store and auth.service

This commit is contained in:
2025-10-06 04:44:30 +05:00
parent 9065f34365
commit bca9161416
4 changed files with 175 additions and 80 deletions
@@ -1,20 +1,69 @@
// src/auth/services/auth.service.js // src/auth/services/auth.service.js
import axios from 'axios'; const API_URL = 'https://yalarba.ru/api/v1/auth';
const API_URL = 'https://yalarba.ru/api'; class AuthService {
static async register(userData) {
try {
const response = await fetch(`${API_URL}/register`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(userData)
});
const login = async (credentials) => { if (!response.ok) {
const response = await axios.post(`${API_URL}/auth/login`, credentials, { throw new Error('Registration failed');
'Content-Type': 'application/json' }
});
return response.data;
};
const checkAuth = async (token) => { return await response.json();
const response = await axios.get(`${API_URL}/auth/check`, { } catch (error) {
headers: { Authorization: `Bearer ${token}` }, console.error('Registration error:', error);
}); throw error;
return response.data; }
}; }
export default { login, checkAuth }; static async login(credentials) {
try {
const response = await fetch(`${API_URL}/login`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(credentials)
});
if (!response.ok) {
throw new Error('Login failed');
}
return await response.json();
} catch (error) {
console.error('Login error:', error);
throw error;
}
}
static async checkAuth(token) {
try {
const response = await fetch(`${API_URL}/validate`, {
method: 'GET',
headers: {
'Authorization': `Bearer ${token}`,
'Content-Type': 'application/json',
}
});
if (!response.ok) {
throw new Error('Token validation failed');
}
return await response.json();
} catch (error) {
console.error('Check auth error:', error);
throw error;
}
}
}
export default AuthService;
@@ -1,20 +0,0 @@
// src/auth/services/auth.service.js
import axios from 'axios';
const API_URL = 'https://yalarba.ru/api';
const login = async (credentials) => {
const response = await axios.post(`${API_URL}/auth/login`, credentials, {
'Content-Type': 'application/json'
});
return response.data;
};
const checkAuth = async (token) => {
const response = await axios.get(`${API_URL}/auth/check`, {
headers: { Authorization: `Bearer ${token}` },
});
return response.data;
};
export default { login, checkAuth };
@@ -8,16 +8,77 @@ export const useAuthStore = defineStore('auth', () => {
const user = reactive({username: '', email: '', id: 0, token: ''}); const user = reactive({username: '', email: '', id: 0, token: ''});
const isAuthenticated = ref(false); const isAuthenticated = ref(false);
// Восстановление из localStorage при инициализации
const initFromStorage = () => {
const storedToken = localStorage.getItem('token');
const storedUser = localStorage.getItem('user');
if (storedToken && storedUser) {
try {
user.token = storedToken;
const userData = JSON.parse(storedUser);
user.username = userData.username;
user.email = userData.email;
user.id = userData.id;
isAuthenticated.value = true;
} catch (error) {
console.error('Error restoring from storage:', error);
logout();
}
}
};
// Вызываем при создании store
initFromStorage();
// ДОБАВЬТЕ ЭТОТ МЕТОД - регистрация
const register = async (userData) => {
try {
const response = await AuthService.register(userData);
// Если сервер возвращает токен при регистрации
if (response.token) {
const decodedToken = jwtDecode(response.token);
user.username = decodedToken.user?.username || userData.name;
user.id = decodedToken.user?.id || 0;
user.email = decodedToken.user?.email || userData.email;
isAuthenticated.value = true;
user.token = response.token;
// Сохраняем в localStorage
localStorage.setItem('token', response.token);
localStorage.setItem('user', JSON.stringify({
username: user.username,
email: user.email,
id: user.id
}));
}
return response;
} catch (error) {
console.error('Registration failed', error);
throw error;
}
};
const login = async (credentials) => { const login = async (credentials) => {
try { try {
const response = await AuthService.login(credentials); const response = await AuthService.login(credentials);
const decodedToken = jwtDecode(response.token); const decodedToken = jwtDecode(response.token);
user.name = decodedToken.user.username; user.username = decodedToken.user?.username || '';
user.id = decodedToken.user.id; user.id = decodedToken.user?.id || 0;
user.email = decodedToken.user.email; user.email = decodedToken.user?.email || credentials.email;
isAuthenticated.value = true; isAuthenticated.value = true;
user.token = response.token; user.token = response.token;
// Сохраняем в localStorage
localStorage.setItem('token', response.token);
localStorage.setItem('user', JSON.stringify({
username: user.username,
email: user.email,
id: user.id
}));
} catch (error) { } catch (error) {
console.error('Login failed', error); console.error('Login failed', error);
throw error; throw error;
@@ -26,30 +87,38 @@ export const useAuthStore = defineStore('auth', () => {
const logout = () => { const logout = () => {
isAuthenticated.value = false; isAuthenticated.value = false;
user.name = ''; user.username = '';
user.token = ''; user.token = '';
user.email = ''; user.email = '';
user.id = 0; user.id = 0;
// Удаляем из localStorage
localStorage.removeItem('token');
localStorage.removeItem('user');
}; };
const checkAuth = async () => { const checkAuth = async () => {
try { try {
const token = user.token; const token = user.token || localStorage.getItem('token');
if (token) { if (token) {
try { try {
const response = await AuthService.checkAuth(token); const response = await AuthService.checkAuth(token);
user.value = response.user; // Обновляем данные пользователя
user.username = response.user?.username || user.username;
user.id = response.user?.id || user.id;
user.email = response.user?.email || user.email;
isAuthenticated.value = true; isAuthenticated.value = true;
} catch (error) { } catch (error) {
console.error('Token validation failed:', error);
logout(); logout();
} }
} }
} catch (error) { } catch (error) {
console.error('Check auth failed', error); console.error('Check auth failed', error);
throw error; throw error;
} }
}; };
return { user, isAuthenticated, login, logout, checkAuth }; // ВАЖНО: добавьте register в return
return { user, isAuthenticated, register, login, logout, checkAuth };
}); });
@@ -8,7 +8,7 @@
<label for="username"> <label for="username">
{{ t('messages.inout.name') }}: {{ t('messages.inout.name') }}:
</label> </label>
<input v-model.trim="username" type="text" id="username" required /> <input v-model.trim="name" type="text" id="username" required />
</div> </div>
<div class="form-group"> <div class="form-group">
@@ -34,40 +34,55 @@
<script> <script>
import { useI18n } from 'vue-i18n'; import { useI18n } from 'vue-i18n';
import { errorMessages } from 'vue/compiler-sfc'; import { useAuthStore } from '@/auth/stores/auth.store';
import { useRouter } from 'vue-router';
export default { export default {
name: 'RegisterForm',
setup() { setup() {
const { t } = useI18n(); const { t } = useI18n();
return { t }; const authStore = useAuthStore();
const router = useRouter();
return { t, authStore, router };
}, },
data() { data() {
return { return {
username: '', name: '',
email: '', email: '',
password: '' password: '',
isLoading: false
}; };
}, },
methods: { methods: {
handleSubmit() { async handleSubmit() {
if (!this.isValid(this.username, this.email, this.password)) { if (!this.isValid(this.name, this.email, this.password)) {
alert("Пожалуйста, заполните все поля корректно."); alert("Пожалуйста, заполните все поля корректно.");
return; return;
} }
this.sendRegistrationData({ this.isLoading = true;
username: this.username,
email: this.email, try {
password: this.password // ИСПОЛЬЗУЕМ authStore.register вместо прямой отправки
}).then(() => { await this.authStore.register({
this.$router.push('/login'); // Переход на страницу логина name: this.name,
}).catch((error) => { email: this.email,
console.error(error); password: this.password
alert('Что-то пошло не так. Попробуйте еще раз.' + error); });
});
// После успешной регистрации переходим в профиль
this.router.push('/profile');
} catch (error) {
console.error('Registration error:', error);
alert(error.message || 'Что-то пошло не так. Попробуйте еще раз.');
} finally {
this.isLoading = false;
}
}, },
isValid(username, email, password) {
if (username.length === 0 || email.length === 0 || password.length === 0) { isValid(name, email, password) {
if (name.length === 0 || email.length === 0 || password.length === 0) {
return false; return false;
} }
@@ -81,24 +96,6 @@ export default {
} }
return true; return true;
},
async sendRegistrationData(data) {
console.log("Register by this data: ", data);
try {
const response = await fetch('https://yalarba.ru/api/auth/register', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(data)
});
if (!response.ok) {
throw new Error('Ошибка при регистрации');
}
} catch (error) {
throw error;
}
} }
} }
}; };