This commit is contained in:
2026-03-19 19:29:30 +03:00
parent ecb3bd7714
commit 69afca68cf
4 changed files with 1116 additions and 353 deletions

View File

@@ -296,8 +296,8 @@ def get_db():
class UserRegister(BaseModel):
full_name: str
email: EmailStr
phone: str
telegram: Optional[str] = None
phone: str # больше не Optional
telegram: str # больше не Optional
password: str
role: str
@@ -882,7 +882,7 @@ async def get_public_stats():
async def register(user: UserRegister):
"""Регистрация нового пользователя"""
try:
print(f"📝 Registering user: {user.email}")
print(f"📝 Регистрация: {user.email}")
with get_db() as conn:
cursor = conn.cursor()
@@ -904,17 +904,11 @@ async def register(user: UserRegister):
user_id = cursor.lastrowid
conn.commit()
print(f"User created with ID: {user_id}")
print(f"Пользователь создан: ID {user_id}")
# Создаем данные для токена
token_data = {
"sub": str(user_id), # Явно преобразуем в строку
"role": user.role,
"is_admin": bool(is_admin)
}
token = create_access_token(token_data)
token = create_access_token({"sub": str(user_id), "role": user.role})
response_data = {
return {
"access_token": token,
"token_type": "bearer",
"user_id": user_id,
@@ -923,13 +917,10 @@ async def register(user: UserRegister):
"is_admin": bool(is_admin)
}
return response_data
except HTTPException:
raise
except Exception as e:
print(f"Registration error: {e}")
traceback.print_exc()
print(f"Ошибка регистрации: {e}")
raise HTTPException(status_code=500, detail=f"Внутренняя ошибка: {str(e)}")

File diff suppressed because it is too large Load Diff

View File

@@ -6,12 +6,11 @@
<title>Регистрация | Rabota.Today</title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta3/css/all.min.css">
<style>
/* Мобильные стили */
* {
margin: 0;
padding: 0;
box-sizing: border-box;
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Helvetica, Arial, sans-serif;
font-family: 'Inter', -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Helvetica, Arial, sans-serif;
}
body {
@@ -123,6 +122,12 @@
font-size: 14px;
}
.required-star {
color: #ef4444;
margin-left: 4px;
font-size: 14px;
}
.input-group input {
width: 100%;
padding: 14px 16px;
@@ -142,6 +147,11 @@
box-shadow: 0 0 0 3px rgba(59,130,246,0.1);
}
.input-group input.error {
border-color: #ef4444;
background: #fef2f2;
}
.input-row {
display: flex;
gap: 10px;
@@ -219,7 +229,61 @@
font-size: 13px;
}
/* Адаптация для очень маленьких экранов */
.password-requirements {
background: #f0f7ff;
border-radius: 20px;
padding: 12px 16px;
margin: 15px 0;
font-size: 12px;
}
.password-requirements p {
color: #1f3f60;
font-weight: 600;
margin-bottom: 8px;
display: flex;
align-items: center;
gap: 5px;
}
.requirement {
color: #4f7092;
margin: 4px 0;
display: flex;
align-items: center;
gap: 5px;
}
.requirement.valid {
color: #10b981;
}
.requirement.valid i {
color: #10b981;
}
.requirement.invalid {
color: #ef4444;
}
.requirement.invalid i {
color: #ef4444;
}
.footer {
text-align: center;
padding: 20px 30px;
background: #f8fafc;
border-top: 1px solid #dee9f5;
font-size: 13px;
color: #4f7092;
}
.footer a {
color: #3b82f6;
text-decoration: none;
}
@media (max-width: 380px) {
.input-row {
flex-direction: column;
@@ -237,7 +301,7 @@
<div class="register-header">
<h1>
<i class="fas fa-briefcase"></i>
МП.Ярмарка
Rabota.Today
</h1>
<p>Регистрация на ярмарке вакансий</p>
</div>
@@ -264,36 +328,65 @@
<form id="registerForm" onsubmit="handleRegister(event)">
<div class="input-group">
<label><i class="fas fa-user-circle"></i> ФИО *</label>
<input type="text" id="fullName" placeholder="Иванов Иван" required>
<label>
<i class="fas fa-user-circle"></i>
ФИО <span class="required-star">*</span>
</label>
<input type="text" id="fullName" placeholder="Иванов Иван Иванович" required>
</div>
<div class="input-group">
<label><i class="fas fa-envelope"></i> Email *</label>
<label>
<i class="fas fa-envelope"></i>
Email <span class="required-star">*</span>
</label>
<input type="email" id="email" placeholder="ivan@example.com" required>
</div>
<div class="input-row">
<div class="input-group">
<label><i class="fas fa-phone-alt"></i> Телефон *</label>
<label>
<i class="fas fa-phone-alt"></i>
Телефон <span class="required-star">*</span>
</label>
<input type="tel" id="phone" placeholder="+7 (999) 123-45-67" required>
</div>
<div class="input-group">
<label><i class="fab fa-telegram-plane"></i> Telegram</label>
<input type="text" id="telegram" placeholder="@username">
<label>
<i class="fab fa-telegram-plane"></i>
Telegram <span class="required-star">*</span>
</label>
<input type="text" id="telegram" placeholder="@username" required>
</div>
</div>
<div class="input-group">
<label><i class="fas fa-lock"></i> Пароль *</label>
<label>
<i class="fas fa-lock"></i>
Пароль <span class="required-star">*</span>
</label>
<input type="password" id="password" placeholder="Минимум 6 символов" required>
</div>
<div class="input-group">
<label><i class="fas fa-lock"></i> Подтверждение *</label>
<label>
<i class="fas fa-lock"></i>
Подтверждение <span class="required-star">*</span>
</label>
<input type="password" id="confirmPassword" placeholder="Повторите пароль" required>
</div>
<!-- Требования к паролю -->
<div class="password-requirements" id="passwordRequirements">
<p><i class="fas fa-shield-alt"></i> Требования к паролю:</p>
<div class="requirement" id="reqLength">
<i class="far fa-circle"></i> Минимум 6 символов
</div>
<div class="requirement" id="reqMatch">
<i class="far fa-circle"></i> Пароли совпадают
</div>
</div>
<button type="submit" class="btn-register" id="registerBtn">
<span>Зарегистрироваться</span>
<i class="fas fa-arrow-right"></i>
@@ -305,17 +398,17 @@
<a href="/login">Войти</a>
</div>
</div>
<div class="footer">
© 2024 Rabota.Today - Ярмарка вакансий.
<a href="/">На главную</a>
</div>
</div>
<script>
const currentProtocol = window.location.protocol; // http: или https:
const currentHost = window.location.host; // yarmarka.rabota.today или IP:порт
let API_BASE_URL = `${currentProtocol}//${currentHost}/api`;
const API_BASE_URL = window.location.protocol + '//' + window.location.host + '/api';
let isSubmitting = false;
// Определение мобильного устройства
const isMobile = /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent);
// Переключение роли
document.getElementById('roleEmployeeBtn').addEventListener('click', () => {
document.getElementById('roleEmployeeBtn').classList.add('active');
@@ -327,6 +420,69 @@
document.getElementById('roleEmployeeBtn').classList.remove('active');
});
// Валидация пароля в реальном времени
const passwordInput = document.getElementById('password');
const confirmInput = document.getElementById('confirmPassword');
function validatePassword() {
const password = passwordInput.value;
const confirm = confirmInput.value;
const reqLength = document.getElementById('reqLength');
const reqMatch = document.getElementById('reqMatch');
// Проверка длины
if (password.length >= 6) {
reqLength.className = 'requirement valid';
reqLength.innerHTML = '<i class="fas fa-check-circle"></i> Минимум 6 символов ✓';
} else {
reqLength.className = 'requirement invalid';
reqLength.innerHTML = '<i class="fas fa-times-circle"></i> Минимум 6 символов';
}
// Проверка совпадения
if (password && confirm && password === confirm) {
reqMatch.className = 'requirement valid';
reqMatch.innerHTML = '<i class="fas fa-check-circle"></i> Пароли совпадают ✓';
} else if (confirm) {
reqMatch.className = 'requirement invalid';
reqMatch.innerHTML = '<i class="fas fa-times-circle"></i> Пароли совпадают';
} else {
reqMatch.className = 'requirement';
reqMatch.innerHTML = '<i class="far fa-circle"></i> Пароли совпадают';
}
}
passwordInput.addEventListener('input', validatePassword);
confirmInput.addEventListener('input', validatePassword);
// Функция для проверки корректности Telegram username
function validateTelegram(telegram) {
if (!telegram) return false;
// Telegram username может начинаться с @ или без него
// Допустимые символы: буквы, цифры, подчеркивание
const cleanTelegram = telegram.replace('@', '');
return /^[a-zA-Z0-9_]{5,32}$/.test(cleanTelegram);
}
// Функция для форматирования телефона
function formatPhone(phone) {
// Удаляем все нецифровые символы
let digits = phone.replace(/\D/g, '');
// Если номер начинается с 8 или 7, нормализуем
if (digits.length === 11) {
if (digits.startsWith('8')) {
digits = '7' + digits.substring(1);
}
} else if (digits.length === 10) {
digits = '7' + digits;
}
return digits;
}
// Показать сообщение об ошибке
function showError(message) {
const errorDiv = document.getElementById('errorMessage');
const errorText = document.getElementById('errorText');
@@ -335,112 +491,172 @@
setTimeout(() => {
errorDiv.style.display = 'none';
}, 4000);
}, 5000);
}
// Показать сообщение об успехе
function showSuccess(message) {
const successDiv = document.getElementById('successMessage');
const successText = document.getElementById('successText');
successText.textContent = message;
successDiv.style.display = 'flex';
setTimeout(() => {
successDiv.style.display = 'none';
}, 3000);
}
// Показать состояние загрузки
function setLoading(isLoading) {
const btn = document.getElementById('registerBtn');
const registerBtn = document.getElementById('registerBtn');
if (isLoading) {
btn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Регистрация...';
btn.disabled = true;
registerBtn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Регистрация...';
registerBtn.disabled = true;
isSubmitting = true;
} else {
btn.innerHTML = '<span>Зарегистрироваться</span><i class="fas fa-arrow-right"></i>';
btn.disabled = false;
registerBtn.innerHTML = '<span>Зарегистрироваться</span><i class="fas fa-arrow-right"></i>';
registerBtn.disabled = false;
isSubmitting = false;
}
}
// Обработка регистрации
async function handleRegister(event) {
event.preventDefault();
if (isSubmitting) return;
// Получаем значения полей
const fullName = document.getElementById('fullName').value.trim();
const email = document.getElementById('email').value.trim();
const phone = document.getElementById('phone').value.trim();
const telegram = document.getElementById('telegram').value.trim() || null;
const telegram = document.getElementById('telegram').value.trim();
const password = document.getElementById('password').value;
const confirmPassword = document.getElementById('confirmPassword').value;
// Определяем роль
const role = document.getElementById('roleEmployeeBtn').classList.contains('active') ? 'employee' : 'employer';
// Валидация
if (!fullName || !email || !phone || !password) {
showError('Заполните все обязательные поля');
// Валидация ФИО
if (!fullName) {
showError('Введите ФИО');
document.getElementById('fullName').focus();
return;
}
// Валидация email
if (!email) {
showError('Введите email');
document.getElementById('email').focus();
return;
}
if (!email.includes('@') || !email.includes('.')) {
showError('Введите корректный email');
document.getElementById('email').focus();
return;
}
// Валидация телефона
if (!phone) {
showError('Введите номер телефона');
document.getElementById('phone').focus();
return;
}
const phoneDigits = formatPhone(phone);
if (phoneDigits.length !== 11) {
showError('Введите корректный номер телефона (10 или 11 цифр)');
document.getElementById('phone').focus();
return;
}
// Валидация Telegram
if (!telegram) {
showError('Введите Telegram username');
document.getElementById('telegram').focus();
return;
}
if (!validateTelegram(telegram)) {
showError('Telegram username должен содержать от 5 до 32 символов (буквы, цифры, _)');
document.getElementById('telegram').focus();
return;
}
// Валидация пароля
if (password.length < 6) {
showError('Пароль должен быть минимум 6 символов');
showError('Пароль должен содержать минимум 6 символов');
document.getElementById('password').focus();
return;
}
if (password !== confirmPassword) {
showError('Пароли не совпадают');
document.getElementById('confirmPassword').focus();
return;
}
// Форматируем телефон для отправки
const formattedPhone = '+' + phoneDigits;
// Форматируем Telegram (добавляем @ если нет)
let formattedTelegram = telegram;
if (!telegram.startsWith('@')) {
formattedTelegram = '@' + telegram;
}
// Подготавливаем данные для отправки
const userData = {
full_name: fullName,
email: email,
phone: formattedPhone,
telegram: formattedTelegram,
password: password,
role: role
};
console.log('📤 Отправка данных регистрации:', {
...userData,
password: '***скрыто***'
});
setLoading(true);
try {
const userData = {
full_name: fullName,
email: email,
phone: phone,
telegram: telegram,
password: password,
role: role
};
console.log('Sending registration request...', { email: userData.email });
const response = await fetch(`${API_BASE_URL}/register`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json',
'X-Requested-With': 'XMLHttpRequest'
'Accept': 'application/json'
},
body: JSON.stringify(userData),
credentials: 'include' // Важно для мобильных
body: JSON.stringify(userData)
});
console.log('Response status:', response.status);
const data = await response.json();
console.log('📥 Ответ сервера:', data);
if (!response.ok) {
throw new Error(data.detail || 'Ошибка регистрации');
}
console.log('Registration successful');
// Успешная регистрация
showSuccess('Регистрация успешна! Перенаправляем...');
// Сохраняем токен
if (data.access_token) {
localStorage.setItem('accessToken', data.access_token);
localStorage.setItem('userId', data.user_id);
localStorage.setItem('userRole', data.role);
localStorage.setItem('userName', data.full_name);
localStorage.setItem('accessToken', data.access_token);
localStorage.setItem('userId', data.user_id);
localStorage.setItem('userRole', data.role);
localStorage.setItem('userName', data.full_name);
showSuccess('Регистрация успешна! Перенаправляем...');
setTimeout(() => {
window.location.href = '/profile';
}, 1500);
} else {
throw new Error('Токен не получен');
}
// Перенаправляем в профиль через секунду
setTimeout(() => {
window.location.href = '/profile';
}, 1500);
} catch (error) {
console.error('Registration error:', error);
showError(error.message || 'Ошибка соединения');
console.error('❌ Ошибка регистрации:', error);
showError(error.message);
setLoading(false);
}
}
@@ -454,6 +670,25 @@
}
});
// Автоматическое добавление @ в Telegram
document.getElementById('telegram').addEventListener('blur', function(e) {
let value = e.target.value.trim();
if (value && !value.startsWith('@')) {
e.target.value = '@' + value.replace(/[^a-zA-Z0-9_]/g, '');
}
});
// Ограничение ввода для Telegram (только буквы, цифры, _)
document.getElementById('telegram').addEventListener('input', function(e) {
let value = e.target.value;
// Если начинается с @, разрешаем @ только в начале
if (value.startsWith('@')) {
e.target.value = '@' + value.substring(1).replace(/[^a-zA-Z0-9_]/g, '');
} else {
e.target.value = value.replace(/[^a-zA-Z0-9_]/g, '');
}
});
// Проверка существующей сессии
if (localStorage.getItem('accessToken')) {
window.location.href = '/profile';

View File

@@ -932,6 +932,10 @@
</div>
<div class="qr-stats">
<div class="qr-stat-item">
<div class="qr-stat-value" id="qrViewCount">0</div> <!-- Добавлено -->
<div class="qr-stat-label">просмотров</div>
</div>
<div class="qr-stat-item">
<div class="qr-stat-value" id="qrUserRole"></div>
<div class="qr-stat-label">роль</div>
@@ -940,10 +944,6 @@
<div class="qr-stat-value" id="qrUserSince"></div>
<div class="qr-stat-label">на платформе</div>
</div>
<div class="qr-stat-item">
<div class="qr-stat-value" id="qrUserActivity">0</div>
<div class="qr-stat-label">активность</div>
</div>
</div>
<div class="qr-actions">
@@ -1488,54 +1488,44 @@
const modal = document.getElementById('qrModal');
if (!modal) {
console.error('❌ Модальное окно с id "qrModal" не найдено в DOM');
console.log('🔍 Поиск всех элементов с классом qr-modal:', document.querySelectorAll('.qr-modal'));
showNotification('Ошибка: модальное окно не найдено', 'error');
return;
}
// Проверяем все необходимые элементы
const elements = {
qrUserName: document.getElementById('qrUserName'),
qrUserUrl: document.getElementById('qrUserUrl'),
qrViewCount: document.getElementById('qrViewCount'),
qrUserRole: document.getElementById('qrUserRole'),
qrUserSince: document.getElementById('qrUserSince'),
qrUserActivity: document.getElementById('qrUserActivity'),
qrCanvas: document.getElementById('qrCanvas'),
qrLogoOverlay: document.getElementById('qrLogoOverlay'),
qrLogoIcon: document.getElementById('qrLogoIcon')
};
// Получаем элементы
const qrUserName = document.getElementById('qrUserName');
const qrUserUrl = document.getElementById('qrUserUrl');
const qrViewCountElement = document.getElementById('qrViewCount'); // Переименовал, чтобы не конфликтовать
const qrUserRole = document.getElementById('qrUserRole');
const qrUserSince = document.getElementById('qrUserSince');
const qrCanvas = document.getElementById('qrCanvas');
// Проверяем каждый элемент
let missingElements = [];
for (let [key, element] of Object.entries(elements)) {
if (!element) {
missingElements.push(key);
console.error(`❌ Элемент с id "${key}" не найден`);
}
}
if (missingElements.length > 0) {
console.error('❌ Отсутствуют элементы:', missingElements.join(', '));
// Проверяем наличие критически важных элементов
if (!qrUserName || !qrUserUrl || !qrViewCountElement || !qrUserRole || !qrUserSince || !qrCanvas) {
console.error('❌ Критические элементы модального окна не найдены');
console.log('qrUserName:', qrUserName);
console.log('qrUserUrl:', qrUserUrl);
console.log('qrViewCountElement:', qrViewCountElement);
console.log('qrUserRole:', qrUserRole);
console.log('qrUserSince:', qrUserSince);
console.log('qrCanvas:', qrCanvas);
showNotification('Ошибка отображения QR-кода', 'error');
return;
}
console.log('✅ Все элементы модального окна найдены');
// Устанавливаем имя пользователя
elements.qrUserName.textContent = escapeHtml(currentProfileUser.full_name);
qrUserName.textContent = escapeHtml(currentProfileUser.full_name);
// Формируем URL профиля
const profileUrl = window.location.origin + '/user/' + currentProfileUser.id;
elements.qrUserUrl.textContent = profileUrl.replace('https://', '').replace('http://', '');
qrUserUrl.textContent = profileUrl.replace('https://', '').replace('http://', '');
// Обновляем счетчик просмотров
if (typeof qrViewCount === 'undefined') {
window.qrViewCount = 0;
// Обновляем счетчик просмотров - используем отдельную переменную
if (typeof window.qrViewCounter === 'undefined') {
window.qrViewCounter = 0;
}
window.qrViewCount++;
elements.qrViewCount.textContent = window.qrViewCount;
window.qrViewCounter++;
qrViewCountElement.textContent = window.qrViewCounter;
// Роль пользователя
let roleText = '';
@@ -1543,7 +1533,7 @@
else if (currentProfileUser.role === 'employer') roleText = '🏢 Работодатель';
else if (currentProfileUser.role === 'admin') roleText = '👑 Админ';
else roleText = '👤 Пользователь';
elements.qrUserRole.textContent = roleText;
qrUserRole.textContent = roleText;
// Дата регистрации
if (currentProfileUser.created_at) {
@@ -1551,18 +1541,15 @@
const date = new Date(currentProfileUser.created_at);
const now = new Date();
const months = Math.floor((now - date) / (1000 * 60 * 60 * 24 * 30));
elements.qrUserSince.textContent = (months > 0 ? months : '< 1') + ' мес';
qrUserSince.textContent = (months > 0 ? months : '< 1') + ' мес';
} catch (e) {
console.error('Ошибка при вычислении даты:', e);
elements.qrUserSince.textContent = '—';
qrUserSince.textContent = '—';
}
} else {
elements.qrUserSince.textContent = '—';
qrUserSince.textContent = '—';
}
// Активность
elements.qrUserActivity.textContent = 'активен';
// Генерируем QR-код
try {
generateQRCodeWithLogo(profileUrl);
@@ -1573,7 +1560,7 @@
// Показываем модальное окно
modal.classList.add('active');
console.log('✅ QR-модальное окно открыто');
console.log('✅ QR-модальное окно открыто, счетчик:', window.qrViewCounter);
}
// Закрыть модальное окно