73 lines
2.2 KiB
TypeScript
73 lines
2.2 KiB
TypeScript
"use client";
|
|
|
|
import { auth_api } from "@/features/auth/lib/api";
|
|
import LoginForm from "@/features/auth/ui/login";
|
|
import { userInfoStore } from "@/shared/hooks/user-info";
|
|
import { getToken, removeToken, saveToken } from "@/shared/lib/cookie";
|
|
import { useMutation } from "@tanstack/react-query";
|
|
import { useEffect } from "react";
|
|
|
|
const TokenLayout = ({ children }: { children: React.ReactNode }) => {
|
|
const { addedUser, loginUser, setLoginUser } = userInfoStore();
|
|
const token = getToken();
|
|
|
|
const { mutate: login, isPending } = useMutation({
|
|
mutationFn: (body: { telegram_id: string }) => auth_api.login(body),
|
|
onSuccess: (res) => {
|
|
const user = res.data.data;
|
|
setLoginUser({
|
|
active: user.is_active,
|
|
first_name: user.first_name,
|
|
last_name: user.last_name,
|
|
});
|
|
if (user.token) saveToken(user.token);
|
|
},
|
|
onError: () => {
|
|
removeToken();
|
|
setLoginUser(null);
|
|
},
|
|
});
|
|
|
|
useEffect(() => {
|
|
if (window.Telegram?.WebApp?.initDataUnsafe?.user) {
|
|
const user = window.Telegram.WebApp.initDataUnsafe.user;
|
|
console.log(user);
|
|
|
|
addedUser({
|
|
first_name: user.first_name,
|
|
last_name: user.last_name || "",
|
|
user_id: String(user.id),
|
|
active: false,
|
|
});
|
|
|
|
login({ telegram_id: String(user.id) });
|
|
}
|
|
}, [addedUser, login]);
|
|
|
|
if (isPending && loginUser === null) {
|
|
return (
|
|
<div className="fixed inset-0 z-50 flex flex-col items-center justify-center bg-slate-50 dark:bg-slate-900">
|
|
<div className="w-16 h-16 border-4 border-gray-300 border-t-emerald-500 rounded-full animate-spin"></div>
|
|
</div>
|
|
);
|
|
}
|
|
|
|
if (loginUser && !loginUser.active) {
|
|
return (
|
|
<div className="fixed inset-0 z-50 flex flex-col items-center justify-center bg-slate-50 dark:bg-slate-900">
|
|
<div className="w-16 h-16 rounded-full bg-emerald-500 animate-pulse"></div>
|
|
<h3 className="mt-4 text-xl font-semibold text-foreground dark:text-white">
|
|
Foydalanuvchi aktivlashtirilmoqda...
|
|
</h3>
|
|
<p className="text-sm text-muted-foreground mt-1">
|
|
Iltimos, bir necha soniya kuting
|
|
</p>
|
|
</div>
|
|
);
|
|
}
|
|
|
|
return <>{token ? children : <LoginForm />}</>;
|
|
};
|
|
|
|
export default TokenLayout;
|