65 lines
1.7 KiB
TypeScript
65 lines
1.7 KiB
TypeScript
'use client';
|
|
import { getProfile, updateProfile } from '@/actions/profile';
|
|
import { LoadingSpinner } from '@repo/ui/components/ui/spinner';
|
|
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, useState } from 'react';
|
|
|
|
export default function Auth() {
|
|
const initDataUser = useSignal(initData.user);
|
|
const isDark = isMiniAppDark();
|
|
const { status } = useSession();
|
|
const { setTheme } = useTheme();
|
|
const [isUpdating, setIsUpdating] = useState(true);
|
|
|
|
useEffect(() => {
|
|
setTheme(isDark ? 'dark' : 'light');
|
|
|
|
const update = async () => {
|
|
if (initDataUser?.photoUrl) {
|
|
await updateProfile({ photoUrl: initDataUser.photoUrl });
|
|
}
|
|
|
|
const customer = await getProfile({ telegramId: initDataUser?.id });
|
|
|
|
if (!customer?.active) {
|
|
await updateProfile({
|
|
active: true,
|
|
name: `${initDataUser?.firstName || ''} + ' ' + ${initDataUser?.lastName}`.trim(),
|
|
});
|
|
}
|
|
|
|
setIsUpdating(false);
|
|
};
|
|
|
|
update();
|
|
}, [
|
|
initDataUser?.firstName,
|
|
initDataUser?.id,
|
|
initDataUser?.lastName,
|
|
initDataUser?.photoUrl,
|
|
isDark,
|
|
setTheme,
|
|
]);
|
|
|
|
useEffect(() => {
|
|
if (isUpdating) return;
|
|
|
|
if (status === 'authenticated') {
|
|
redirect('/profile');
|
|
}
|
|
|
|
if (status === 'unauthenticated' && initDataUser?.id) {
|
|
signIn('telegram', {
|
|
callbackUrl: '/profile',
|
|
redirect: false,
|
|
telegramId: String(initDataUser.id),
|
|
});
|
|
}
|
|
}, [initDataUser?.id, isUpdating, status]);
|
|
|
|
return <LoadingSpinner />;
|
|
}
|