From ac53c3c6cf95a4d45e61e71fcbe42264c4e7b2e2 Mon Sep 17 00:00:00 2001 From: Astrian Zheng Date: Sun, 12 Jan 2025 11:33:20 +1100 Subject: [PATCH] feat: implement bearer token validation for payer and invoice routes --- backend/src/app.ts | 14 ++++++++++++-- backend/src/func/index.ts | 4 +++- backend/src/func/verifyBearerToken.ts | 6 ++++++ 3 files changed, 21 insertions(+), 3 deletions(-) create mode 100644 backend/src/func/verifyBearerToken.ts diff --git a/backend/src/app.ts b/backend/src/app.ts index 2d7e358..4c8091f 100644 --- a/backend/src/app.ts +++ b/backend/src/app.ts @@ -41,7 +41,12 @@ app.use(route.get('/', (ctx) => { })) app.use(route.post('/payer', async (ctx) => { - // TODO: 请求头验证 bearer token + // 请求头验证 bearer token + const bearerToken = ctx.request.headers['authorization']?.split(' ') + if (!bearerToken) throw new HttpError(ErrorDescEnum.unauthorized, 401) + if (bearerToken[0] !== 'Bearer') throw new HttpError(ErrorDescEnum.unauthorized, 401) + if (!bearerToken[1]) throw new HttpError(ErrorDescEnum.unauthorized, 401) + await func.verifyBearerToken(bearerToken[1]) // 验证必填字段 // 字段缺失时 @@ -75,7 +80,12 @@ app.use(route.post('/payer', async (ctx) => { })) app.use(route.post('/invoice', async (ctx) => { - // TODO: 请求头验证 bearer token + // 请求头验证 bearer token + const bearerToken = ctx.request.headers['authorization']?.split(' ') + if (!bearerToken) throw new HttpError(ErrorDescEnum.unauthorized, 401) + if (bearerToken[0] !== 'Bearer') throw new HttpError(ErrorDescEnum.unauthorized, 401) + if (!bearerToken[1]) throw new HttpError(ErrorDescEnum.unauthorized, 401) + await func.verifyBearerToken(bearerToken[1]) // 提取字段,并验证必填字段 if (!ctx.request.body) throw new HttpError(ErrorDescEnum.required_fields_missing, 400, ['payerId', 'period', 'items', 'dueDate']) diff --git a/backend/src/func/index.ts b/backend/src/func/index.ts index 4054074..4e38775 100644 --- a/backend/src/func/index.ts +++ b/backend/src/func/index.ts @@ -1,7 +1,9 @@ import createPayer from "./createPayer" import issueInvoice from "./issueInvoice" +import verifyBearerToken from "./verifyBearerToken" export default { createPayer, - issueInvoice + issueInvoice, + verifyBearerToken } \ No newline at end of file diff --git a/backend/src/func/verifyBearerToken.ts b/backend/src/func/verifyBearerToken.ts new file mode 100644 index 0000000..23a31f1 --- /dev/null +++ b/backend/src/func/verifyBearerToken.ts @@ -0,0 +1,6 @@ +import { ErrorDescEnum, HttpError } from "../classes/HttpError" + +export default async (token: string) => { + const bearerToken = process.env.BEARER_TOKEN + if (!bearerToken) throw new HttpError(ErrorDescEnum.unauthorized, 401) +} \ No newline at end of file