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

Use an object to describe permission instead of strings #293

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
18 changes: 13 additions & 5 deletions keycloak.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -41,10 +41,15 @@ declare namespace KeycloakConnect {
}

interface Token {
isExpired(): boolean
hasRole(roleName: string): boolean
hasApplicationRole(appName: string, roleName: string): boolean
hasRealmRole(roleName: string): boolean
isExpired(): boolean;
hasRole(roleName: string): boolean;
hasApplicationRole(appName: string, roleName: string): boolean;
hasRealmRole(roleName: string): boolean;
}

interface Permission {
resource: string;
scope?: string;
}

interface GrantManager {
Expand Down Expand Up @@ -344,7 +349,10 @@ declare namespace KeycloakConnect {
*
* @param {string[]} permissions A single string representing a permission or an arrat of strings representing the permissions. For instance, 'item:read' or ['item:read', 'item:write'].
*/
enforcer(permissions: string[]|string, config?: EnforcerOptions): express.RequestHandler
enforcer(
permissions: Permission[] | string | string[] | string[][],
config?: EnforcerOptions
): express.RequestHandler;

/**
* Apply check SSO middleware to an application or specific URL.
Expand Down
22 changes: 17 additions & 5 deletions middleware/enforcer.js
Original file line number Diff line number Diff line change
Expand Up @@ -17,12 +17,24 @@

function handlePermissions (permissions, callback) {
for (let i = 0; i < permissions.length; i++) {
const expected = permissions[i].split(':');
const resource = expected[0];
const permission = permissions[i];

let resource;
let scope;

if (expected.length > 1) {
scope = expected[1];
if (typeof permission === 'string') {
const parts = permission.split(':');
resource = parts[0];
if (parts.length > 1) {
scope = parts[1];
}
} else if (Array.isArray(permission)) {
resource = permission[0];
if (permission.length > 1) {
scope = permission[1];
}
} else if (typeof permission === 'object') {
resource = permission.resource;
scope = permission.scope || undefined;
}

let r = callback(resource, scope);
Expand Down