root 2 months ago
parent
commit
a5ba6ca851
3 changed files with 71 additions and 14 deletions
  1. 15 10
      app/api/auth/[...nextauth]/route.ts
  2. 55 4
      app/run-agent-flow/components/Header.tsx
  3. 1 0
      package.json

+ 15 - 10
app/api/auth/[...nextauth]/route.ts

@@ -13,16 +13,19 @@ export const authOptions = {
       // e.g. domain, username, password, 2FA token, etc.
       // You can pass any HTML attribute to the <input> tag through the object.
       credentials: {
-        loginUsername: { label: "用户名", type: "text" },
-        loginPassword: { label: "密码", type: "password" },
+        userid: { label: 'userid', type: 'text' }
+        // loginUsername: { label: "用户名", type: "text" },
+        // loginPassword: { label: "密码", type: "password" },
       },
       async authorize(credentials, req) {
+        return { userid: credentials.userid };
         // You need to provide your own logic here that takes the credentials
         // submitted and returns either a object representing a user or value
         // that is false/null if the credentials are invalid.
         // e.g. return { id: 1, name: 'J Smith', email: 'jsmith@example.com' }
         // You can also use the `req` object to obtain additional parameters
         // (i.e., the request IP address)
+        /*
         const res = await fetch("https://beta.api.cocorobo.cn/api/user", {
           method: "POST",
           body: JSON.stringify(
@@ -43,19 +46,20 @@ export const authOptions = {
         if (res.ok && user && user.active) {
           return { ...user, id: user.userid, name: user.username };
         }
-        // Return null if user data could not be retrieved
-        return null;
+        */
+
+
       },
     }),
   ],
   callbacks: {
-    async session({ session, token }) {
-      console.log(session, token);
+    async session({ session, user }) {
+      console.log(session, user);
       // Send properties to the client, like an access_token from a provider.
-      session.user.id = token.sub;
+      session.user.id = user.userid;
       try {
         const res = await fetch(
-          `https://pbl.cocorobo.cn/api/pbl/selectUser?userid=${token.sub}`,
+          `https://pbl.cocorobo.cn/api/pbl/selectUser?userid=${user.userid}`,
           {
             method: "GET",
             headers: {
@@ -65,8 +69,9 @@ export const authOptions = {
         );
         const username = (await res.json())?.[0]?.[0]?.username;
         session.user.name = username;
-      } catch (e) {
-        session.user.name = token.name;
+      }
+      catch (e) {
+        return null;
       }
       return session;
     },

+ 55 - 4
app/run-agent-flow/components/Header.tsx

@@ -4,6 +4,7 @@ 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()
@@ -16,6 +17,12 @@ export default function Header() {
   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 () => {
@@ -27,9 +34,49 @@ export default function Header() {
       setIsLogInFail(true)
     }
   }
+
+  // useEffect(() => {
+  //   setIsLogInFail(false)
+  // }, [username, password, org])
+
+
+  /*
+  用户登陆判断
+*/
   useEffect(() => {
-    setIsLogInFail(false)
-  }, [username, password, org])
+    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",
+          headers: {
+            Origin: "https://edu.cocorobo.cn"
+          },
+        });
+        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 (
     <div className="navbar bg-base-100 shadow-xl rounded-box justify-center min-h-4 relative">
@@ -52,7 +99,11 @@ export default function Header() {
           <>
             <dialog className="modal modal-open" onCancel={event => event.preventDefault()}>
               <div className="modal-box">
-                <h3 className="font-bold text-lg">您需要先登录</h3>
+                <iframe src="https://edu.cocorobo.cn/course/login?type=2"
+                  style={{ border: "0px", width: "450px", height: "480px" }}></iframe>
+              </div>
+              <div className="modal-box" style={{ display: "none" }} >
+                <h3 className="font-bold text-lg" >您需要先登录</h3>
                 <div className="w-full flex flex-col items-center gap-2 py-2">
                   {isLogInFail && <div role="alert" className="alert alert-error">
                     <span>账号或密码错误</span>
@@ -83,6 +134,6 @@ export default function Header() {
           </>
         )
       }
-    </div>
+    </div >
   )
 }

+ 1 - 0
package.json

@@ -15,6 +15,7 @@
     "@trpc/react-query": "^11.0.0-rc.482",
     "@trpc/server": "^11.0.0-rc.482",
     "jotai": "^2.9.3",
+    "js-cookie": "^3.0.5",
     "next": "14.2.5",
     "next-auth": "^4.24.7",
     "ramda": "^0.30.1",