first commit

This commit is contained in:
Web-serfer 2026-03-29 17:24:16 +05:00
commit 0065c017e4
496 changed files with 54265 additions and 0 deletions

View file

@ -0,0 +1,395 @@
---
import Button from '@components/base/Button.astro';
// Получаем ошибку из параметров URL
const url = new URL(Astro.request.url);
const initialError = url.searchParams.get('error');
---
<div class="min-h-screen flex items-center justify-center bg-gray-100 p-4">
<div class="flex flex-col md:flex-row w-full max-w-4xl bg-white rounded-2xl shadow-2xl overflow-hidden">
{/* ЛЕВАЯ КОЛОНКА (Изображение) */}
<div class="w-full md:w-1/2 relative min-h-[300px] md:min-h-0">
<img
src="/images/auth/sign-in.avif"
alt="Interior"
class="object-cover w-full h-full"
/>
<div class="absolute inset-0 bg-black/40 flex flex-col justify-end p-8">
<h2 class="text-white font-bold text-3xl">Minivan Berlin</h2>
<p class="text-white text-lg mt-2 font-light">
Ihr zuverlässiger Partner für komfortable Fahrten.
</p>
</div>
</div>
{/* ПРАВАЯ КОЛОНКА (Форма) */}
<div class="w-full md:w-1/2 p-8 md:p-12 flex flex-col justify-center">
<div class="mb-8">
<h2 class="font-bold text-gray-900 text-3xl">Willkommen zurück</h2>
<p class="text-gray-500 mt-2">
Melden Sie sich an, um fortzufahren.
</p>
</div>
{/* Глобальный блок ошибок (от сервера или API) */}
<div id="global-error-container" class={`mb-6 ${initialError ? '' : 'hidden'}`}>
<div class="bg-red-50 border-l-4 border-red-500 text-red-700 p-4 rounded-r" role="alert">
<p class="font-bold">Anmeldung fehlgeschlagen</p>
<p id="global-error-message">{initialError}</p>
</div>
</div>
{/* ФОРМА */}
<form id="login-form" class="space-y-5" novalidate>
{/* EMAIL */}
<div class="group">
<label for="email" class="block text-sm font-medium text-gray-700 mb-1">Email-Adresse</label>
<div class="relative">
<div class="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
<svg class="h-5 w-5 text-gray-400 group-focus-within:text-blue-500 transition-colors" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M16 12a4 4 0 10-8 0 4 4 0 008 0zm0 0v1.5a2.5 2.5 0 005 0V12a9 9 0 10-9 9m4.5-1.206a8.959 8.959 0 01-4.5 1.207"></path></svg>
</div>
<input
id="email"
name="email"
type="email"
autocomplete="email"
required
minlength="5"
maxlength="100"
class="form-input block w-full pl-10 pr-3 py-2.5 border border-gray-300 rounded-lg shadow-sm placeholder-gray-400 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500 sm:text-sm transition-all"
placeholder="beispiel@email.de"
aria-describedby="emailError"
/>
</div>
<div id="emailError" class="text-xs mt-1 text-red-600 hidden h-4"></div>
<div class="text-xs text-gray-500 mt-1">5-100 Zeichen</div>
</div>
{/* PASSWORD */}
<div class="group">
<label for="password" class="block text-sm font-medium text-gray-700 mb-1">Passwort</label>
<div class="relative">
<div class="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
<svg class="h-5 w-5 text-gray-400 group-focus-within:text-blue-500 transition-colors" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 15v2m-6 4h12a2 2 0 002-2v-6a2 2 0 00-2-2H6a2 2 0 00-2 2v6a2 2 0 002 2zm10-10V7a4 4 0 00-8 0v4h8z"></path></svg>
</div>
<input
id="password"
name="password"
type="password"
autocomplete="current-password"
required
minlength="8"
maxlength="128"
class="form-input block w-full pl-10 pr-10 py-2.5 border border-gray-300 rounded-lg shadow-sm placeholder-gray-400 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500 sm:text-sm transition-all"
placeholder="Mindestens 8 Zeichen"
aria-describedby="passwordError"
/>
<button type="button" id="togglePassword" class="absolute inset-y-0 right-0 pr-3 flex items-center text-gray-400 hover:text-gray-600 cursor-pointer focus:outline-none transition-colors" aria-label="Passwort anzeigen">
<svg id="eyeIcon" class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 12a3 3 0 11-6 0 3 3 0 016 0z"></path>
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M2.458 12C3.732 7.943 7.523 5 12 5c4.478 0 8.268 2.943 9.542 7-1.274 4.057-5.064 7-9.542 7-4.477 0-8.268-2.943-9.542-7z"></path>
</svg>
</button>
</div>
<div id="passwordError" class="text-xs mt-1 text-red-600 hidden h-4"></div>
<div class="text-xs text-gray-500 mt-1">Mindestens 8 Zeichen</div>
</div>
<div class="flex items-center justify-end text-sm">
<a href="/auth/forgot-password" class="font-medium text-blue-600 hover:text-blue-500 transition-colors">
Passwort vergessen?
</a>
</div>
<div class="pt-2">
<Button
id="submitButton"
type="submit"
variant="blue"
size="md"
fullWidth={true}
disabled={true}
className="opacity-50 cursor-not-allowed transition-all duration-300"
>
Anmelden
</Button>
</div>
</form>
<div class="mt-8">
<div class="relative">
<div class="absolute inset-0 flex items-center">
<div class="w-full border-t border-gray-200" />
</div>
<div class="relative flex justify-center text-sm">
<span class="px-3 bg-white text-gray-500">Oder weiter mit</span>
</div>
</div>
<div class="mt-6">
<a
href={`/api/auth/google${Astro.url.searchParams.get('callbackUrl') ? `?callbackUrl=${encodeURIComponent(Astro.url.searchParams.get('callbackUrl'))}` : ''}`}
class="w-full flex justify-center items-center px-4 py-3 border border-gray-300 rounded-lg shadow-sm bg-white font-medium text-gray-700 hover:bg-gray-50 transition-colors focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500 cursor-pointer"
>
<svg class="w-5 h-5 mr-2" viewBox="0 0 24 24" width="24" height="24">
<path d="M22.56 12.25c0-.78-.07-1.53-.2-2.25H12v4.26h5.92c-.26 1.37-1.04 2.53-2.21 3.31v2.77h3.57c2.08-1.92 3.28-4.74 3.28-8.09z" fill="#4285F4"/>
<path d="M12 23c2.97 0 5.46-.98 7.28-2.66l-3.57-2.77c-.98.66-2.23 1.06-3.71 1.06-2.86 0-5.29-1.93-6.16-4.53H2.18v2.84C3.99 20.53 7.7 23 12 23z" fill="#34A853"/>
<path d="M5.84 14.09c-.22-.66-.35-1.36-.35-2.09s.13-1.43.35-2.09V7.07H2.18C1.43 8.55 1 10.22 1 12s.43 3.45 1.18 4.93l2.85-2.22.81-.62z" fill="#FBBC05"/>
<path d="M12 5.38c1.62 0 3.06.56 4.21 1.64l3.15-3.15C17.45 2.09 14.97 1 12 1 7.7 1 3.99 3.47 2.18 7.07l3.66 2.84c.87-2.6 3.3-4.53 6.16-4.53z" fill="#EA4335"/>
</svg>
Mit Google anmelden
</a>
</div>
</div>
<div class="mt-8 text-center">
<p class="text-sm text-gray-600">
Noch kein Konto?{' '}
<a href="/auth/register" class="font-medium text-blue-600 hover:text-blue-500 transition-colors">
Registrieren
</a>
</p>
</div>
</div>
</div>
</div>
<script>
document.addEventListener('DOMContentLoaded', () => {
// === ЭЛЕМЕНТЫ DOM ===
const form = document.getElementById('login-form') as HTMLFormElement;
const submitButton = document.getElementById('submitButton') as HTMLButtonElement;
const emailInput = document.getElementById('email') as HTMLInputElement;
const passwordInput = document.getElementById('password') as HTMLInputElement;
const emailError = document.getElementById('emailError') as HTMLDivElement;
const passwordError = document.getElementById('passwordError') as HTMLDivElement;
const globalErrorContainer = document.getElementById('global-error-container');
const globalErrorMessage = document.getElementById('global-error-message');
const togglePassword = document.getElementById('togglePassword');
const eyeIcon = document.getElementById('eyeIcon');
// === ВСПОМОГАТЕЛЬНЫЕ ФУНКЦИИ ===
const showError = (el: HTMLElement, message: string) => {
el.textContent = message;
el.classList.remove('hidden');
};
const hideError = (el: HTMLElement) => {
el.textContent = '';
el.classList.add('hidden');
};
const setValidState = (input: HTMLInputElement, isValid: boolean) => {
if (isValid) {
input.classList.remove('border-red-500', 'focus:ring-red-500', 'focus:border-red-500');
input.classList.add('border-green-500');
} else {
input.classList.remove('border-green-500');
input.classList.add('border-red-500', 'focus:ring-red-500', 'focus:border-red-500');
}
};
const resetState = (input: HTMLInputElement) => {
input.classList.remove('border-red-500', 'border-green-500');
};
// === 1. УПРАВЛЕНИЕ ПАРОЛЕМ (ГЛАЗОК) ===
if (togglePassword && passwordInput && eyeIcon) {
togglePassword.addEventListener('click', () => {
const type = passwordInput.getAttribute('type') === 'password' ? 'text' : 'password';
passwordInput.setAttribute('type', type);
if (type === 'text') {
// Глаз перечеркнут (скрыть)
eyeIcon.innerHTML = '<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M13.875 18.825A10.05 10.05 0 0112 19c-4.478 0-8.268-2.943-9.543-7a9.97 9.97 0 011.563-3.029m5.858.908a3 3 0 114.243 4.243M9.878 9.878l4.242 4.242M9.88 9.88l-3.29-3.29m7.532 7.532l3.29 3.29M3 3l3.59 3.59m0 0A9.953 9.953 0 0112 5c4.478 0 8.268 2.943 9.543 7a10.025 10.025 0 01-4.132 5.411m0 0L21 21" />';
} else {
// Глаз открыт (показать)
eyeIcon.innerHTML = '<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 12a3 3 0 11-6 0 3 3 0 016 0z" /><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M2.458 12C3.732 7.943 7.523 5 12 5c4.478 0 8.268 2.943 9.542 7-1.274 4.057-5.064 7-9.542 7-4.477 0-8.268-2.943-9.542-7z" />';
}
});
}
// === 2. ВАЛИДАЦИЯ EMAIL ===
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
// Запрет пробелов в Email
if (emailInput) {
emailInput.addEventListener('keydown', (e) => {
if (e.key === ' ') e.preventDefault();
});
// Санитизация при вставке
emailInput.addEventListener('input', (e) => {
const target = e.target as HTMLInputElement;
if (target.value.includes(' ')) {
target.value = target.value.replace(/\s/g, '');
}
// Проверка длины
if (target.value.length > 100) {
target.value = target.value.substring(0, 100);
}
validateGlobal();
});
emailInput.addEventListener('blur', () => {
const val = emailInput.value.trim();
if (!val) {
showError(emailError, 'E-Mail ist erforderlich');
setValidState(emailInput, false);
} else if (val.length < 5) {
showError(emailError, 'E-Mail muss mindestens 5 Zeichen enthalten');
setValidState(emailInput, false);
} else if (val.length > 100) {
showError(emailError, 'E-Mail darf maximal 100 Zeichen enthalten');
setValidState(emailInput, false);
} else if (!emailRegex.test(val)) {
showError(emailError, 'Ungültiges E-Mail-Format');
setValidState(emailInput, false);
} else {
hideError(emailError);
setValidState(emailInput, true);
}
validateGlobal();
});
}
// === 3. ВАЛИДАЦИЯ ПАРОЛЯ ===
if (passwordInput) {
// Запрет пробелов в начале и конце пароля
passwordInput.addEventListener('input', (e) => {
const target = e.target as HTMLInputElement;
// Проверка длины
if (target.value.length > 128) {
target.value = target.value.substring(0, 128);
}
validateGlobal();
});
passwordInput.addEventListener('blur', () => {
const val = passwordInput.value;
if (!val) {
showError(passwordError, 'Passwort ist erforderlich');
setValidState(passwordInput, false);
} else if (val.length < 8) {
showError(passwordError, 'Passwort muss mindestens 8 Zeichen enthalten');
setValidState(passwordInput, false);
} else if (val.length > 128) {
showError(passwordError, 'Passwort darf maximal 128 Zeichen enthalten');
setValidState(passwordInput, false);
} else {
hideError(passwordError);
resetState(passwordInput); // Пароль не красим в зеленый для безопасности, просто убираем красный
}
validateGlobal();
});
passwordInput.addEventListener('input', validateGlobal);
}
// === 4. ГЛОБАЛЬНАЯ ВАЛИДАЦИЯ КНОПКИ ===
function validateGlobal() {
if (!emailInput || !passwordInput || !submitButton) return;
const isEmailFilled = emailInput.value.trim().length > 0;
const isEmailLengthValid = emailInput.value.trim().length >= 5 && emailInput.value.trim().length <= 100;
const isEmailFormatValid = emailRegex.test(emailInput.value.trim());
const isPasswordFilled = passwordInput.value.length > 0;
const isPasswordLengthValid = passwordInput.value.length >= 8 && passwordInput.value.length <= 128;
if (isEmailFilled && isEmailLengthValid && isEmailFormatValid && isPasswordFilled && isPasswordLengthValid) {
submitButton.disabled = false;
submitButton.classList.remove('opacity-50', 'cursor-not-allowed');
submitButton.classList.add('hover:shadow-lg', 'cursor-pointer');
} else {
submitButton.disabled = true;
submitButton.classList.add('opacity-50', 'cursor-not-allowed');
submitButton.classList.remove('hover:shadow-lg', 'cursor-pointer');
}
}
// Инициализация
validateGlobal();
// === 5. ОТПРАВКА ФОРМЫ (AJAX) ===
if (form) {
form.addEventListener('submit', async (e) => {
e.preventDefault();
// Извлекаем callbackUrl из URL параметров
const urlParams = new URLSearchParams(window.location.search);
const callbackUrl = urlParams.get('callbackUrl') || '/bewertungen'; // По умолчанию остаемся на странице отзывов
// UI Loading State
const originalContent = submitButton.innerHTML;
const originalWidth = submitButton.offsetWidth; // Фиксируем ширину, чтобы кнопка не дергалась
submitButton.style.width = `${originalWidth}px`;
submitButton.innerHTML = `
<div class="flex items-center justify-center">
<svg class="animate-spin -ml-1 mr-3 h-5 w-5 text-white" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
<circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle>
<path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
</svg>
Wird geladen...
</div>
`;
submitButton.disabled = true;
// Скрываем старые ошибки
if (globalErrorContainer) globalErrorContainer.classList.add('hidden');
const formData = new FormData(form);
const data = Object.fromEntries(formData);
try {
const response = await fetch('/api/auth/login', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(data)
});
const result = await response.json();
if (result.success) {
// Успех - редирект на callbackUrl с параметром для отображения уведомления
const successUrl = callbackUrl.includes('?')
? `${callbackUrl}&loginSuccess=true`
: `${callbackUrl}?loginSuccess=true`;
window.location.href = successUrl;
} else {
// Ошибка API
if (globalErrorMessage && globalErrorContainer) {
globalErrorMessage.textContent = result.message || 'E-Mail oder Passwort falsch.';
globalErrorContainer.classList.remove('hidden');
}
// Возвращаем кнопку
submitButton.innerHTML = originalContent;
submitButton.style.width = 'auto';
submitButton.disabled = false;
}
} catch (error) {
console.error(error);
if (globalErrorMessage && globalErrorContainer) {
globalErrorMessage.textContent = 'Verbindungsfehler. Bitte versuchen Sie es später erneut.';
globalErrorContainer.classList.remove('hidden');
}
submitButton.innerHTML = originalContent;
submitButton.style.width = 'auto';
submitButton.disabled = false;
}
});
}
});
</script>

View file

@ -0,0 +1,535 @@
---
import Button from '@components/base/Button.astro';
import PocketBase, { ClientResponseError } from 'pocketbase';
// Локальные переменные состояния
let isSuccess = false;
let formError = '';
let emailForDisplay = ''; // Переменная для отображения email после успешной регистрации
// === ЛОГИКА СЕРВЕРА ===
if (Astro.request.method === "POST") {
try {
const formData = await Astro.request.formData();
const name = formData.get("name") as string;
const email = formData.get("email") as string;
const password = formData.get("password") as string;
const confirmPassword = formData.get("confirmPassword") as string;
// 1. Проверка паролей на сервере
if (password !== confirmPassword) {
throw new Error("Passwörter stimmen nicht überein.");
}
// 2. Подключение к PocketBase
// Используем переменную окружения или дефолтный адрес
const pb = new PocketBase(import.meta.env.POCKETBASE_URL || 'http://127.0.0.1:8090');
// 3. Создание пользователя
await pb.collection('users').create({
username: undefined, // Генерируется автоматически, если не задан
email: email,
emailVisibility: true,
password: password,
passwordConfirm: confirmPassword,
name: name,
});
// 4. Отправка письма подтверждения
await pb.collection('users').requestVerification(email);
// 5. Успех
isSuccess = true;
emailForDisplay = email; // Сохраняем email для отображения на странице успеха
} catch (e: unknown) {
console.error("Registration error:", e);
if (e instanceof ClientResponseError) {
const data = e.data.data;
if (data) {
// Преобразуем ошибки API PocketBase в читаемый вид
const errors = Object.entries(data).map(([key, val]) => {
const errorObj = val as { code: string; message: string };
if (key === 'email' && errorObj.code === 'validation_not_unique') {
return "Diese E-Mail-Adresse ist bereits vergeben. Bitte melden Sie sich an.";
}
if (key === 'password' && errorObj.code === 'validation_length_short') {
return "Das Passwort ist zu kurz (mindestens 8 Zeichen).";
}
return `${key}: ${errorObj.message}`;
}).join(' ');
formError = errors;
} else {
formError = e.message;
}
} else if (e instanceof Error) {
formError = e.message;
} else {
formError = "Ein unbekannter Fehler ist aufgetreten.";
}
}
}
---
<div class="min-h-screen flex items-center justify-center bg-gray-100 p-4">
<div class="flex flex-col md:flex-row w-full max-w-4xl bg-white rounded-2xl shadow-2xl overflow-hidden">
{/* ЛЕВАЯ КОЛОНКА (Изображение) */}
<div class="w-full md:w-1/2 relative min-h-[300px] md:min-h-0">
<img
src="/images/auth/sign-in.avif"
alt="Интерьер комфортабельного минивэна"
class="object-cover w-full h-full"
/>
<div class="absolute inset-0 bg-black/40 flex flex-col justify-end p-8">
<h2 class="text-white font-bold text-3xl">Minivan Berlin</h2>
<p class="text-white text-lg mt-2 font-light">
Ihr zuverlässiger Partner für komfortable Fahrten.
</p>
</div>
</div>
{/* ПРАВАЯ КОЛОНКА (Форма) */}
<div class="w-full md:w-1/2 p-8 md:p-12 flex flex-col justify-center">
{isSuccess ? (
// === БЛОК УСПЕХА ===
<div class="text-center animate-fade-in">
<div class="mx-auto flex items-center justify-center h-20 w-20 rounded-full bg-green-100 mb-6">
<svg class="h-10 w-10 text-green-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 13l4 4L19 7"></path>
</svg>
</div>
<h2 class="text-2xl font-bold text-gray-900 mb-4">Bitte überprüfen Sie Ihre E-Mails</h2>
<p class="text-gray-600 mb-8 text-lg leading-relaxed">
Wir haben einen Bestätigungslink an <strong>{emailForDisplay}</strong> gesendet.<br/>
Bitte klicken Sie auf den Link, um Ihr Konto zu aktivieren.
</p>
<div class="p-4 bg-blue-50 text-blue-800 rounded-lg text-sm mb-6">
Keine E-Mail erhalten? Bitte überprüfen Sie Ihren Spam-Ordner.
</div>
<div>
<a href="/" class="text-gray-500 hover:text-gray-800 font-medium text-sm transition-colors">Zurück zur Startseite</a>
</div>
</div>
) : (
// === БЛОК ФОРМЫ ===
<>
<div class="mb-8">
<h2 class="font-bold text-gray-900 text-3xl">Erstellen Sie Ihr Konto</h2>
<p class="text-gray-500 mt-2">
Füllen Sie das Formular aus, um zu beginnen.
</p>
</div>
{formError && (
<div class="bg-red-50 border-l-4 border-red-500 text-red-700 p-4 mb-6 rounded-r" role="alert">
<p class="font-bold">Fehler bei der Registrierung</p>
<p>{formError}</p>
</div>
)}
<form method="POST" class="space-y-5" id="registerForm" novalidate>
{/* NAME */}
<div class="group">
<label for="name" class="block text-sm font-medium text-gray-700 mb-1">Name</label>
<div class="relative">
<div class="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
<svg class="h-5 w-5 text-gray-400 group-focus-within:text-blue-500 transition-colors" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M16 7a4 4 0 11-8 0 4 4 0 018 0zM12 14a7 7 0 00-7 7h14a7 7 0 00-7-7z"></path></svg>
</div>
<input
id="name"
name="name"
type="text"
autocomplete="name"
required
minlength="2"
maxlength="50"
class="form-input block w-full pl-10 pr-3 py-2.5 border border-gray-300 rounded-lg shadow-sm placeholder-gray-400 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500 sm:text-sm transition-all"
placeholder="Ihr Name"
aria-describedby="nameError"
/>
</div>
<div id="nameError" class="text-xs mt-1 text-red-600 hidden h-4"></div>
</div>
{/* EMAIL */}
<div class="group">
<label for="email" class="block text-sm font-medium text-gray-700 mb-1">E-Mail-Adresse</label>
<div class="relative">
<div class="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
<svg class="h-5 w-5 text-gray-400 group-focus-within:text-blue-500 transition-colors" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M16 12a4 4 0 10-8 0 4 4 0 008 0zm0 0v1.5a2.5 2.5 0 005 0V12a9 9 0 10-9 9m4.5-1.206a8.959 8.959 0 01-4.5 1.207"></path></svg>
</div>
<input
id="email"
name="email"
type="email"
autocomplete="email"
required
class="form-input block w-full pl-10 pr-3 py-2.5 border border-gray-300 rounded-lg shadow-sm placeholder-gray-400 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500 sm:text-sm transition-all"
placeholder="beispiel@email.de"
aria-describedby="emailError"
/>
</div>
<div id="emailError" class="text-xs mt-1 text-red-600 hidden h-4"></div>
</div>
{/* PASSWORD */}
<div class="group">
<label for="password" class="block text-sm font-medium text-gray-700 mb-1">Passwort</label>
<div class="relative">
<div class="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
<svg class="h-5 w-5 text-gray-400 group-focus-within:text-blue-500 transition-colors" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 15v2m-6 4h12a2 2 0 002-2v-6a2 2 0 00-2-2H6a2 2 0 00-2 2v6a2 2 0 002 2zm10-10V7a4 4 0 00-8 0v4h8z"></path></svg>
</div>
<input
id="password"
name="password"
type="password"
autocomplete="new-password"
required
minlength="8"
class="form-input block w-full pl-10 pr-10 py-2.5 border border-gray-300 rounded-lg shadow-sm placeholder-gray-400 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500 sm:text-sm transition-all"
placeholder="Mindestens 8 Zeichen"
aria-describedby="passwordError"
/>
<button type="button" id="togglePassword" class="absolute inset-y-0 right-0 pr-3 flex items-center text-gray-400 hover:text-gray-600 focus:outline-none cursor-pointer transition-colors" aria-label="Passwort anzeigen">
<svg id="eyeIcon" class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 12a3 3 0 11-6 0 3 3 0 016 0z"></path><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M2.458 12C3.732 7.943 7.523 5 12 5c4.478 0 8.268 2.943 9.542 7-1.274 4.057-5.064 7-9.542 7-4.477 0-8.268-2.943-9.542-7z"></path></svg>
</button>
</div>
{/* Индикатор силы пароля */}
<div class="mt-2 h-1 w-full bg-gray-200 rounded-full overflow-hidden">
<div id="passwordStrengthBar" class="h-full w-0 bg-red-500 transition-all duration-300 ease-out"></div>
</div>
<div class="flex justify-between items-start mt-1">
<div id="passwordError" class="text-xs text-red-600 hidden"></div>
<div id="passwordStrengthText" class="text-xs text-gray-400 ml-auto whitespace-nowrap"></div>
</div>
</div>
{/* CONFIRM PASSWORD */}
<div class="group">
<label for="confirmPassword" class="block text-sm font-medium text-gray-700 mb-1">Passwort bestätigen</label>
<div class="relative">
<div class="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
<svg class="h-5 w-5 text-gray-400 group-focus-within:text-blue-500 transition-colors" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z"></path></svg>
</div>
<input
id="confirmPassword"
name="confirmPassword"
type="password"
autocomplete="new-password"
required
class="form-input block w-full pl-10 pr-10 py-2.5 border border-gray-300 rounded-lg shadow-sm placeholder-gray-400 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500 sm:text-sm transition-all"
placeholder="Passwort wiederholen"
/>
<button type="button" id="toggleConfirmPassword" class="absolute inset-y-0 right-0 pr-3 flex items-center text-gray-400 hover:text-gray-600 focus:outline-none cursor-pointer transition-colors" aria-label="Passwort anzeigen">
<svg id="confirmEyeIcon" class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 12a3 3 0 11-6 0 3 3 0 016 0z"></path><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M2.458 12C3.732 7.943 7.523 5 12 5c4.478 0 8.268 2.943 9.542 7-1.274 4.057-5.064 7-9.542 7-4.477 0-8.268-2.943-9.542-7z"></path></svg>
</button>
</div>
<div id="passwordMatchMessage" class="text-xs mt-1 h-4 hidden"></div>
</div>
<div class="pt-2">
<Button
id="submitButton"
type="submit"
variant="blue"
size="md"
fullWidth={true}
disabled={true}
className="opacity-50 cursor-not-allowed transition-all duration-300"
>
Konto erstellen
</Button>
</div>
</form>
<div class="mt-8">
<div class="relative">
<div class="absolute inset-0 flex items-center">
<div class="w-full border-t border-gray-200" />
</div>
<div class="relative flex justify-center text-sm">
<span class="px-3 bg-white text-gray-500">Oder weiter mit</span>
</div>
</div>
<div class="mt-6">
<a href="/api/auth/google" class="w-full flex justify-center items-center px-4 py-3 border border-gray-300 rounded-lg shadow-sm bg-white font-medium text-gray-700 hover:bg-gray-50 hover:cursor-pointer transition-colors focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500">
<svg class="w-5 h-5 mr-2" viewBox="0 0 24 24" width="24" height="24"><path d="M22.56 12.25c0-.78-.07-1.53-.2-2.25H12v4.26h5.92c-.26 1.37-1.04 2.53-2.21 3.31v2.77h3.57c2.08-1.92 3.28-4.74 3.28-8.09z" fill="#4285F4"/><path d="M12 23c2.97 0 5.46-.98 7.28-2.66l-3.57-2.77c-.98.66-2.23 1.06-3.71 1.06-2.86 0-5.29-1.93-6.16-4.53H2.18v2.84C3.99 20.53 7.7 23 12 23z" fill="#34A853"/><path d="M5.84 14.09c-.22-.66-.35-1.36-.35-2.09s.13-1.43.35-2.09V7.07H2.18C1.43 8.55 1 10.22 1 12s.43 3.45 1.18 4.93l2.85-2.22.81-.62z" fill="#FBBC05"/><path d="M12 5.38c1.62 0 3.06.56 4.21 1.64l3.15-3.15C17.45 2.09 14.97 1 12 1 7.7 1 3.99 3.47 2.18 7.07l3.66 2.84c.87-2.6 3.3-4.53 6.16-4.53z" fill="#EA4335"/></svg>
Mit Google anmelden
</a>
</div>
</div>
<div class="mt-8 text-center">
<p class="text-sm text-gray-600">
Haben Sie bereits ein Konto?{' '}
<a href="/auth/login" class="font-medium text-blue-600 hover:text-blue-500 transition-colors">
Anmelden
</a>
</p>
</div>
</>
)}
</div>
</div>
</div>
<script>
document.addEventListener('DOMContentLoaded', () => {
// === ПОЛУЧЕНИЕ ЭЛЕМЕНТОВ DOM ===
const form = document.querySelector('#registerForm') as HTMLFormElement | null;
if (!form) return;
const submitButton = document.getElementById('submitButton') as HTMLButtonElement;
const nameInput = document.getElementById('name') as HTMLInputElement;
const emailInput = document.getElementById('email') as HTMLInputElement;
const passwordInput = document.getElementById('password') as HTMLInputElement;
const confirmInput = document.getElementById('confirmPassword') as HTMLInputElement;
const nameError = document.getElementById('nameError') as HTMLDivElement;
const emailError = document.getElementById('emailError') as HTMLDivElement;
const passwordError = document.getElementById('passwordError') as HTMLDivElement;
const passwordMatchMessage = document.getElementById('passwordMatchMessage') as HTMLDivElement;
const passwordStrengthBar = document.getElementById('passwordStrengthBar') as HTMLDivElement;
const passwordStrengthText = document.getElementById('passwordStrengthText') as HTMLDivElement;
// Переключатели видимости пароля
const togglePassBtn = document.getElementById('togglePassword');
const toggleConfirmBtn = document.getElementById('toggleConfirmPassword');
const eyeIcon = document.getElementById('eyeIcon');
const confirmEyeIcon = document.getElementById('confirmEyeIcon');
// === ВСПОМОГАТЕЛЬНЫЕ ФУНКЦИИ ===
/** Показать ошибку */
const showError = (el: HTMLElement, message: string) => {
el.textContent = message;
el.classList.remove('hidden');
};
/** Скрыть ошибку */
const hideError = (el: HTMLElement) => {
el.textContent = '';
el.classList.add('hidden');
};
/** Переключение иконки глаза */
const updateEyeIcon = (icon: HTMLElement | null, isVisible: boolean) => {
if (!icon) return;
if (isVisible) {
// Иконка "скрыть" (глаз перечеркнут)
icon.innerHTML = `<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M13.875 18.825A10.05 10.05 0 0112 19c-4.478 0-8.268-2.943-9.543-7a9.97 9.97 0 011.563-3.029m5.858.908a3 3 0 114.243 4.243M9.878 9.878l4.242 4.242M9.88 9.88l-3.29-3.29m7.532 7.532l3.29 3.29M3 3l3.59 3.59m0 0A9.953 9.953 0 0112 5c4.478 0 8.268 2.943 9.543 7a10.025 10.025 0 01-4.132 5.411m0 0L21 21" />`;
} else {
// Иконка "показать" (глаз обычный)
icon.innerHTML = `<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 12a3 3 0 11-6 0 3 3 0 016 0z"></path><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M2.458 12C3.732 7.943 7.523 5 12 5c4.478 0 8.268 2.943 9.542 7-1.274 4.057-5.064 7-9.542 7-4.477 0-8.268-2.943-9.542-7z"></path></svg>`;
}
};
// === 1. ВАЛИДАЦИЯ ИМЕНИ (СТРОГАЯ) ===
// Разрешаем: Латиница, Кириллица, пробел, дефис, апостроф.
const nameRegex = /^[a-zA-Zа-яА-ЯёЁ\s\-']+$/u;
// Блокировка ввода клавиш
nameInput.addEventListener('keydown', (e) => {
const allowedKeys = ['Backspace', 'Delete', 'Tab', 'Escape', 'Enter', 'ArrowLeft', 'ArrowRight', 'Home', 'End'];
if (allowedKeys.includes(e.key) || e.ctrlKey || e.metaKey || e.altKey) return;
// Если символ не соответствует регулярке - предотвращаем ввод
if (!nameRegex.test(e.key)) {
e.preventDefault();
}
});
// Санитизация ввода (против вставки и автозаполнения)
nameInput.addEventListener('input', (e) => {
const target = e.target as HTMLInputElement;
// Удаляем всё, что не соответствует разрешенным символам
// Note: инвертируем диапазон для replace
const sanitized = target.value.replace(/[^a-zA-Zа-яА-ЯёЁ\s\-']/gu, '');
if (sanitized !== target.value) {
target.value = sanitized;
}
validateGlobal();
});
nameInput.addEventListener('blur', () => {
if (!nameInput.value.trim()) {
showError(nameError, 'Name ist erforderlich');
nameInput.classList.add('border-red-500', 'focus:ring-red-500', 'focus:border-red-500');
} else if (nameInput.value.trim().length < 2) {
showError(nameError, 'Name muss mindestens 2 Zeichen lang sein');
nameInput.classList.add('border-red-500');
} else {
hideError(nameError);
nameInput.classList.remove('border-red-500', 'focus:ring-red-500', 'focus:border-red-500');
nameInput.classList.add('border-green-500');
}
validateGlobal();
});
// === 2. ВАЛИДАЦИЯ EMAIL ===
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
const validateEmail = () => {
const val = emailInput.value.trim();
if (!val) return false;
return emailRegex.test(val);
};
emailInput.addEventListener('blur', () => {
if (!emailInput.value.trim()) {
showError(emailError, 'E-Mail ist erforderlich');
emailInput.classList.add('border-red-500');
} else if (!validateEmail()) {
showError(emailError, 'Bitte geben Sie eine gültige E-Mail-Adresse ein');
emailInput.classList.add('border-red-500');
} else {
hideError(emailError);
emailInput.classList.remove('border-red-500');
emailInput.classList.add('border-green-500');
}
validateGlobal();
});
emailInput.addEventListener('input', validateGlobal);
// === 3. ВАЛИДАЦИЯ И СИЛА ПАРОЛЯ ===
const checkPasswordStrength = (pass: string) => {
let score = 0;
if (!pass) return 0;
if (pass.length >= 8) score += 1;
if (pass.length >= 12) score += 1;
if (/[A-Z]/.test(pass)) score += 1;
if (/[0-9]/.test(pass)) score += 1;
if (/[^A-Za-z0-9]/.test(pass)) score += 1;
return score; // Max 5
};
const updateStrengthMeter = (pass: string) => {
const score = checkPasswordStrength(pass);
const width = (score / 5) * 100;
passwordStrengthBar.style.width = `${width}%`;
// Цвета и текст
if (score <= 1) {
passwordStrengthBar.className = 'h-full bg-red-500 transition-all duration-300';
passwordStrengthText.textContent = 'Sehr schwach';
passwordStrengthText.className = 'text-xs text-red-500 ml-auto whitespace-nowrap font-medium';
} else if (score === 2) {
passwordStrengthBar.className = 'h-full bg-orange-500 transition-all duration-300';
passwordStrengthText.textContent = 'Schwach';
passwordStrengthText.className = 'text-xs text-orange-500 ml-auto whitespace-nowrap font-medium';
} else if (score === 3) {
passwordStrengthBar.className = 'h-full bg-yellow-500 transition-all duration-300';
passwordStrengthText.textContent = 'Mittel';
passwordStrengthText.className = 'text-xs text-yellow-600 ml-auto whitespace-nowrap font-medium';
} else if (score >= 4) {
passwordStrengthBar.className = 'h-full bg-green-500 transition-all duration-300';
passwordStrengthText.textContent = 'Stark';
passwordStrengthText.className = 'text-xs text-green-600 ml-auto whitespace-nowrap font-medium';
}
return score;
};
passwordInput.addEventListener('input', () => {
const val = passwordInput.value;
const score = updateStrengthMeter(val);
if (val.length > 0 && val.length < 8) {
showError(passwordError, 'Mindestens 8 Zeichen erforderlich');
} else {
hideError(passwordError);
}
validateGlobal();
});
// === 4. ПРОВЕРКА СОВПАДЕНИЯ ===
const checkMatch = () => {
const pass = passwordInput.value;
const conf = confirmInput.value;
if (!conf) {
hideError(passwordMatchMessage);
confirmInput.classList.remove('border-red-500', 'border-green-500');
return false;
}
if (pass !== conf) {
passwordMatchMessage.textContent = 'Passwörter stimmen nicht überein';
passwordMatchMessage.className = 'text-xs mt-1 text-red-600 block';
confirmInput.classList.add('border-red-500');
confirmInput.classList.remove('border-green-500');
return false;
} else {
passwordMatchMessage.textContent = 'Passwörter stimmen überein';
passwordMatchMessage.className = 'text-xs mt-1 text-green-600 block';
confirmInput.classList.remove('border-red-500');
confirmInput.classList.add('border-green-500');
return true;
}
};
confirmInput.addEventListener('input', () => {
checkMatch();
validateGlobal();
});
// Повторная проверка совпадения, если меняется основной пароль
passwordInput.addEventListener('input', () => {
if (confirmInput.value) checkMatch();
});
// === ГЛОБАЛЬНАЯ ВАЛИДАЦИЯ КНОПКИ ===
function validateGlobal() {
const isNameValid = nameInput.value.trim().length >= 2;
const isEmailValid = validateEmail();
const isPassValid = passwordInput.value.length >= 8 && checkPasswordStrength(passwordInput.value) >= 2; // Требуем хотя бы слабой сложности
const isMatch = passwordInput.value === confirmInput.value && confirmInput.value.length > 0;
if (isNameValid && isEmailValid && isPassValid && isMatch) {
submitButton.disabled = false;
submitButton.classList.remove('opacity-50', 'cursor-not-allowed');
submitButton.classList.add('hover:shadow-lg', 'cursor-pointer');
} else {
submitButton.disabled = true;
submitButton.classList.add('opacity-50', 'cursor-not-allowed');
submitButton.classList.remove('hover:shadow-lg', 'cursor-pointer');
}
}
// === ЛОГИКА ГЛАЗКОВ ===
if (togglePassBtn) {
togglePassBtn.addEventListener('click', () => {
const type = passwordInput.type === 'password' ? 'text' : 'password';
passwordInput.type = type;
updateEyeIcon(eyeIcon as HTMLElement, type === 'text');
});
}
if (toggleConfirmBtn) {
toggleConfirmBtn.addEventListener('click', () => {
const type = confirmInput.type === 'password' ? 'text' : 'password';
confirmInput.type = type;
updateEyeIcon(confirmEyeIcon as HTMLElement, type === 'text');
});
}
});
</script>