Реализовано без authlib, на голом httpx (AsyncClient — синхронный httpx
блокировал бы event loop API на время внешнего запроса), по образцу двух
провайдеров:
- Миграция 004: hashed_password → nullable (OAuth-юзеры без пароля),
oauth_provider/oauth_id + уникальный индекс на пару.
- app/core/security.py: verify_password защищён от hashed=None (иначе TypeError
при попытке OAuth-юзера войти по паролю — нашёл при ревью, не баг-репорт).
- app/core/oauth.py: get_authorize_url()/exchange_code() — единый интерфейс для
google/yandex. Redirect URI: <APP_URL>/api/auth/<provider>/callback.
- app/api/auth.py: GET /auth/{provider}/login (редирект на согласие, state в
httponly-cookie от CSRF) и /callback (обмен code, find-or-create юзера по
oauth_id → по email для привязки существующего аккаунта → новый без пароля,
is_verified=email_verified от провайдера). Токен фронту — через URL-фрагмент
#token=..., не query (не уходит в логи/Referer).
- Фронтенд: OAuthButtons (Login/Register), страница /oauth/callback (читает
фрагмент → GET /auth/me → setAuth → редирект в кабинет).
- 6 юнит-тестов чистой логики сборки ссылок (app/core/oauth.py) — первый тест-
контур для api/ в этой сессии (pytest.ini/conftest/requirements-test по
образцу остальных сервисов), добавлен в общий run_tests.sh + mypy-гейт.
GOOGLE_CLIENT_ID/SECRET уже в .env (юзер создал OAuth-клиент), YANDEX_* пусты —
эндпоинты в этом случае отвечают 503, не падают. .env.example документирует обе
пары. Тестов всего: 118 (было 112).
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
110 lines
4.1 KiB
TypeScript
110 lines
4.1 KiB
TypeScript
import React, { useState } from 'react';
|
||
import { Link, useNavigate } from 'react-router-dom';
|
||
import { useMutation } from '@tanstack/react-query';
|
||
import { GraduationCap } from 'lucide-react';
|
||
import toast from 'react-hot-toast';
|
||
import { authApi } from '../api/client';
|
||
import { OAuthButtons } from '../components/OAuthButtons';
|
||
import { useAuthStore } from '../store/auth';
|
||
import type { TokenResponse } from '../types';
|
||
|
||
export function Register() {
|
||
const navigate = useNavigate();
|
||
const { setAuth } = useAuthStore();
|
||
const [name, setName] = useState('');
|
||
const [email, setEmail] = useState('');
|
||
const [password, setPassword] = useState('');
|
||
|
||
const register = useMutation({
|
||
mutationFn: () => authApi.register({ name, email, password }),
|
||
onSuccess: (response) => {
|
||
const data: TokenResponse = response.data;
|
||
setAuth(data.user, data.access_token);
|
||
toast.success('Аккаунт создан! Проверьте email для подтверждения.');
|
||
navigate('/cabinet');
|
||
},
|
||
onError: (error: any) => {
|
||
const msg = error.response?.data?.detail || 'Ошибка регистрации';
|
||
toast.error(msg);
|
||
},
|
||
});
|
||
|
||
const handleSubmit = (e: React.FormEvent) => {
|
||
e.preventDefault();
|
||
register.mutate();
|
||
};
|
||
|
||
return (
|
||
<div className="max-w-md mx-auto pt-8">
|
||
<div className="bg-white rounded-2xl border border-gray-100 p-8">
|
||
<div className="flex justify-center mb-6">
|
||
<div className="p-3 bg-brand-600 rounded-xl">
|
||
<GraduationCap className="w-7 h-7 text-white" />
|
||
</div>
|
||
</div>
|
||
<h1 className="text-2xl font-bold text-gray-900 text-center mb-1">Регистрация</h1>
|
||
<p className="text-gray-400 text-center text-sm mb-6">Создайте аккаунт, это бесплатно</p>
|
||
|
||
<form onSubmit={handleSubmit} className="space-y-4">
|
||
<div>
|
||
<label className="text-sm font-medium text-gray-700 block mb-1">Имя</label>
|
||
<input
|
||
type="text"
|
||
value={name}
|
||
onChange={(e) => setName(e.target.value)}
|
||
required
|
||
minLength={2}
|
||
placeholder="Иван Иванов"
|
||
className="w-full border border-gray-200 rounded-xl px-4 py-2.5 text-sm focus:outline-none focus:ring-2 focus:ring-brand-500"
|
||
/>
|
||
</div>
|
||
|
||
<div>
|
||
<label className="text-sm font-medium text-gray-700 block mb-1">Email</label>
|
||
<input
|
||
type="email"
|
||
value={email}
|
||
onChange={(e) => setEmail(e.target.value)}
|
||
required
|
||
placeholder="ivan@example.com"
|
||
className="w-full border border-gray-200 rounded-xl px-4 py-2.5 text-sm focus:outline-none focus:ring-2 focus:ring-brand-500"
|
||
/>
|
||
</div>
|
||
|
||
<div>
|
||
<label className="text-sm font-medium text-gray-700 block mb-1">Пароль</label>
|
||
<input
|
||
type="password"
|
||
value={password}
|
||
onChange={(e) => setPassword(e.target.value)}
|
||
required
|
||
minLength={8}
|
||
placeholder="Минимум 8 символов"
|
||
className="w-full border border-gray-200 rounded-xl px-4 py-2.5 text-sm focus:outline-none focus:ring-2 focus:ring-brand-500"
|
||
/>
|
||
</div>
|
||
|
||
<button
|
||
type="submit"
|
||
disabled={register.isPending}
|
||
className="w-full py-2.5 bg-brand-600 text-white rounded-xl text-sm font-medium hover:bg-brand-700 disabled:opacity-50 transition-colors"
|
||
>
|
||
{register.isPending ? 'Создаём...' : 'Создать аккаунт'}
|
||
</button>
|
||
</form>
|
||
|
||
<div className="mt-4">
|
||
<OAuthButtons />
|
||
</div>
|
||
|
||
<p className="text-center text-sm text-gray-400 mt-6">
|
||
Уже есть аккаунт?{' '}
|
||
<Link to="/login" className="text-brand-600 hover:underline font-medium">
|
||
Войти
|
||
</Link>
|
||
</p>
|
||
</div>
|
||
</div>
|
||
);
|
||
}
|