Skip to content
This repository has been archived by the owner on Mar 28, 2024. It is now read-only.

Commit

Permalink
feat(nano-server): add requireUserAuth support asynchronous validation
Browse files Browse the repository at this point in the history
  • Loading branch information
njfamirm committed Jan 1, 2024
1 parent fb3cb04 commit 3634e2f
Showing 1 changed file with 10 additions and 4 deletions.
14 changes: 10 additions & 4 deletions packages/nano-server/src/nano-server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -495,14 +495,20 @@ export class AlwatrConnection {
*
* @param validator Optional function to validate the user authentication.
* @returns The user authentication information.
* @throws {'access_denied'} If user authentication is missing or validation fails.
* @throws {'authorization_required'} If user authentication is missing.
* @throws {'access_denied'} If user authentication is invalid.
*
*
* @example
* ```ts
* const userAuth = connection.requireUserAuth();
* function validateUserAuth(userAuth: UserAuth): boolean {
* return userAuth.id === 'public_user_id' && userAuth.token === 'secret_token';
* }
*
* await connection.requireUserAuth(validateUserAuth);
* ```
*/
requireUserAuth(validator?: (userAuth: Partial<UserAuth>) => boolean): UserAuth {
async requireUserAuth(validator?: (userAuth: UserAuth) => PromiseLike<boolean>): Promise<UserAuth> {
const userAuth = this.getUserAuth();

if (userAuth.id == null || userAuth.token == null || userAuth.deviceId == null) {
Expand All @@ -512,7 +518,7 @@ export class AlwatrConnection {
errorCode: 'authorization_required',
};
}
else if (typeof validator === 'function' && validator(userAuth) !== true) {
else if (typeof validator === 'function' && await validator(userAuth as UserAuth) !== true) {
throw {
ok: false,
statusCode: 403,
Expand Down

0 comments on commit 3634e2f

Please sign in to comment.