feat(auth): implement registration page and logic

This commit is contained in:
2025-06-17 08:46:35 +03:00
parent df460f57ab
commit c4a1c2cde0
6 changed files with 200 additions and 5 deletions

7
src/api/auth.ts Normal file
View File

@@ -0,0 +1,7 @@
import type { RegisterRequest } from "@/types"; // Мы создадим этот тип
import apiClient from "./axios";
export const registerUser = (userData: RegisterRequest) => {
// apiClient уже настроен на /api, поэтому путь относительный
return apiClient.post("/register", userData);
};

39
src/stores/auth.ts Normal file
View File

@@ -0,0 +1,39 @@
import { defineStore } from "pinia";
import { ref } from "vue";
import { registerUser as apiRegisterUser } from "@/api/auth";
import type { RegisterRequest } from "@/types";
import router from "@/router";
export const useAuthStore = defineStore("auth", () => {
// State
const isLoading = ref(false);
const error = ref<string | null>(null);
// Actions
async function handleRegister(userData: RegisterRequest) {
isLoading.value = true;
error.value = null;
try {
await apiRegisterUser(userData);
// После успешной регистрации перенаправляем на страницу входа
await router.push({ name: "login" });
// Можно добавить сообщение об успехе ("тост")
// alert('Регистрация прошла успешно! Теперь вы можете войти.');
} catch (e: any) {
// Обрабатываем ошибки от Axios
if (e.response && e.response.data) {
error.value = e.response.data;
} else {
error.value = "Произошла неизвестная ошибка";
}
} finally {
isLoading.value = false;
}
}
return {
isLoading,
error,
handleRegister,
};
});

6
src/types.ts Normal file
View File

@@ -0,0 +1,6 @@
// Тип для запроса на регистрацию, должен совпадать с бэкендом
export interface RegisterRequest {
username: string;
email: string;
password: string;
}

View File

@@ -1,3 +1,136 @@
<template>
<div class="register-container">
<form @submit.prevent="onSubmit" class="register-form">
<h1>Регистрация</h1>
<div class="form-group">
<label for="username">Имя пользователя</label>
<input id="username" v-model="username" type="text" required minlength="3" maxlength="16" pattern="^[a-zA-Z0-9_]+$" />
<small>От 3 до 16 символов. Только буквы, цифры и `_`.</small>
</div>
<div class="form-group">
<label for="email">Email</label>
<input id="email" v-model="email" type="email" required />
</div>
<div class="form-group">
<label for="password">Пароль</label>
<input id="password" v-model="password" type="password" required minlength="8" />
<small>Минимум 8 символов.</small>
</div>
<div v-if="authStore.error" class="error-message">
{{ authStore.error }}
</div>
<button type="submit" :disabled="authStore.isLoading">
{{ authStore.isLoading ? "Регистрация..." : "Зарегистрироваться" }}
</button>
</form>
</div>
</template>
<script setup lang="ts">
import { ref } from "vue";
import { useAuthStore } from "@/stores/auth";
// Используем наш Pinia store
const authStore = useAuthStore();
// Реактивные переменные для полей формы
const username = ref("");
const email = ref("");
const password = ref("");
// Функция, вызываемая при отправке формы
const onSubmit = async () => {
// Простая валидация на клиенте (хотя основная на бэкенде)
if (!username.value || !email.value || !password.value) {
return;
}
await authStore.handleRegister({
username: username.value,
email: email.value,
password: password.value,
});
};
</script>
<style scoped>
.register-container {
display: flex;
justify-content: center;
align-items: center;
padding-top: 50px;
}
.register-form {
width: 100%;
max-width: 400px;
padding: 2rem;
border: 1px solid #ccc;
border-radius: 8px;
box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}
h1 {
text-align: center;
margin-bottom: 1.5rem;
}
.form-group {
margin-bottom: 1rem;
}
label {
display: block;
margin-bottom: 0.5rem;
}
input {
width: 100%;
padding: 0.75rem;
border: 1px solid #ccc;
border-radius: 4px;
box-sizing: border-box; /* Важно для правильного расчета ширины */
}
small {
display: block;
margin-top: 0.25rem;
color: #666;
}
.error-message {
background-color: #f8d7da;
color: #721c24;
padding: 0.75rem;
border: 1px solid #f5c6cb;
border-radius: 4px;
margin-bottom: 1rem;
text-align: center;
}
button {
width: 100%;
padding: 0.75rem;
background-color: #42b983;
color: white;
border: none;
border-radius: 4px;
font-size: 1rem;
cursor: pointer;
transition: background-color 0.2s;
}
button:hover {
background-color: #36a476;
}
button:disabled {
background-color: #ccc;
cursor: not-allowed;
}
</style>

View File

@@ -9,7 +9,13 @@
"noUnusedParameters": true,
"erasableSyntaxOnly": true,
"noFallthroughCasesInSwitch": true,
"noUncheckedSideEffectImports": true
"noUncheckedSideEffectImports": true,
/* Path Aliases */
"baseUrl": ".",
"paths": {
"@/*": ["src/*"]
}
},
"include": ["src/**/*.ts", "src/**/*.tsx", "src/**/*.vue"]
}

View File

@@ -1,15 +1,19 @@
import { defineConfig } from "vite";
import vue from "@vitejs/plugin-vue";
import path from "path";
// https://vitejs.dev/config/
export default defineConfig({
plugins: [vue()],
resolve: {
alias: {
"@": path.resolve(__dirname, "./src"),
},
},
server: {
// <-- ДОБАВЬТЕ ЭТОТ БЛОК
proxy: {
// Проксируем все запросы, начинающиеся с /api, /authserver, /sessionserver
"^/api|/authserver|/sessionserver": {
target: "http://localhost:8080", // Адрес вашего локального бэкенда
target: "http://localhost:8080",
changeOrigin: true,
},
},