Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

add support for async guard function #355

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion keycloak.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -192,7 +192,7 @@ declare namespace KeycloakConnect {
isExpired(): boolean
}

type GuardFn = (accessToken: Token, req: express.Request, res: express.Response) => boolean
type GuardFn = (accessToken: Token, req: express.Request, res: express.Response) => boolean|Promise<boolean>

interface EnforcerOptions {
response_mode?: string,
Expand Down
18 changes: 14 additions & 4 deletions middleware/protect.js
Original file line number Diff line number Diff line change
Expand Up @@ -50,11 +50,21 @@ module.exports = function (keycloak, spec) {

return function protect (request, response, next) {
if (request.kauth && request.kauth.grant) {
if (!guard || guard(request.kauth.grant.access_token, request, response)) {
return next();
const guardedResponse = guard && guard(request.kauth.grant.access_token, request, response);
if (guardedResponse instanceof Promise) {
return guardedResponse
.then(function (authorized) {
return authorized ? next() : keycloak.accessDenied(request, response, next);
})
.catch(function () {
return keycloak.accessDenied(request, response, next);
});
} else {
if (!guard || guardedResponse) {
return next();
}
return keycloak.accessDenied(request, response, next);
}

return keycloak.accessDenied(request, response, next);
}

if (keycloak.redirectToLogin(request)) {
Expand Down