You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.
// 导入 User 模型,用于操作 users 表数据
const User = require ( '../models/User' ) ;
const { generateToken } = require ( '../utils/jwt' ) ;
// 核心:登录接口逻辑
const login = async ( req , res ) => {
try {
// 1. 检查请求体是否存在
if ( ! req . body ) {
return res . status ( 400 ) . json ( {
code : 400 ,
msg : '用户名或密码不能为空'
} ) ;
}
// 2. 从前端请求体中获取登录参数(用户名、密码)
const { username , password } = req . body ;
// 3. 验证参数是否完整(基础校验,避免空值请求)
if ( ! username || ! password ) {
return res . status ( 400 ) . json ( {
code : 400 ,
msg : '用户名和密码不能为空'
} ) ;
}
// 3. 从数据库中查询该用户名对应的用户( Sequelize 方法,无需手写 SQL)
const user = await User . findOne ( {
where : { username : username } // 条件:用户名匹配
} ) ;
// 4. 判断用户是否存在及密码是否正确(统一提示,提高安全性)
if ( ! user || user . password !== password ) {
return res . status ( 401 ) . json ( {
code : 401 ,
msg : '用户名或密码不正确'
} ) ;
}
// 6. 生成JWT Token
const token = generateToken ( {
id : user . id ,
username : user . username
} ) ;
// 7. 登录成功: 返回用户信息和token( 隐藏密码, 避免泄露)
const { password : _ , ... userInfo } = user . dataValues ; // 解构删除密码字段
return res . status ( 200 ) . json ( {
code : 200 ,
msg : '登录成功' ,
data : {
user : userInfo , // 返回用户ID、用户名、邮箱等安全信息
token : token , // 返回生成的JWT token
tokenType : 'Bearer'
}
} ) ;
} catch ( error ) {
// 7. 捕获异常(如数据库错误)
return res . status ( 500 ) . json ( {
code : 500 ,
msg : '登录失败,服务器异常' ,
error : error . message
} ) ;
}
} ;
// 导出登录方法,供路由调用
module . exports = { login } ;