feat(auth): вход через Google и Яндекс (OAuth2 authorization code flow)
All checks were successful
Deploy / test (push) Successful in 2m48s
Deploy / deploy (push) Successful in 23s

Реализовано без 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>
This commit is contained in:
jze9
2026-08-24 17:59:10 +05:00
parent 251be1d77b
commit 9f35ae8de1
19 changed files with 488 additions and 8 deletions

View File

@@ -0,0 +1,27 @@
// Кнопки входа через Google/Яндекс — обычные <a>, не React Router Link:
// это реальная навигация браузера на бэкенд (/api/auth/{provider}/login),
// который редиректит на экран согласия провайдера, а не SPA-переход.
export function OAuthButtons() {
return (
<div className="space-y-3">
<div className="flex items-center gap-3">
<div className="h-px flex-1 bg-gray-200" />
<span className="text-xs text-gray-400">или</span>
<div className="h-px flex-1 bg-gray-200" />
</div>
<a
href="/api/auth/google/login"
className="w-full flex items-center justify-center gap-2 py-2.5 border border-gray-200 rounded-xl text-sm font-medium text-gray-700 hover:bg-gray-50 transition-colors"
>
Продолжить с Google
</a>
<a
href="/api/auth/yandex/login"
className="w-full flex items-center justify-center gap-2 py-2.5 border border-gray-200 rounded-xl text-sm font-medium text-gray-700 hover:bg-gray-50 transition-colors"
>
Продолжить с Яндекс
</a>
</div>
);
}

View File

@@ -15,6 +15,7 @@ import { Task } from './pages/Task';
import { Pricing } from './pages/Pricing';
import { Login } from './pages/Login';
import { Register } from './pages/Register';
import { OAuthCallback } from './pages/OAuthCallback';
import { VerifyEmail } from './pages/VerifyEmail';
import { AdminLayout } from './pages/admin/AdminLayout';
import { Dashboard } from './pages/admin/Dashboard';
@@ -51,6 +52,7 @@ function PublicApp() {
<Route path="/pricing" element={<Pricing />} />
<Route path="/login" element={<Login />} />
<Route path="/register" element={<Register />} />
<Route path="/oauth/callback" element={<OAuthCallback />} />
<Route path="/verify-email/:token" element={<VerifyEmail />} />
</Routes>
</Layout>

View File

@@ -4,6 +4,7 @@ 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';
@@ -78,6 +79,10 @@ export function Login() {
</button>
</form>
<div className="mt-4">
<OAuthButtons />
</div>
<p className="text-center text-sm text-gray-400 mt-6">
Нет аккаунта?{' '}
<Link to="/register" className="text-brand-600 hover:underline font-medium">

View File

@@ -0,0 +1,45 @@
import { useEffect } from 'react';
import { useNavigate } from 'react-router-dom';
import toast from 'react-hot-toast';
import { api } from '../api/client';
import { useAuthStore } from '../store/auth';
import type { User } from '../types';
// Токен приходит в URL-фрагменте (#token=...) после редиректа с бэкенда
// (см. app/api/auth.py::oauth_callback) — фрагмент не уходит на сервер и не
// попадает в логи/Referer, в отличие от query-параметра.
export function OAuthCallback() {
const navigate = useNavigate();
const { setAuth } = useAuthStore();
useEffect(() => {
const params = new URLSearchParams(window.location.hash.slice(1));
const token = params.get('token');
if (!token) {
toast.error('Не удалось войти — токен не получен');
navigate('/login');
return;
}
// Токен ещё не в сторе — передаём явным заголовком в обход interceptor'а
api
.get('/auth/me', { headers: { Authorization: `Bearer ${token}` } })
.then((response) => {
const user: User = response.data;
setAuth(user, token);
toast.success(`Добро пожаловать, ${user.name}!`);
navigate('/cabinet');
})
.catch(() => {
toast.error('Не удалось войти — попробуйте ещё раз');
navigate('/login');
});
}, [navigate, setAuth]);
return (
<div className="max-w-md mx-auto pt-16 text-center text-gray-500 text-sm">
Выполняется вход…
</div>
);
}

View File

@@ -4,6 +4,7 @@ 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';
@@ -92,6 +93,10 @@ export function Register() {
</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">