add new yandex auth

This commit is contained in:
smanylov
2026-03-11 18:21:19 +07:00
parent e8f4f9939f
commit 9fbb74ba60
8 changed files with 156 additions and 20 deletions
+53
View File
@@ -0,0 +1,53 @@
'use client'
import { useEffect } from 'react';
import { useSearchParams, useRouter } from 'next/navigation';
import styles from '@/app/styles/module/login.module.scss'
export default function YandexCallback() {
const searchParams = useSearchParams();
const router = useRouter();
useEffect(() => {
const code = searchParams.get('code');
const error = searchParams.get('error');
if (error) {
console.error('Ошибка авторизации:', error);
router.push('/login?error=yandex_denied');
return;
}
if (code) {
console.log('получаю код');
console.log(code);
fetch('/api/auth/yandex/callback', {
method: 'POST',
body: JSON.stringify({ code })
})
.then(res => res.json())
.then(data => {
if (data.success) {
console.log(data);
console.log('all ok');
/* router.push('/dashboard'); */
}
});
}
}, [searchParams, router]);
return (
<div
className={`${styles['login-container-wrapper']}`}
>
<div
className="loading-animation"
>
<div
className="global-spinner large"
>
</div>
</div>
</div>
)
}
+2 -1
View File
@@ -9,6 +9,7 @@ import VKLogin from '@/app/components/VKLogin';
import YandexAuthWithScript from '@/app/components/YandexLogin';
import { getHealt } from '@/app/actions/action';
import { Suspense } from 'react';
import {YandexLoginButton} from '@/app/components/YandexLoginButton';
export const metadata: Metadata = {
title: 'Login',
@@ -51,7 +52,7 @@ export default function Page() {
<VKLogin />
</div>
<div>
<YandexAuthWithScript />
<YandexLoginButton />
</div>
<div className={`${styles['register-link']}`}>
<p>{t('no-account')}?
-1
View File
@@ -4,7 +4,6 @@ import { API_BASE_URL } from '@/app/actions/definitions';
import { createSession } from '@/app/actions/session';
import { redirect } from 'next/navigation';
export async function YandexAuthorization(data: any, codeVerifier: string) {
console.log(data);
+38
View File
@@ -0,0 +1,38 @@
import { NextResponse } from 'next/server';
export async function POST(request: Request) {
const { code } = await request.json();
try {
const response = await fetch('https://oauth.yandex.ru/token', {
method: 'POST',
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
body: new URLSearchParams({
grant_type: 'authorization_code',
code,
client_id: 'b356a7ceac0f4c50a3b434220f86bce0',
client_secret: '0800f7774f7d4e19ad4b434f10afd4ab',
})
});
const data = await response.json();
console.log(data);
if (data.access_token) {
const userInfo = await fetch('https://login.yandex.ru/info?format=json', {
headers: { 'Authorization': `OAuth ${data.access_token}` }
}).then(r => r.json());
console.log(userInfo);
// Тут мне нужно будет отправить сделать запрос в бек с userInfo и там уже редиректить на дешборд
return NextResponse.json({ success: true });
}
} catch (error) {
console.error('Token exchange failed:', error);
}
return NextResponse.json({ success: false }, { status: 400 });
}
+11 -18
View File
@@ -14,10 +14,6 @@ export default function YandexAuthWithScript() {
const [isReady, setIsReady] = useState(false);
const [showButton, setShowButton] = useState(true);
const handleLogin = (token: string) => {
console.log('handleLogin');
};
useEffect(() => {
if (!isReady || !buttonRef.current || !window.YaAuthSuggest) return;
@@ -25,31 +21,28 @@ export default function YandexAuthWithScript() {
{
client_id: 'b356a7ceac0f4c50a3b434220f86bce0',
response_type: 'token',
redirect_uri: `http://localhost:2999/ru/login`,
redirect_uri: `https://fallibly-desired-moonfish.cloudpub.ru/en/login`,
},
'http://localhost:2999',
'https://fallibly-desired-moonfish.cloudpub.ru',
{
parentId: buttonRef.current.id,
view: 'button',
buttonView: 'main',
buttonTheme: 'light',
buttonSize: 'm',
buttonSize: 'l',
buttonBorderRadius: 10
}
)
.then((result: any) => {
console.log('then');
.then(function (result: any) {
console.log('you at least try?')
console.log(result);
if (result?.access_token) {
handleLogin(result.access_token);
} else {
setTimeout(() => {
setShowButton(false);
}, 1000)
}
return result.handler();
})
.catch((error: any) => {
console.error('Yandex auth error:', error);
.then(function (data: any) {
console.log('Сообщение с токеном: ', data);
})
.catch(function (error: any) {
console.log('Что-то пошло не так: ', error);
});
}, [isReady]);
+15
View File
@@ -0,0 +1,15 @@
export function YandexLoginButton() {
const clientId = 'b356a7ceac0f4c50a3b434220f86bce0';
const redirectUri = encodeURIComponent('https://fallibly-desired-moonfish.cloudpub.ru/login/callback');
const authUrl = `https://oauth.yandex.ru/authorize?response_type=code&client_id=${clientId}&redirect_uri=${redirectUri}&force_confirm=yes`;
return (
<a
href={authUrl}
className="yandex-auth-button"
>
Войти через Яндекс
</a>
);
}
+26
View File
@@ -711,3 +711,29 @@
font-weight: 500;
}
}
.yandex-auth-button {
display: flex;
align-items: center;
justify-content: center;
gap: 10px;
padding: 14px 24px;
border: none;
border-radius: 8px;
font-size: 16px;
font-weight: 500;
cursor: pointer;
transition: all 0.2s ease;
text-decoration: none;
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
width: 100%;
box-sizing: border-box;
background: #000000;
color: #FFFFFF;
&:hover {
background: #1a1a1a;
box-shadow: 0 4px 16px rgba(0, 0, 0, 0.25);
/* transform: translateY(-2px); */
}
}
+11
View File
@@ -3983,6 +3983,17 @@
border-radius: 50%;
animation: spin 1s linear infinite;
}
&.large {
width: 80px;
height: 80px;
&::before {
border: 10px solid #e5e7eb;
border-top: 10px solid #667eea;
}
}
}
}