'use client' import { BsCaretDownFill } from "react-icons/bs"; import { useSession, signIn, signOut } from "next-auth/react" import { createRef, useEffect, useState } from "react"; import { useQuery } from "@tanstack/react-query"; import { trpc } from "@/lib/trpc"; import Cookies from 'js-cookie'; export default function Header() { const { data: session, status } = useSession() const [org, setOrg] = useState('') const [username, setUsername] = useState('') const [password, setPassword] = useState('') const [isLogInFail, setIsLogInFail] = useState(false) const orgQuery = trpc.org.bySlug.useQuery({ mode: org }) const logOut = async () => { const res = await fetch(" beta.api.cocorobo.cn/api/logout", { method: "GET", headers: { Origin: "https://edu.cocorobo.cn" }, }); await signOut({ redirect: false }) } const logIn = async () => { const loginUsername = orgQuery.data?.mail ? `${username}@${orgQuery.data?.mail}` : `${username}@cocorobo.cc` const loginPassword = btoa(password) const res = await signIn('credentials', { redirect: false, loginUsername, loginPassword }) console.log(res) if (!res.ok) { setIsLogInFail(true) } } // useEffect(() => { // setIsLogInFail(false) // }, [username, password, org]) /* 用户登陆判断 */ useEffect(() => { const checkLoginStatus = async (intervalId) => { // 检查名为 'authToken' 的 cookie 是否存在 const authToken = Cookies.get('cocorobo'); console.log(authToken) const tf = authToken ? true : false; if (status !== 'authenticated') {//tf && const cookie = await fetch("https://beta.api.cocorobo.cn/api/getcookieuserid", { method: "GET", credentials: 'include', }); try { const cookiejson = await cookie.json(); console.log(cookiejson); const user = cookiejson?.[0]?.[0]; if (cookie.ok && user) { const res = await signIn('credentials', { redirect: false, userid: user.userid }) setIsLogInFail(true); clearInterval(intervalId); } } catch (e) { setIsLogInFail(false) } } setIsLogInFail(authToken); // 如果存在 authToken,则用户已登录 }; console.log("start") const intervalId = setInterval(async () => { await checkLoginStatus(intervalId); }, 5000); return () => { clearInterval(intervalId) } }, []); return (
选择对话
{status === 'authenticated' ? (

Hi, {session.user?.name}

) : ( <> event.preventDefault()}>

您需要先登录

{isLogInFail &&
账号或密码错误
}
) }
) }