auth.js 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193
  1. "use strict";
  2. var __importDefault = (this && this.__importDefault) || function (mod) {
  3. return (mod && mod.__esModule) ? mod : { "default": mod };
  4. };
  5. Object.defineProperty(exports, "__esModule", { value: true });
  6. exports.requireAdmin = exports.authorizeRole = exports.authenticateToken = void 0;
  7. const jsonwebtoken_1 = __importDefault(require("jsonwebtoken"));
  8. const errorHandler_1 = require("./errorHandler");
  9. const loggerService_1 = require("../services/loggerService");
  10. const authenticateToken = (req, res, next) => {
  11. try {
  12. const authHeader = req.headers['authorization'];
  13. const token = authHeader && authHeader.split(' ')[1];
  14. if (!token) {
  15. loggerService_1.LoggerService.warn('认证失败:未提供认证令牌', {
  16. source: 'auth',
  17. module: 'authenticate_token',
  18. details: JSON.stringify({
  19. path: req.path,
  20. method: req.method,
  21. ip: req.ip,
  22. userAgent: req.get('user-agent')
  23. })
  24. }).catch(err => {
  25. console.error('认证失败日志写入失败:', err);
  26. });
  27. throw new errorHandler_1.AppError('未提供认证令牌', 401);
  28. }
  29. if (token.startsWith('mock_token_')) {
  30. const parts = token.split('_');
  31. if (parts.length < 3) {
  32. loggerService_1.LoggerService.warn('认证失败:无效的认证令牌', {
  33. source: 'auth',
  34. module: 'authenticate_token',
  35. details: JSON.stringify({
  36. tokenType: 'mock',
  37. path: req.path,
  38. method: req.method,
  39. ip: req.ip
  40. })
  41. }).catch(err => {
  42. console.error('认证失败日志写入失败:', err);
  43. });
  44. throw new errorHandler_1.AppError('无效的认证令牌', 401);
  45. }
  46. const userId = parts[2];
  47. const UserModel = require('../models/user').UserModel;
  48. UserModel.getById(userId).then((user) => {
  49. if (!user) {
  50. loggerService_1.LoggerService.warn('认证失败:用户不存在', {
  51. source: 'auth',
  52. module: 'authenticate_token',
  53. details: JSON.stringify({
  54. userId,
  55. tokenType: 'mock',
  56. path: req.path,
  57. method: req.method,
  58. ip: req.ip
  59. })
  60. }).catch(err => {
  61. console.error('认证失败日志写入失败:', err);
  62. });
  63. throw new errorHandler_1.AppError('用户不存在', 401);
  64. }
  65. req.user = {
  66. id: user.id,
  67. username: user.username,
  68. role: user.role
  69. };
  70. loggerService_1.LoggerService.info('认证成功', {
  71. source: 'auth',
  72. module: 'authenticate_token',
  73. details: JSON.stringify({
  74. userId: user.id,
  75. username: user.username,
  76. role: user.role,
  77. tokenType: 'mock',
  78. path: req.path,
  79. method: req.method,
  80. ip: req.ip
  81. })
  82. }).catch(err => {
  83. console.error('认证成功日志写入失败:', err);
  84. });
  85. next();
  86. }).catch((error) => {
  87. next(error);
  88. });
  89. }
  90. else {
  91. const decoded = jsonwebtoken_1.default.verify(token, process.env.JWT_SECRET);
  92. req.user = decoded;
  93. loggerService_1.LoggerService.info('认证成功', {
  94. source: 'auth',
  95. module: 'authenticate_token',
  96. details: JSON.stringify({
  97. userId: decoded.id,
  98. username: decoded.username,
  99. role: decoded.role,
  100. tokenType: 'jwt',
  101. path: req.path,
  102. method: req.method,
  103. ip: req.ip
  104. })
  105. }).catch(err => {
  106. console.error('认证成功日志写入失败:', err);
  107. });
  108. next();
  109. }
  110. }
  111. catch (error) {
  112. if (error instanceof jsonwebtoken_1.default.JsonWebTokenError) {
  113. loggerService_1.LoggerService.warn('认证失败:无效的认证令牌', {
  114. source: 'auth',
  115. module: 'authenticate_token',
  116. details: JSON.stringify({
  117. tokenType: 'jwt',
  118. error: error.message,
  119. path: req.path,
  120. method: req.method,
  121. ip: req.ip
  122. })
  123. }).catch((err) => {
  124. console.error('认证失败日志写入失败:', err);
  125. });
  126. next(new errorHandler_1.AppError('无效的认证令牌', 401));
  127. }
  128. else if (error instanceof jsonwebtoken_1.default.TokenExpiredError) {
  129. loggerService_1.LoggerService.warn('认证失败:认证令牌已过期', {
  130. source: 'auth',
  131. module: 'authenticate_token',
  132. details: JSON.stringify({
  133. tokenType: 'jwt',
  134. expiredAt: error.expiredAt,
  135. path: req.path,
  136. method: req.method,
  137. ip: req.ip
  138. })
  139. }).catch((err) => {
  140. console.error('认证失败日志写入失败:', err);
  141. });
  142. next(new errorHandler_1.AppError('认证令牌已过期', 401));
  143. }
  144. else if (error instanceof Error) {
  145. next(error);
  146. }
  147. else {
  148. next(new errorHandler_1.AppError('认证失败', 401));
  149. }
  150. }
  151. };
  152. exports.authenticateToken = authenticateToken;
  153. const authorizeRole = (roles) => {
  154. return (req, res, next) => {
  155. if (!req.user || !req.user.role || !roles.includes(req.user.role)) {
  156. loggerService_1.LoggerService.warn('授权失败:没有权限执行此操作', {
  157. source: 'auth',
  158. module: 'authorize_role',
  159. details: JSON.stringify({
  160. userRole: req.user?.role,
  161. requiredRoles: roles,
  162. path: req.path,
  163. method: req.method,
  164. userId: req.user?.id,
  165. username: req.user?.username,
  166. ip: req.ip
  167. })
  168. }).catch(err => {
  169. console.error('授权失败日志写入失败:', err);
  170. });
  171. throw new errorHandler_1.AppError('没有权限执行此操作', 403);
  172. }
  173. loggerService_1.LoggerService.info('授权成功', {
  174. source: 'auth',
  175. module: 'authorize_role',
  176. details: JSON.stringify({
  177. userRole: req.user.role,
  178. requiredRoles: roles,
  179. path: req.path,
  180. method: req.method,
  181. userId: req.user.id,
  182. username: req.user.username,
  183. ip: req.ip
  184. })
  185. }).catch(err => {
  186. console.error('授权成功日志写入失败:', err);
  187. });
  188. next();
  189. };
  190. };
  191. exports.authorizeRole = authorizeRole;
  192. exports.requireAdmin = (0, exports.authorizeRole)(['admin']);
  193. //# sourceMappingURL=auth.js.map