From 20b35078f0371390f567fd54523b0a2ff08d6f48 Mon Sep 17 00:00:00 2001 From: sijinhui Date: Sat, 30 Mar 2024 22:41:41 +0800 Subject: [PATCH 1/4] =?UTF-8?q?=E5=88=9D=E6=AC=A1=E4=BC=98=E5=8C=96?= =?UTF-8?q?=E8=AE=A4=E8=AF=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/api/common.ts | 15 +++++++------ app/api/logs/[...path]/route.ts | 12 ---------- app/api/openai/[...path]/route.ts | 6 ++--- lib/auth.ts | 12 +++++++--- middleware.ts | 37 +++++++++++++++---------------- 5 files changed, 37 insertions(+), 45 deletions(-) diff --git a/app/api/common.ts b/app/api/common.ts index c6bf431fb..ad994190c 100644 --- a/app/api/common.ts +++ b/app/api/common.ts @@ -4,6 +4,7 @@ import { DEFAULT_MODELS, OPENAI_BASE_URL, GEMINI_BASE_URL } from "../constant"; import { collectModelTable } from "../utils/model"; import { makeAzurePath } from "../azure"; import { getIP } from "@/app/api/auth"; +import { getSessionName } from "@/lib/auth"; const serverConfig = getServerSideConfig(); @@ -149,22 +150,22 @@ export async function requestLog( req: NextRequest, jsonBody: any, url_path: string, + name?: string, ) { // LOG try { if (url_path.startsWith("mj/") && !url_path.startsWith("mj/submit/")) { return; } - // const protocol = req.headers.get("x-forwarded-proto") || "http"; - //const baseUrl = process.env.NEXTAUTH_URL ?? "http://localhost:3000"; const baseUrl = "http://localhost:3000"; const ip = getIP(req); // 对其进行 Base64 解码 - let h_userName = req.headers.get("x-request-name"); - if (h_userName) { - const buffer = Buffer.from(h_userName, "base64"); - h_userName = decodeURIComponent(buffer.toString("utf-8")); - } + // let h_userName = req.headers.get("x-request-name"); + // if (h_userName) { + // const buffer = Buffer.from(h_userName, "base64"); + // h_userName = decodeURIComponent(buffer.toString("utf-8")); + // } + let h_userName = await getSessionName(); console.log("[中文]", h_userName, baseUrl); const logData = { ip: ip, diff --git a/app/api/logs/[...path]/route.ts b/app/api/logs/[...path]/route.ts index 5083853dd..8a1839622 100644 --- a/app/api/logs/[...path]/route.ts +++ b/app/api/logs/[...path]/route.ts @@ -1,20 +1,8 @@ import { NextRequest, NextResponse } from "next/server"; import prisma from "@/lib/prisma"; import { insertUser } from "@/lib/auth"; -// import { getTokenLength } from "@/app/utils/token"; -// import { Tiktoken } from "tiktoken/lite" -// import cl100k_base from "tiktoken/encoders/cl100k_base.json" -// import "tiktoken"; -// import { get_encoding } from "tiktoken"; -import { addHours, subMinutes } from "date-fns"; import { getTokenLength } from "@/lib/utils"; -// function getTokenLength(input: string): number { -// const encoding = get_encoding("cl100k_base"); -// // console.log('tokens: ', input, encoding.countTokens()) -// return encoding.encode(input).length; -// } - async function handle( req: NextRequest, { params }: { params: { path: string[] } }, diff --git a/app/api/openai/[...path]/route.ts b/app/api/openai/[...path]/route.ts index 9e4352413..8b47aa937 100644 --- a/app/api/openai/[...path]/route.ts +++ b/app/api/openai/[...path]/route.ts @@ -8,10 +8,8 @@ import { } from "@/app/constant"; import { prettyObject } from "@/app/utils/format"; import { NextRequest, NextResponse } from "next/server"; -import { auth, getIP } from "../../auth"; -import { getToken } from "next-auth/jwt"; +import { auth } from "../../auth"; import { requestLog, requestOpenai } from "../../common"; -import { headers } from "next/headers"; const ALLOWD_PATH = new Set(Object.values({ ...OpenaiPath, ...AZURE_PATH })); @@ -113,7 +111,7 @@ async function handle( export const GET = handle; export const POST = handle; -export const runtime = "edge"; +// export const runtime = "edge"; export const preferredRegion = [ "arn1", "bom1", diff --git a/lib/auth.ts b/lib/auth.ts index e0a17356f..0388479d5 100644 --- a/lib/auth.ts +++ b/lib/auth.ts @@ -2,10 +2,10 @@ import {getServerSession, type NextAuthOptions, Theme} from "next-auth"; import GitHubProvider from "next-auth/providers/github"; import EmailProvider from "next-auth/providers/email"; import CredentialsProvider from "next-auth/providers/credentials"; -import { PrismaAdapter } from "@next-auth/prisma-adapter"; +import {PrismaAdapter} from "@next-auth/prisma-adapter"; import prisma from "@/lib/prisma"; -import { isEmail, isName } from "@/lib/auth_list"; -import { createTransport } from "nodemailer"; +import {isEmail, isName} from "@/lib/auth_list"; +import {createTransport} from "nodemailer"; const SECURE_COOKIES:boolean = !!process.env.SECURE_COOKIES; @@ -157,6 +157,12 @@ export function getSession() { } | null>; } +export async function getSessionName() { + const session = await getSession(); + // console.log('in........',) + return session?.user?.email || session?.user?.name +} + // export function withSiteAuth(action: any) { // return async ( // formData: FormData | null, diff --git a/middleware.ts b/middleware.ts index 781b4dda0..d8d168a32 100644 --- a/middleware.ts +++ b/middleware.ts @@ -1,8 +1,7 @@ import { NextResponse } from "next/server"; import type { NextRequest } from "next/server"; import { getToken } from "next-auth/jwt"; -import { DENY_LIST, isName, ADMIN_LIST } from "@/lib/auth_list"; -import {use} from "react"; +import { isName, ADMIN_LIST } from "@/lib/auth_list"; export default async function middleware(req: NextRequest) { const url = req.nextUrl; @@ -60,23 +59,23 @@ export default async function middleware(req: NextRequest) { ); } - if (req.method == 'POST' && (path.startsWith("/api/openai/") || path.startsWith("/api/midjourney"))) { - // 重写header,添加用户名 - // console.log(session,'========') - const requestHeaders = new Headers(req.headers) - - // 使用 encodeURIComponent 对特殊字符进行编码 - // 将编码的 URI 组件转换成 Base64 - const encodeName = Buffer.from(encodeURIComponent(`${session?.name}`)).toString('base64'); - - requestHeaders.set('x-request-name', encodeName) - return NextResponse.next({ - request: { - // New request headers - headers: requestHeaders, - }, - }) - } + // if (req.method == 'POST' && (path.startsWith("/api/openai/") || path.startsWith("/api/midjourney"))) { + // // 重写header,添加用户名 + // // console.log(session,'========') + // const requestHeaders = new Headers(req.headers) + // + // // 使用 encodeURIComponent 对特殊字符进行编码 + // // 将编码的 URI 组件转换成 Base64 + // const encodeName = Buffer.from(encodeURIComponent(`${session?.name}`)).toString('base64'); + // + // requestHeaders.set('x-request-name', encodeName) + // return NextResponse.next({ + // request: { + // // New request headers + // headers: requestHeaders, + // }, + // }) + // } return NextResponse.next() } From 8debb785fb2a53c364b038d29b692dc789ab6698 Mon Sep 17 00:00:00 2001 From: sijinhui Date: Sat, 30 Mar 2024 22:49:01 +0800 Subject: [PATCH 2/4] =?UTF-8?q?=E5=88=9D=E6=AC=A1=E4=BC=98=E5=8C=96?= =?UTF-8?q?=E8=AE=A4=E8=AF=81-=E6=9F=A5=E8=AF=A2=E5=B7=B2=E5=AD=98?= =?UTF-8?q?=E5=9C=A8=E7=94=A8=E6=88=B7=E6=97=B6=E9=80=BB=E8=BE=91=E9=97=AE?= =?UTF-8?q?=E9=A2=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/api/common.ts | 8 +------- app/api/logs/[...path]/route.ts | 2 +- 2 files changed, 2 insertions(+), 8 deletions(-) diff --git a/app/api/common.ts b/app/api/common.ts index ad994190c..bbc3fd6bf 100644 --- a/app/api/common.ts +++ b/app/api/common.ts @@ -159,12 +159,6 @@ export async function requestLog( } const baseUrl = "http://localhost:3000"; const ip = getIP(req); - // 对其进行 Base64 解码 - // let h_userName = req.headers.get("x-request-name"); - // if (h_userName) { - // const buffer = Buffer.from(h_userName, "base64"); - // h_userName = decodeURIComponent(buffer.toString("utf-8")); - // } let h_userName = await getSessionName(); console.log("[中文]", h_userName, baseUrl); const logData = { @@ -172,7 +166,7 @@ export async function requestLog( path: url_path, logEntry: JSON.stringify(jsonBody), model: url_path.startsWith("mj/") ? "midjourney" : jsonBody?.model, // 后面尝试请求是添加到参数 - userName: h_userName, + name: h_userName, }; await fetch(`${baseUrl}/api/logs/openai`, { diff --git a/app/api/logs/[...path]/route.ts b/app/api/logs/[...path]/route.ts index 8a1839622..43182faa9 100644 --- a/app/api/logs/[...path]/route.ts +++ b/app/api/logs/[...path]/route.ts @@ -10,7 +10,7 @@ async function handle( try { const request_data = await req.json(); if (request_data?.userName) { - await insertUser({ name: request_data?.userName }); + await insertUser({ name: request_data?.name, email: request_data?.name }); } // console.log("===========4", request_data); try { From cea656ec9a1a1cafaeef6cd6acacf66563657780 Mon Sep 17 00:00:00 2001 From: sijinhui Date: Sat, 30 Mar 2024 23:59:41 +0800 Subject: [PATCH 3/4] =?UTF-8?q?'=E4=BF=AE=E5=A4=8D=E5=91=BD=E5=90=8D?= =?UTF-8?q?=E9=94=99=E8=AF=AF'?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/api/common.ts | 2 +- app/api/logs/[...path]/route.ts | 5 ++++- 2 files changed, 5 insertions(+), 2 deletions(-) diff --git a/app/api/common.ts b/app/api/common.ts index bbc3fd6bf..a50da30e5 100644 --- a/app/api/common.ts +++ b/app/api/common.ts @@ -166,7 +166,7 @@ export async function requestLog( path: url_path, logEntry: JSON.stringify(jsonBody), model: url_path.startsWith("mj/") ? "midjourney" : jsonBody?.model, // 后面尝试请求是添加到参数 - name: h_userName, + userName: h_userName, }; await fetch(`${baseUrl}/api/logs/openai`, { diff --git a/app/api/logs/[...path]/route.ts b/app/api/logs/[...path]/route.ts index 43182faa9..aad4ad087 100644 --- a/app/api/logs/[...path]/route.ts +++ b/app/api/logs/[...path]/route.ts @@ -10,7 +10,10 @@ async function handle( try { const request_data = await req.json(); if (request_data?.userName) { - await insertUser({ name: request_data?.name, email: request_data?.name }); + await insertUser({ + name: request_data?.userName, + email: request_data?.userName, + }); } // console.log("===========4", request_data); try { From 013bb7ca01adf78c8d402861a3298b08c29b9703 Mon Sep 17 00:00:00 2001 From: sijinhui Date: Sun, 31 Mar 2024 01:18:47 +0800 Subject: [PATCH 4/4] =?UTF-8?q?=E8=BF=9B=E4=B8=80=E6=AD=A5=E4=BC=98?= =?UTF-8?q?=E5=8C=96=E8=AE=A4=E8=AF=81=E6=B5=81=E7=A8=8B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/api/common.ts | 9 +++++---- app/api/logs/[...path]/route.ts | 13 +++++++------ lib/auth.ts | 31 +++++++++++++++++-------------- prisma/schema.prisma | 7 ++++--- 4 files changed, 33 insertions(+), 27 deletions(-) diff --git a/app/api/common.ts b/app/api/common.ts index a50da30e5..6ec3017d5 100644 --- a/app/api/common.ts +++ b/app/api/common.ts @@ -159,21 +159,22 @@ export async function requestLog( } const baseUrl = "http://localhost:3000"; const ip = getIP(req); - let h_userName = await getSessionName(); - console.log("[中文]", h_userName, baseUrl); + + let { session, name } = await getSessionName(); + console.log("[中文]", name, session, baseUrl); const logData = { ip: ip, path: url_path, logEntry: JSON.stringify(jsonBody), model: url_path.startsWith("mj/") ? "midjourney" : jsonBody?.model, // 后面尝试请求是添加到参数 - userName: h_userName, + userName: name, + userID: session?.user?.id, }; await fetch(`${baseUrl}/api/logs/openai`, { method: "POST", headers: { "Content-Type": "application/json", - // ...req.headers, }, body: JSON.stringify(logData), }); diff --git a/app/api/logs/[...path]/route.ts b/app/api/logs/[...path]/route.ts index aad4ad087..28b0b3fde 100644 --- a/app/api/logs/[...path]/route.ts +++ b/app/api/logs/[...path]/route.ts @@ -9,12 +9,13 @@ async function handle( ) { try { const request_data = await req.json(); - if (request_data?.userName) { - await insertUser({ - name: request_data?.userName, - email: request_data?.userName, - }); - } + console.log("log", request_data); + // if (request_data?.userName) { + // await insertUser({ + // name: request_data?.userName, + // email: request_data?.userName, + // }); + // } // console.log("===========4", request_data); try { if (request_data?.logEntry) { diff --git a/lib/auth.ts b/lib/auth.ts index 0388479d5..4f27aa9b3 100644 --- a/lib/auth.ts +++ b/lib/auth.ts @@ -82,15 +82,13 @@ export const authOptions: NextAuthOptions = { // 判断姓名格式是否符合要求,不符合则拒绝 if (username && isName(username)) { // Any object returned will be saved in `user` property of the JWT - let user:{[key: string]: string} = { - name: username, - // email: null - } + let user:{[key: string]: string} = {} if (isEmail(username)) { - user['email'] = username; + user['email'] = username; + } else { + user['name'] = username; } - await insertUser(user); - return user + return await insertUser(user) ?? user } else { // If you return null then an error will be displayed advising the user to check their details. // return null @@ -125,7 +123,7 @@ export const authOptions: NextAuthOptions = { callbacks: { jwt: async ({ token, user }) => { // const current_time = Math.floor(Date.now() / 1000); - // console.log('=============', token, user, current_time) + console.log('=============', token, user,) if (user) { token.user = user; } @@ -139,6 +137,7 @@ export const authOptions: NextAuthOptions = { // @ts-expect-error username: token?.user?.username || token?.user?.gh_username, }; + console.log('555555555,', session, token) return session; }, }, @@ -159,8 +158,11 @@ export function getSession() { export async function getSessionName() { const session = await getSession(); - // console.log('in........',) - return session?.user?.email || session?.user?.name + console.log('in........', session) + return { + name: session?.user?.email || session?.user?.name, + session + } } // export function withSiteAuth(action: any) { @@ -232,21 +234,22 @@ export async function insertUser(user: {[key: string]: string}) { } const existingUser = conditions.length? await prisma.user.findFirst({ where: { - OR: conditions, + AND: conditions, }, }) : null; // console.log('[LOG]', existingUser, user, '=======') if (!existingUser) { - const newUser = await prisma.user.create({ + return await prisma.user.create({ data: user }) - // console.log('[LOG]', user, '=======') + } else { + console.log('user==========', existingUser) + return existingUser; } } catch (e) { console.log('[Prisma Error]', e); return false; } - return true; } diff --git a/prisma/schema.prisma b/prisma/schema.prisma index 022d20013..741ac3512 100644 --- a/prisma/schema.prisma +++ b/prisma/schema.prisma @@ -16,8 +16,8 @@ model User { id String @id @default(cuid()) name String? @unique // if you are using Github OAuth, you can get rid of the username attribute (that is for Twitter OAuth) - username String? - gh_username String? + username String? @unique + gh_username String? @unique email String? @unique emailVerified DateTime? image String? @@ -70,10 +70,11 @@ model LogEntry { path String? @db.Text model String? @db.VarChar(25) userName String? @db.VarChar(50) + userID String? createdAt DateTime @default(now()) // logEntry String? @db.Text logToken Int? @default(0) - user User? @relation(fields: [userName], references: [name], onDelete: NoAction) + user User? @relation(fields: [userID], references: [id], onDelete: NoAction) } model VerificationToken {