AuthProvider.tsx 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  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 = () => {
  30. const { data: user, refetch } = useQuery({ queryKey: ['auth'], queryFn: queryAuthFn })
  31. useEffect(() => {
  32. const intervalId = setInterval(() => {
  33. refetch()
  34. }, 5000)
  35. return () => clearInterval(intervalId)
  36. }, [refetch])
  37. useEffect(() => {
  38. if (user) {
  39. signIn('credentials', { redirect: false, userId: user.userid })
  40. }
  41. }, [user])
  42. return (
  43. <dialog className="modal modal-open">
  44. <div className="modal-box relative">
  45. <iframe src="https://edu.cocorobo.cn/course/login?type=2"
  46. style={{ border: "0px", width: "450px", height: "480px" }}></iframe>
  47. <LoadingMask />
  48. </div>
  49. </dialog>
  50. )
  51. }
  52. export function AuthProvider({ children }: { children: ReactNode }) {
  53. const { data: session, status } = useSession()
  54. if (status === 'authenticated') {
  55. return children
  56. }
  57. return (
  58. <AuthModal />
  59. )
  60. }