/** * 认证路由 * @file auth.js * @description 认证相关的路由定义 */ const express = require('express'); const { body } = require('express-validator'); const authController = require('../controllers/authController'); const { authMiddleware } = require('../middleware/auth'); const router = express.Router(); // 登录验证规则 const loginValidation = [ body('username') .notEmpty() .withMessage('用户名不能为空') .isLength({ min: 3, max: 50 }) .withMessage('用户名长度必须在3-50个字符之间'), body('password') .notEmpty() .withMessage('密码不能为空') .isLength({ min: 6 }) .withMessage('密码长度不能少于6个字符') ]; // 修改密码验证规则 const changePasswordValidation = [ body('oldPassword') .notEmpty() .withMessage('原密码不能为空'), body('newPassword') .notEmpty() .withMessage('新密码不能为空') .isLength({ min: 6 }) .withMessage('新密码长度不能少于6个字符') .matches(/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)/) .withMessage('新密码必须包含大小写字母和数字') ]; /** * @swagger * /api/auth/login: * post: * summary: 用户登录 * tags: [认证] * requestBody: * required: true * content: * application/json: * schema: * type: object * required: * - username * - password * properties: * username: * type: string * description: 用户名 * password: * type: string * description: 密码 * responses: * 200: * description: 登录成功 * content: * application/json: * schema: * type: object * properties: * success: * type: boolean * message: * type: string * data: * type: object * properties: * token: * type: string * user: * type: object * 401: * description: 登录失败 */ router.post('/login', loginValidation, authController.login); /** * @swagger * /api/auth/logout: * post: * summary: 用户登出 * tags: [认证] * security: * - bearerAuth: [] * responses: * 200: * description: 登出成功 */ router.post('/logout', authMiddleware, authController.logout); /** * @swagger * /api/auth/refresh: * post: * summary: 刷新令牌 * tags: [认证] * security: * - bearerAuth: [] * responses: * 200: * description: 令牌刷新成功 * 401: * description: 令牌无效 */ router.post('/refresh', authMiddleware, authController.refreshToken); /** * @swagger * /api/auth/me: * get: * summary: 获取当前用户信息 * tags: [认证] * security: * - bearerAuth: [] * responses: * 200: * description: 获取成功 * 401: * description: 未授权 */ router.get('/me', authMiddleware, authController.getCurrentUser); /** * @swagger * /api/auth/change-password: * post: * summary: 修改密码 * tags: [认证] * security: * - bearerAuth: [] * requestBody: * required: true * content: * application/json: * schema: * type: object * required: * - oldPassword * - newPassword * properties: * oldPassword: * type: string * description: 原密码 * newPassword: * type: string * description: 新密码 * responses: * 200: * description: 密码修改成功 * 400: * description: 请求参数错误 */ router.post('/change-password', authMiddleware, changePasswordValidation, authController.changePassword); module.exports = router;