Merge remote-tracking branch 'origin/main'
This commit is contained in:
@@ -7,25 +7,101 @@ const router = express.Router()
|
||||
// 引入数据库模型
|
||||
const { ApiUser } = require('../models')
|
||||
|
||||
// 登录参数验证
|
||||
// 引入认证中间件
|
||||
const { authenticateJWT } = require('../middleware/auth')
|
||||
|
||||
/**
|
||||
* @swagger
|
||||
* components:
|
||||
* schemas:
|
||||
* LoginRequest:
|
||||
* type: object
|
||||
* required:
|
||||
* - username
|
||||
* - password
|
||||
* properties:
|
||||
* username:
|
||||
* type: string
|
||||
* description: 用户名
|
||||
* password:
|
||||
* type: string
|
||||
* description: 密码
|
||||
* LoginResponse:
|
||||
* type: object
|
||||
* properties:
|
||||
* success:
|
||||
* type: boolean
|
||||
* message:
|
||||
* type: string
|
||||
* token:
|
||||
* type: string
|
||||
* user:
|
||||
* type: object
|
||||
* properties:
|
||||
* id:
|
||||
* type: integer
|
||||
* username:
|
||||
* type: string
|
||||
* email:
|
||||
* type: string
|
||||
* user_type:
|
||||
* type: string
|
||||
* status:
|
||||
* type: string
|
||||
*/
|
||||
|
||||
// 从环境变量或配置中获取JWT密钥
|
||||
const JWT_SECRET = process.env.JWT_SECRET || 'your_jwt_secret_key'
|
||||
const JWT_EXPIRES_IN = process.env.JWT_EXPIRES_IN || '24h'
|
||||
|
||||
// 验证模式
|
||||
const loginSchema = Joi.object({
|
||||
username: Joi.string().min(2).max(50).required(),
|
||||
password: Joi.string().min(6).max(100).required()
|
||||
username: Joi.string().required(),
|
||||
password: Joi.string().required()
|
||||
})
|
||||
|
||||
// 生成JWT token
|
||||
// 生成JWT令牌
|
||||
const generateToken = (user) => {
|
||||
return jwt.sign(
|
||||
{
|
||||
id: user.id,
|
||||
username: user.username,
|
||||
role: user.user_type
|
||||
email: user.email,
|
||||
user_type: user.user_type
|
||||
},
|
||||
process.env.JWT_SECRET || 'niumall-secret-key',
|
||||
{ expiresIn: process.env.JWT_EXPIRES_IN || '24h' }
|
||||
JWT_SECRET,
|
||||
{
|
||||
expiresIn: JWT_EXPIRES_IN
|
||||
}
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* @swagger
|
||||
* /api/auth/login:
|
||||
* post:
|
||||
* summary: 用户登录
|
||||
* tags: [认证管理]
|
||||
* requestBody:
|
||||
* required: true
|
||||
* content:
|
||||
* application/json:
|
||||
* schema:
|
||||
* $ref: '#/components/schemas/LoginRequest'
|
||||
* responses:
|
||||
* 200:
|
||||
* description: 登录成功
|
||||
* content:
|
||||
* application/json:
|
||||
* schema:
|
||||
* $ref: '#/components/schemas/LoginResponse'
|
||||
* 400:
|
||||
* description: 参数验证失败或用户名密码错误
|
||||
* 401:
|
||||
* description: 未授权或用户被禁用
|
||||
* 500:
|
||||
* description: 服务器内部错误
|
||||
*/
|
||||
// 用户登录
|
||||
router.post('/login', async (req, res) => {
|
||||
try {
|
||||
@@ -38,94 +114,126 @@ router.post('/login', async (req, res) => {
|
||||
details: error.details[0].message
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
const { username, password } = value
|
||||
|
||||
|
||||
// 查找用户
|
||||
const user = await ApiUser.findOne({
|
||||
where: {
|
||||
[require('sequelize').Op.or]: [
|
||||
{ username: username },
|
||||
{ phone: username },
|
||||
[ApiUser.sequelize.Op.or]: [
|
||||
{ username },
|
||||
{ email: username }
|
||||
]
|
||||
}
|
||||
});
|
||||
})
|
||||
|
||||
if (!user) {
|
||||
// 检查用户是否存在以及密码是否正确
|
||||
if (!user || !(await bcrypt.compare(password, user.password_hash))) {
|
||||
return res.status(401).json({
|
||||
success: false,
|
||||
message: '用户名或密码错误'
|
||||
})
|
||||
}
|
||||
|
||||
// 验证密码
|
||||
const isPasswordValid = await bcrypt.compare(password, user.password_hash)
|
||||
if (!isPasswordValid) {
|
||||
return res.status(401).json({
|
||||
success: false,
|
||||
message: '用户名或密码错误'
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
// 检查用户状态
|
||||
if (user.status !== 'active') {
|
||||
return res.status(403).json({
|
||||
return res.status(401).json({
|
||||
success: false,
|
||||
message: '账户已被禁用,请联系管理员'
|
||||
message: '用户账号已被禁用'
|
||||
})
|
||||
}
|
||||
|
||||
// 生成token
|
||||
|
||||
// 生成JWT令牌
|
||||
const token = generateToken(user)
|
||||
|
||||
|
||||
// 准备返回的用户信息(不包含敏感数据)
|
||||
const userInfo = {
|
||||
id: user.id,
|
||||
username: user.username,
|
||||
email: user.email,
|
||||
user_type: user.user_type,
|
||||
status: user.status
|
||||
}
|
||||
|
||||
res.json({
|
||||
success: true,
|
||||
message: '登录成功',
|
||||
data: {
|
||||
access_token: token,
|
||||
token_type: 'Bearer',
|
||||
expires_in: 86400, // 24小时
|
||||
user: {
|
||||
id: user.id,
|
||||
username: user.username,
|
||||
email: user.email,
|
||||
role: user.user_type,
|
||||
status: user.status
|
||||
}
|
||||
}
|
||||
token,
|
||||
user: userInfo
|
||||
})
|
||||
} catch (error) {
|
||||
console.error('登录失败:', error)
|
||||
console.error('用户登录失败:', error)
|
||||
res.status(500).json({
|
||||
success: false,
|
||||
message: '登录失败,请稍后重试'
|
||||
message: '登录失败,请稍后再试'
|
||||
})
|
||||
}
|
||||
})
|
||||
|
||||
/**
|
||||
* @swagger
|
||||
* /api/auth/me:
|
||||
* get:
|
||||
* summary: 获取当前用户信息
|
||||
* tags: [认证管理]
|
||||
* security:
|
||||
* - bearerAuth: []
|
||||
* responses:
|
||||
* 200:
|
||||
* description: 获取成功
|
||||
* content:
|
||||
* application/json:
|
||||
* schema:
|
||||
* type: object
|
||||
* properties:
|
||||
* success:
|
||||
* type: boolean
|
||||
* data:
|
||||
* type: object
|
||||
* properties:
|
||||
* id:
|
||||
* type: integer
|
||||
* username:
|
||||
* type: string
|
||||
* email:
|
||||
* type: string
|
||||
* user_type:
|
||||
* type: string
|
||||
* status:
|
||||
* type: string
|
||||
* createdAt:
|
||||
* type: string
|
||||
* format: date-time
|
||||
* updatedAt:
|
||||
* type: string
|
||||
* format: date-time
|
||||
* 401:
|
||||
* description: 未授权
|
||||
* 500:
|
||||
* description: 服务器内部错误
|
||||
*/
|
||||
// 获取当前用户信息
|
||||
router.get('/me', authenticateToken, async (req, res) => {
|
||||
router.get('/me', authenticateJWT, async (req, res) => {
|
||||
try {
|
||||
const user = await ApiUser.findByPk(req.user.id)
|
||||
const userId = req.user.id
|
||||
|
||||
// 根据ID查找用户
|
||||
const user = await ApiUser.findByPk(userId, {
|
||||
attributes: {
|
||||
exclude: ['password_hash'] // 排除密码哈希等敏感信息
|
||||
}
|
||||
})
|
||||
|
||||
if (!user) {
|
||||
return res.status(404).json({
|
||||
success: false,
|
||||
message: '用户不存在'
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
res.json({
|
||||
success: true,
|
||||
data: {
|
||||
user: {
|
||||
id: user.id,
|
||||
username: user.username,
|
||||
email: user.email,
|
||||
role: user.user_type,
|
||||
status: user.status
|
||||
}
|
||||
}
|
||||
data: user
|
||||
})
|
||||
} catch (error) {
|
||||
console.error('获取用户信息失败:', error)
|
||||
@@ -136,37 +244,49 @@ router.get('/me', authenticateToken, async (req, res) => {
|
||||
}
|
||||
})
|
||||
|
||||
/**
|
||||
* @swagger
|
||||
* /api/auth/logout:
|
||||
* post:
|
||||
* summary: 用户登出
|
||||
* tags: [认证管理]
|
||||
* security:
|
||||
* - bearerAuth: []
|
||||
* responses:
|
||||
* 200:
|
||||
* description: 登出成功
|
||||
* content:
|
||||
* application/json:
|
||||
* schema:
|
||||
* type: object
|
||||
* properties:
|
||||
* success:
|
||||
* type: boolean
|
||||
* message:
|
||||
* type: string
|
||||
* 401:
|
||||
* description: 未授权
|
||||
* 500:
|
||||
* description: 服务器内部错误
|
||||
*/
|
||||
// 用户登出
|
||||
router.post('/logout', authenticateToken, (req, res) => {
|
||||
// 在实际项目中,可以将token加入黑名单
|
||||
res.json({
|
||||
success: true,
|
||||
message: '登出成功'
|
||||
})
|
||||
})
|
||||
|
||||
// JWT token验证中间件
|
||||
function authenticateToken(req, res, next) {
|
||||
const authHeader = req.headers['authorization']
|
||||
const token = authHeader && authHeader.split(' ')[1]
|
||||
|
||||
if (!token) {
|
||||
return res.status(401).json({
|
||||
router.post('/logout', authenticateJWT, async (req, res) => {
|
||||
try {
|
||||
// 注意:JWT是无状态的,服务器端无法直接使token失效
|
||||
// 登出操作主要由客户端完成,如删除本地存储的token
|
||||
// 这里只返回成功信息
|
||||
|
||||
res.json({
|
||||
success: true,
|
||||
message: '登出成功'
|
||||
})
|
||||
} catch (error) {
|
||||
console.error('用户登出失败:', error)
|
||||
res.status(500).json({
|
||||
success: false,
|
||||
message: '访问令牌缺失'
|
||||
message: '登出失败,请稍后再试'
|
||||
})
|
||||
}
|
||||
|
||||
jwt.verify(token, process.env.JWT_SECRET || 'niumall-secret-key', (err, user) => {
|
||||
if (err) {
|
||||
return res.status(403).json({
|
||||
success: false,
|
||||
message: '访问令牌无效或已过期'
|
||||
})
|
||||
}
|
||||
req.user = user
|
||||
next()
|
||||
})
|
||||
}
|
||||
})
|
||||
|
||||
module.exports = router
|
||||
Reference in New Issue
Block a user