This commit is contained in:
sijinhui
2024-04-18 10:04:10 +08:00
parent 9ed72b8f47
commit 714ad21b74
3 changed files with 101 additions and 74 deletions

View File

@@ -7,7 +7,7 @@ import prisma from "@/lib/prisma";
import { User } from "@prisma/client";
import {ADMIN_LIST, isEmail, isName} from "@/lib/auth_list";
import {createTransport} from "nodemailer";
import { comparePassword, hashPassword } from "@/lib/utils";
const SECURE_COOKIES:boolean = !!process.env.SECURE_COOKIES;
@@ -73,13 +73,14 @@ export const authOptions: NextAuthOptions = {
// You can pass any HTML attribute to the <input> tag through the object.
credentials: {
username: { label: "Username", type: "text", placeholder: "输入姓名或邮箱" },
// password: { label: "Password", type: "password" }
password: { label: "Password", type: "password", placeholder: "密码验证,测试阶段" }
},
// @ts-ignore
async authorize(credential, req) {
const username = cleanUpString(`${credential?.username}`);
const password = cleanPassword(`${credential?.password}`);
// 验证用户名
// console.log(credential, username, '==============3')
console.log(credential, 'p', password, '==============3')
// 判断姓名格式是否符合要求,不符合则拒绝
if (username && isName(username)) {
// Any object returned will be saved in `user` property of the JWT
@@ -89,6 +90,12 @@ export const authOptions: NextAuthOptions = {
} else {
user['name'] = username;
}
if (password) {
user['password'] = password;
// 如果有密码,则启用密码验证,查询数据库,否则失败
return await validatePassword(user);
}
return await insertUser(user) ?? user
} else {
// If you return null then an error will be displayed advising the user to check their details.
@@ -183,76 +190,37 @@ export async function VerifiedAdminUser() {
return !!(name && ADMIN_LIST.includes(name));
}
// export function withSiteAuth(action: any) {
// return async (
// formData: FormData | null,
// siteId: string,
// key: string | null,
// ) => {
// const session = await getSession();
// if (!session) {
// return {
// error: "Not authenticated",
// };
// }
// const site = await prisma.site.findUnique({
// where: {
// id: siteId,
// },
// });
// if (!site || site.userId !== session.user.id) {
// return {
// error: "Not authorized",
// };
// }
//
// return action(formData, site, key);
// };
// }
//
// export function withPostAuth(action: any) {
// return async (
// formData: FormData | null,
// postId: string,
// key: string | null,
// ) => {
// const session = await getSession();
// if (!session?.user.id) {
// return {
// error: "Not authenticated",
// };
// }
// const post = await prisma.post.findUnique({
// where: {
// id: postId,
// },
// include: {
// site: true,
// },
// });
// if (!post || post.userId !== session.user.id) {
// return {
// error: "Post not found",
// };
// }
//
// return action(formData, post, key);
// };
// }
export async function validatePassword(user: {[key: string]: string}): Promise<User | void> {
const existingUser = await existUser(user);
console.log('------', 'existUser', existUser)
if (!existingUser) {
throw new Error("用户名或密码不正确");
}
if (existingUser.password == null) {
throw new Error("未设置密码");
}
if (!comparePassword(user.passowrd, existingUser.password)) {
throw new Error("用户名或密码不正确")
} else {
return existingUser;
}
}
async function existUser(user: {[key: string]: string} | User ) {
const conditions = [];
if (user?.name) {
conditions.push({ name: user.name });
}
if (user?.email) {
conditions.push({ email: user.email });
}
return conditions.length ? await prisma.user.findFirst({
where: {
AND: conditions,
},
}) : null
const conditions = [];
if (user?.name) {
conditions.push({ name: user.name });
}
if (user?.email) {
conditions.push({ email: user.email });
}
return conditions.length ? await prisma.user.findFirst({
where: {
AND: conditions,
},
}) : null
}
export async function insertUser(user: {[key: string]: string}) {
@@ -287,6 +255,15 @@ function cleanUpString(input: string): string {
}
}
function cleanPassword(input: string): string {
try {
// 去除前后空格
return input.trim()
}
catch {
return '';
}
}