AuthProvider.tsx 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. 'use client'
  2. import React, { useEffect, useState } from 'react'
  3. import { signIn, useSession } from "next-auth/react"
  4. import { ReactNode } from "react"
  5. import { useQuery } from "@tanstack/react-query";
  6. const queryAuthFn = async () => {
  7. const cookie = await fetch("https://beta.api.cocorobo.cn/api/getcookieuserid", {
  8. method: "GET",
  9. credentials: 'include',
  10. });
  11. const cookiejson = await cookie.json();
  12. const user = cookiejson?.[0]?.[0];
  13. if (cookie.ok && user) {
  14. return user
  15. }
  16. return null
  17. }
  18. const LoadingMask = () => {
  19. const { status } = useSession()
  20. if (status === 'loading') {
  21. return (
  22. <div className="absolute top-0 left-0 w-full h-full bg-black/50 flex items-center justify-center">
  23. <span className="loading loading-spinner loading-lg m-auto"></span>
  24. </div>
  25. )
  26. }
  27. return null
  28. }
  29. const AuthModal = ({ refetch }: { refetch: () => void }) => {
  30. useEffect(() => {
  31. const intervalId = setInterval(() => {
  32. refetch()
  33. }, 5000)
  34. return () => clearInterval(intervalId)
  35. }, [refetch])
  36. return (
  37. <dialog className="modal modal-open">
  38. <div className="modal-box relative">
  39. <iframe src="https://edu.cocorobo.cn/course/login?type=2"
  40. style={{ border: "0px", width: "450px", height: "480px" }}></iframe>
  41. <LoadingMask />
  42. </div>
  43. </dialog>
  44. )
  45. }
  46. export function AuthProvider({ children }: { children: ReactNode }) {
  47. const { status } = useSession()
  48. const { data: user, refetch, isLoading, isError, isFetching } = useQuery({ queryKey: ['auth'], queryFn: queryAuthFn })
  49. useEffect(() => {
  50. if (user && !isLoading && !isError && !isFetching) {
  51. signIn('credentials', { redirect: false, userId: user.userid })
  52. }
  53. }, [user, isLoading, isError, isFetching])
  54. if (status === 'authenticated' && !isLoading && !isError && !isFetching) {
  55. return children
  56. }
  57. return (
  58. <AuthModal refetch={refetch} />
  59. )
  60. }