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