102 lines
2.5 KiB
TypeScript
102 lines
2.5 KiB
TypeScript
|
|
import { NextApiRequest, NextApiResponse } from 'next';
|
||
|
|
import jwt from 'jsonwebtoken';
|
||
|
|
|
||
|
|
interface LoginRequest {
|
||
|
|
email: string;
|
||
|
|
password: string;
|
||
|
|
}
|
||
|
|
|
||
|
|
// 硬编码的管理员凭据(用于演示)
|
||
|
|
const ADMIN_CREDENTIALS = {
|
||
|
|
email: 'admin@example.com',
|
||
|
|
password: 'admin123',
|
||
|
|
user: {
|
||
|
|
id: 'admin-001',
|
||
|
|
email: 'admin@example.com',
|
||
|
|
name: '系统管理员',
|
||
|
|
userType: 'admin',
|
||
|
|
phone: '13800138000',
|
||
|
|
avatarUrl: null
|
||
|
|
}
|
||
|
|
};
|
||
|
|
|
||
|
|
export default async function handler(
|
||
|
|
req: NextApiRequest,
|
||
|
|
res: NextApiResponse
|
||
|
|
) {
|
||
|
|
if (req.method !== 'POST') {
|
||
|
|
return res.status(405).json({ success: false, error: '方法不允许' });
|
||
|
|
}
|
||
|
|
|
||
|
|
try {
|
||
|
|
const { email, password }: LoginRequest = req.body;
|
||
|
|
|
||
|
|
console.log('收到登录请求:', { email, password: '***' });
|
||
|
|
|
||
|
|
// 验证必填字段
|
||
|
|
if (!email || !password) {
|
||
|
|
console.log('缺少必填字段');
|
||
|
|
return res.status(400).json({
|
||
|
|
success: false,
|
||
|
|
error: '邮箱和密码不能为空'
|
||
|
|
});
|
||
|
|
}
|
||
|
|
|
||
|
|
// 验证邮箱格式
|
||
|
|
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
|
||
|
|
if (!emailRegex.test(email)) {
|
||
|
|
console.log('邮箱格式不正确:', email);
|
||
|
|
return res.status(400).json({
|
||
|
|
success: false,
|
||
|
|
error: '邮箱格式不正确'
|
||
|
|
});
|
||
|
|
}
|
||
|
|
|
||
|
|
console.log('验证管理员凭据...');
|
||
|
|
|
||
|
|
// 验证管理员凭据
|
||
|
|
if (email !== ADMIN_CREDENTIALS.email || password !== ADMIN_CREDENTIALS.password) {
|
||
|
|
console.log('管理员凭据不正确');
|
||
|
|
return res.status(401).json({
|
||
|
|
success: false,
|
||
|
|
error: '邮箱或密码错误'
|
||
|
|
});
|
||
|
|
}
|
||
|
|
|
||
|
|
console.log('管理员凭据验证通过');
|
||
|
|
|
||
|
|
// 生成JWT令牌
|
||
|
|
const jwtSecret = process.env.JWT_SECRET || 'your-secret-key';
|
||
|
|
const token = jwt.sign(
|
||
|
|
{
|
||
|
|
userId: ADMIN_CREDENTIALS.user.id,
|
||
|
|
email: ADMIN_CREDENTIALS.user.email,
|
||
|
|
userType: ADMIN_CREDENTIALS.user.userType,
|
||
|
|
name: ADMIN_CREDENTIALS.user.name
|
||
|
|
},
|
||
|
|
jwtSecret,
|
||
|
|
{ expiresIn: '24h' }
|
||
|
|
);
|
||
|
|
|
||
|
|
console.log('JWT令牌生成成功');
|
||
|
|
console.log('登录成功,返回用户信息');
|
||
|
|
|
||
|
|
// 返回成功响应
|
||
|
|
res.status(200).json({
|
||
|
|
success: true,
|
||
|
|
message: '登录成功',
|
||
|
|
user: ADMIN_CREDENTIALS.user,
|
||
|
|
token,
|
||
|
|
expiresIn: '24h'
|
||
|
|
});
|
||
|
|
|
||
|
|
} catch (error) {
|
||
|
|
console.error('登录错误:', error);
|
||
|
|
res.status(500).json({
|
||
|
|
success: false,
|
||
|
|
error: process.env.NODE_ENV === 'development'
|
||
|
|
? `服务器错误: ${error}`
|
||
|
|
: '服务器内部错误'
|
||
|
|
});
|
||
|
|
}
|
||
|
|
}
|