Skip to content

Commit

Permalink
feat(pre-handlers): Add getAuthBearer function
Browse files Browse the repository at this point in the history
This commit adds the getAuthBearer function to the pre-handlers package. The function extracts the Bearer token from the authorization header and returns it. If the header is invalid or the token is missing, it returns null.

Example usage:
console.log(this.headers.authorization); // 'Bearer myToken123'
const token = getAuthBearer(this.headers.authorization);
console.log(token); // 'myToken123'

const invalidToken = getAuthBearer('Basic myToken123');
console.log(invalidToken); // null
  • Loading branch information
alimd committed Oct 28, 2024
1 parent 8ed4eb3 commit 43de511
Showing 1 changed file with 26 additions and 0 deletions.
26 changes: 26 additions & 0 deletions packages/pre-handlers/src/lib/get-auth-bearer.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
/**
* Extracts the Bearer token from the authorization header.
*
* This function takes an optional authorization header string, extracts the Bearer token, and returns it.
* If the header is invalid or the token is missing, it returns null.
*
* @param {string} [authorizationHeader] - The authorization header string.
* @returns {string | null} The extracted Bearer token or null if the header is invalid.
*
* @example
* ```ts
* console.log(this.headers.authorization); // 'Bearer myToken123'
* const token = getAuthBearer(this.headers.authorization);
* console.log(token); // 'myToken123'
*
* const invalidToken = getAuthBearer('Basic myToken123');
* console.log(invalidToken); // null
* ```
*/
export function getAuthBearer(authorizationHeader?: string): string | null {
const auth = authorizationHeader?.split(' ');
if (!auth || auth[0].toLowerCase() !== 'bearer' || !auth[1]) {
return null;
}
return auth[1];
}

0 comments on commit 43de511

Please sign in to comment.