- Updated the authentication logic in both Auth and useAuth functions to redirect unregistered users to the '/unregistered' page. - Enhanced error handling in the authOptions to check for user registration status using the Telegram ID. - Improved the matcher configuration in middleware to exclude the '/unregistered' route from authentication checks.
56 lines
1.4 KiB
TypeScript
56 lines
1.4 KiB
TypeScript
/* eslint-disable promise/prefer-await-to-then */
|
|
'use client';
|
|
|
|
import { initData, isMiniAppDark, useSignal } from '@telegram-apps/sdk-react';
|
|
import { signIn, useSession } from 'next-auth/react';
|
|
import { useTheme } from 'next-themes';
|
|
import { redirect } from 'next/navigation';
|
|
import { useEffect } from 'react';
|
|
|
|
export default function Auth() {
|
|
useTelegramTheme();
|
|
useAuth();
|
|
|
|
return null;
|
|
}
|
|
|
|
function useAuth() {
|
|
const initDataUser = useSignal(initData.user);
|
|
const { status } = useSession();
|
|
|
|
useEffect(() => {
|
|
if (!initDataUser?.id) return;
|
|
|
|
if (status === 'authenticated') {
|
|
redirect('/profile');
|
|
}
|
|
|
|
if (status === 'unauthenticated') {
|
|
signIn('telegram', {
|
|
callbackUrl: '/profile',
|
|
redirect: false,
|
|
telegramId: initDataUser.id.toString(),
|
|
}).then((result) => {
|
|
if (
|
|
result?.error &&
|
|
(result?.error?.includes('CredentialsSignin') || result?.error?.includes('UNREGISTERED'))
|
|
) {
|
|
// Пользователь не зарегистрирован
|
|
redirect('/unregistered');
|
|
} else if (result?.ok) {
|
|
redirect('/profile');
|
|
}
|
|
});
|
|
}
|
|
}, [initDataUser?.id, status]);
|
|
}
|
|
|
|
function useTelegramTheme() {
|
|
const isDark = isMiniAppDark();
|
|
const { setTheme } = useTheme();
|
|
|
|
useEffect(() => {
|
|
setTheme(isDark ? 'dark' : 'light');
|
|
}, [isDark, setTheme]);
|
|
}
|