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

Commit

Permalink
feat: add requireAuth field to useKeycloak
Browse files Browse the repository at this point in the history
  • Loading branch information
Creaous committed Mar 15, 2024
1 parent 82214e8 commit 28c56b4
Showing 1 changed file with 21 additions and 3 deletions.
24 changes: 21 additions & 3 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,9 @@ export type KeycloakPluginOptions = KeycloakPluginOptionsBase;
/**
* Represents the options for the Keycloak plugin.
*/
/**
* Represents the options for the Keycloak plugin.
*/
export interface KeycloakPluginOptionsBase {
/**
* The Keycloak instance to use for token verification.
Expand All @@ -39,9 +42,16 @@ export interface KeycloakPluginOptionsBase {

/**
* The roles that are allowed to authenticate.
* @default []
*/
allowedRoles?: string[];

/**
* Specifies whether authentication is required.
* @default false
*/
requireAuth?: boolean;

/**
* A function that retrieves the token for authentication.
* @param params - The parameters for token retrieval.
Expand All @@ -63,11 +73,12 @@ export interface KeycloakPluginOptionsBase {
export function useKeycloak(options: KeycloakPluginOptions): Plugin {
// Destructure the options object and assign default values
const {
cachePrefix = 'tokens',
extendContextField = 'keycloak',
keycloak,
redis,
allowedRoles,
extendContextField = 'keycloak',
cachePrefix = 'tokens',
allowedRoles = [],
requireAuth = false,
getToken = defaultGetToken
} = options;

Expand Down Expand Up @@ -132,6 +143,13 @@ export function useKeycloak(options: KeycloakPluginOptions): Plugin {

// Store the token content in the payloadByRequest WeakMap
payloadByRequest.set(request, JSON.parse(ct));
} else {
// If authentication is required, throw an unauthorized error
if (requireAuth) {
throw unauthorizedError(
'Authentication is required to access this resource.'
);
}
}
},
onContextBuilding({ context, extendContext }) {
Expand Down

0 comments on commit 28c56b4

Please sign in to comment.