进一步优化认证流程

This commit is contained in:
sijinhui 2024-03-31 01:18:47 +08:00
parent cea656ec9a
commit 013bb7ca01
4 changed files with 33 additions and 27 deletions

View File

@ -159,21 +159,22 @@ export async function requestLog(
} }
const baseUrl = "http://localhost:3000"; const baseUrl = "http://localhost:3000";
const ip = getIP(req); 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 = { const logData = {
ip: ip, ip: ip,
path: url_path, path: url_path,
logEntry: JSON.stringify(jsonBody), logEntry: JSON.stringify(jsonBody),
model: url_path.startsWith("mj/") ? "midjourney" : jsonBody?.model, // 后面尝试请求是添加到参数 model: url_path.startsWith("mj/") ? "midjourney" : jsonBody?.model, // 后面尝试请求是添加到参数
userName: h_userName, userName: name,
userID: session?.user?.id,
}; };
await fetch(`${baseUrl}/api/logs/openai`, { await fetch(`${baseUrl}/api/logs/openai`, {
method: "POST", method: "POST",
headers: { headers: {
"Content-Type": "application/json", "Content-Type": "application/json",
// ...req.headers,
}, },
body: JSON.stringify(logData), body: JSON.stringify(logData),
}); });

View File

@ -9,12 +9,13 @@ async function handle(
) { ) {
try { try {
const request_data = await req.json(); const request_data = await req.json();
if (request_data?.userName) { console.log("log", request_data);
await insertUser({ // if (request_data?.userName) {
name: request_data?.userName, // await insertUser({
email: request_data?.userName, // name: request_data?.userName,
}); // email: request_data?.userName,
} // });
// }
// console.log("===========4", request_data); // console.log("===========4", request_data);
try { try {
if (request_data?.logEntry) { if (request_data?.logEntry) {

View File

@ -82,15 +82,13 @@ export const authOptions: NextAuthOptions = {
// 判断姓名格式是否符合要求,不符合则拒绝 // 判断姓名格式是否符合要求,不符合则拒绝
if (username && isName(username)) { if (username && isName(username)) {
// Any object returned will be saved in `user` property of the JWT // Any object returned will be saved in `user` property of the JWT
let user:{[key: string]: string} = { let user:{[key: string]: string} = {}
name: username,
// email: null
}
if (isEmail(username)) { if (isEmail(username)) {
user['email'] = username; user['email'] = username;
} else {
user['name'] = username;
} }
await insertUser(user); return await insertUser(user) ?? user
return user
} else { } else {
// If you return null then an error will be displayed advising the user to check their details. // If you return null then an error will be displayed advising the user to check their details.
// return null // return null
@ -125,7 +123,7 @@ export const authOptions: NextAuthOptions = {
callbacks: { callbacks: {
jwt: async ({ token, user }) => { jwt: async ({ token, user }) => {
// const current_time = Math.floor(Date.now() / 1000); // const current_time = Math.floor(Date.now() / 1000);
// console.log('=============', token, user, current_time) console.log('=============', token, user,)
if (user) { if (user) {
token.user = user; token.user = user;
} }
@ -139,6 +137,7 @@ export const authOptions: NextAuthOptions = {
// @ts-expect-error // @ts-expect-error
username: token?.user?.username || token?.user?.gh_username, username: token?.user?.username || token?.user?.gh_username,
}; };
console.log('555555555,', session, token)
return session; return session;
}, },
}, },
@ -159,8 +158,11 @@ export function getSession() {
export async function getSessionName() { export async function getSessionName() {
const session = await getSession(); const session = await getSession();
// console.log('in........',) console.log('in........', session)
return session?.user?.email || session?.user?.name return {
name: session?.user?.email || session?.user?.name,
session
}
} }
// export function withSiteAuth(action: any) { // 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({ const existingUser = conditions.length? await prisma.user.findFirst({
where: { where: {
OR: conditions, AND: conditions,
}, },
}) : null; }) : null;
// console.log('[LOG]', existingUser, user, '=======') // console.log('[LOG]', existingUser, user, '=======')
if (!existingUser) { if (!existingUser) {
const newUser = await prisma.user.create({ return await prisma.user.create({
data: user data: user
}) })
// console.log('[LOG]', user, '=======') } else {
console.log('user==========', existingUser)
return existingUser;
} }
} catch (e) { } catch (e) {
console.log('[Prisma Error]', e); console.log('[Prisma Error]', e);
return false; return false;
} }
return true;
} }

View File

@ -16,8 +16,8 @@ model User {
id String @id @default(cuid()) id String @id @default(cuid())
name String? @unique name String? @unique
// if you are using Github OAuth, you can get rid of the username attribute (that is for Twitter OAuth) // if you are using Github OAuth, you can get rid of the username attribute (that is for Twitter OAuth)
username String? username String? @unique
gh_username String? gh_username String? @unique
email String? @unique email String? @unique
emailVerified DateTime? emailVerified DateTime?
image String? image String?
@ -70,10 +70,11 @@ model LogEntry {
path String? @db.Text path String? @db.Text
model String? @db.VarChar(25) model String? @db.VarChar(25)
userName String? @db.VarChar(50) userName String? @db.VarChar(50)
userID String?
createdAt DateTime @default(now()) createdAt DateTime @default(now())
// logEntry String? @db.Text // logEntry String? @db.Text
logToken Int? @default(0) logToken Int? @default(0)
user User? @relation(fields: [userName], references: [name], onDelete: NoAction) user User? @relation(fields: [userID], references: [id], onDelete: NoAction)
} }
model VerificationToken { model VerificationToken {