From bd2868276993062c64f06e33a9009fb6a77de160 Mon Sep 17 00:00:00 2001 From: whyour Date: Tue, 6 Sep 2022 23:57:21 +0800 Subject: [PATCH] =?UTF-8?q?=E6=8E=92=E9=99=A4=E8=AE=A4=E8=AF=81=E5=A4=B1?= =?UTF-8?q?=E8=B4=A5=E9=94=99=E8=AF=AF=E4=B8=8A=E6=8A=A5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- back/loaders/express.ts | 26 +++++++++++++++++++------- 1 file changed, 19 insertions(+), 7 deletions(-) diff --git a/back/loaders/express.ts b/back/loaders/express.ts index 3402799d..a514eb31 100644 --- a/back/loaders/express.ts +++ b/back/loaders/express.ts @@ -3,7 +3,7 @@ import bodyParser from 'body-parser'; import cors from 'cors'; import routes from '../api'; import config from '../config'; -import jwt from 'express-jwt'; +import jwt, { UnauthorizedError } from 'express-jwt'; import fs from 'fs'; import { getPlatform, getToken } from '../config/util'; import Container from 'typedi'; @@ -75,22 +75,24 @@ export default ({ app }: { app: Application }) => { if ( !headerToken && originPath && - config.apiWhiteList.includes(originPath) && - originPath !== '/api/crons/status' + config.apiWhiteList.includes(originPath) ) { return next(); } const data = fs.readFileSync(config.authConfigFile, 'utf8'); - if (data) { + if (data && headerToken) { const { token = '', tokens = {} } = JSON.parse(data); if (headerToken === token || tokens[req.platform] === headerToken) { return next(); } } - const err: any = new Error('UnauthorizedError'); - err.status = 401; + const errorCode = headerToken ? 'invalid_token' : 'credentials_required'; + const errorMessage = headerToken + ? 'jwt malformed' + : 'No authorization token was found'; + const err = new UnauthorizedError(errorCode, { message: errorMessage }); next(err); }); @@ -168,7 +170,17 @@ export default ({ app }: { app: Application }) => { }, ); - app.use(Sentry.Handlers.errorHandler()); + app.use( + Sentry.Handlers.errorHandler({ + shouldHandleError(error) { + // 排除 SequelizeUniqueConstraintError / NotFound + return ( + !['SequelizeUniqueConstraintError'].includes(error.name) || + !['Not Found'].includes(error.message) + ); + }, + }), + ); app.use( (