Skip to content

Commit

Permalink
feat(nano-server): add getUserAuth
Browse files Browse the repository at this point in the history
Co-authored-by: Mohammad Honarvar <[email protected]>
  • Loading branch information
alimd and mohammadhonarvar committed May 7, 2023
1 parent 811fbc0 commit 615266f
Showing 1 changed file with 24 additions and 4 deletions.
28 changes: 24 additions & 4 deletions core/nano-server/src/nano-server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ import type {
ParamValueType,
QueryParameters,
StringifyableRecord,
UserAuth,
} from '@alwatr/type';
import type {IncomingMessage, ServerResponse} from 'node:http';
import type {Duplex} from 'node:stream';
Expand Down Expand Up @@ -405,7 +406,7 @@ export class AlwatrConnection {
/**
* Get the token placed in the request header.
*/
getToken(): string | null {
getAuthBearer(): string | null {
const auth = this.incomingMessage.headers.authorization?.split(' ');

if (auth == null || auth[0].toLowerCase() !== 'bearer') {
Expand Down Expand Up @@ -497,10 +498,9 @@ export class AlwatrConnection {
* ```
*/
requireToken(validator?: ((token: string) => boolean) | Array<string> | string): string {
const token = this.getToken();
const token = this.getAuthBearer();

if (token == null) {
// eslint-disable-next-line no-throw-literal
throw {
ok: false,
statusCode: 401,
Expand All @@ -519,14 +519,34 @@ export class AlwatrConnection {
else if (typeof validator === 'function') {
if (validator(token) === true) return token;
}
// eslint-disable-next-line no-throw-literal
throw {
ok: false,
statusCode: 403,
errorCode: 'access_denied',
};
}

/**
* Parse and get request user auth (include id and token).
*
* Example:
* ```ts
* const userAuth = connection.requireUserAuth();
* ```
*/
getUserAuth(): UserAuth | null {
const auth = this.getAuthBearer()
?.split('/')
.filter((item) => item.trim() !== '');

return auth == null || auth.length !== 2
? null
: {
id: auth[0],
token: auth[1],
};
}

/**
* Parse query param and validate with param type.
*/
Expand Down

0 comments on commit 615266f

Please sign in to comment.