feat: refactor authentication logic for admin and user login, improve error handling

This commit is contained in:
2025-06-18 16:59:36 +08:00
parent 0ca2d51669
commit ad78f713a3
5 changed files with 35 additions and 8219 deletions

View File

@ -1,42 +1,14 @@
import { defineEventHandler, readBody, setResponseStatus } from 'h3';
import { db, customers } from '~/server/db';
import { eq } from 'drizzle-orm';
import bcrypt from 'bcryptjs';
import { defineEventHandler, readBody, createError } from 'h3';
import { userLoginLogic } from './user/_logic';
export default defineEventHandler(async (event) => {
const body = await readBody(event);
const { contact, password } = body;
if (!contact || !password) {
setResponseStatus(event, 400);
return { message: '请填写手机号和密码' };
}
try {
const user = await db.query.customers.findFirst({
where: eq(customers.contact, contact),
const body = await readBody(event);
return await userLoginLogic(body);
} catch (error: any) {
throw createError({
statusCode: error.statusCode || 500,
statusMessage: error.message,
});
if (!user) {
setResponseStatus(event, 401);
return { message: '手机号或密码错误' };
}
const isPasswordValid = bcrypt.compareSync(password, user.password);
if (!isPasswordValid) {
setResponseStatus(event, 401);
return { message: '手机号或密码错误' };
}
return {
message: '登录成功!',
customerId: user.id,
};
} catch (error) {
console.error('Login error:', error);
setResponseStatus(event, 500);
return { message: '登录失败,请稍后重试' };
}
});