File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change @@ -5,20 +5,17 @@ import {
55 renderMetrics ,
66} from "../metrics/authMetrics" ;
77import { env } from "../config/env" ;
8-
9- const getBearerToken = ( request : Request ) : string | null => {
10- const authorization = request . header ( "authorization" ) ;
11- const match = authorization ?. match ( / ^ B e a r e r \s + ( .+ ) $ / i) ;
12-
13- return match ?. [ 1 ] ?. trim ( ) || null ;
14- } ;
8+ import { extractBearerToken } from "../utils/bearerToken" ;
159
1610export async function metrics ( req : Request , res : Response ) {
1711 if ( ! metricsEnabled ) {
1812 return res . status ( 404 ) . json ( { message : "metrics disabled" } ) ;
1913 }
2014
21- if ( env . METRICS_AUTH_TOKEN && getBearerToken ( req ) !== env . METRICS_AUTH_TOKEN ) {
15+ if (
16+ env . METRICS_AUTH_TOKEN &&
17+ extractBearerToken ( req . header ( "authorization" ) ) !== env . METRICS_AUTH_TOKEN
18+ ) {
2219 return res . status ( 401 ) . json ( {
2320 error : {
2421 code : "METRICS_AUTHORIZATION_REQUIRED" ,
Original file line number Diff line number Diff line change @@ -3,6 +3,7 @@ import { SessionStatus } from "@prisma/client";
33import AppError from "../errors/AppError" ;
44import tokenService from "../services/tokenService" ;
55import sessionRepository from "../repositories/sessionRepository" ;
6+ import { extractBearerToken } from "../utils/bearerToken" ;
67
78export default async function authMiddleware (
89 req : Request ,
@@ -21,8 +22,7 @@ export default async function authMiddleware(
2122 ) ;
2223 }
2324
24- const match = authorization . match ( / ^ B e a r e r \s + ( .+ ) $ / i) ;
25- const token = match ?. [ 1 ] ;
25+ const token = extractBearerToken ( authorization ) ;
2626 if ( ! token ) {
2727 return next (
2828 new AppError ( {
Original file line number Diff line number Diff line change 1+ export function extractBearerToken ( authorization : string | undefined ) : string | null {
2+ if ( ! authorization ) {
3+ return null ;
4+ }
5+
6+ const trimmed = authorization . trim ( ) ;
7+ if ( trimmed . length === 0 ) {
8+ return null ;
9+ }
10+
11+ const separatorIndex = trimmed . indexOf ( " " ) ;
12+ if ( separatorIndex === - 1 ) {
13+ return null ;
14+ }
15+
16+ const scheme = trimmed . slice ( 0 , separatorIndex ) ;
17+ if ( scheme . toLowerCase ( ) !== "bearer" ) {
18+ return null ;
19+ }
20+
21+ const token = trimmed . slice ( separatorIndex + 1 ) . trim ( ) ;
22+ return token . length > 0 ? token : null ;
23+ }
You can’t perform that action at this time.
0 commit comments