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

feat: export isAuthorizedByRole util function #85

Merged
merged 3 commits into from
May 13, 2020
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
14 changes: 3 additions & 11 deletions src/directives/directiveResolvers.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { CONTEXT_KEY } from '../KeycloakContext'
import { isAuthorizedByRole } from './utils'

/**
*
Expand Down Expand Up @@ -104,17 +105,8 @@ export const hasRole = (roles: Array<string>) => (next: Function) => (root: any,
if (typeof roles === 'string') {
roles = [roles]
}

let foundRole = null // this will be the role the user was successfully authorized on

for (let role of roles) {
if (context[CONTEXT_KEY].hasRole(role)) {
foundRole = role
break
}
}

if (!foundRole) {

if (!isAuthorizedByRole(roles, context)) {
const error: any = new Error(`User is not authorized. Must have one of the following roles: [${roles}]`);
error.code = "FORBIDDEN"
throw error
Expand Down
21 changes: 21 additions & 0 deletions src/directives/utils.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
import { CONTEXT_KEY } from '../KeycloakContext'

/**
*
* @param roles the list of roles the user should match against
* @param context the graphql context that contains the user info
*/
export function isAuthorizedByRole(roles: string[], context?: any) {
if (!(context && context[CONTEXT_KEY])) {
console.error('context.kauth is missing. Keycloak integration is probably misconfigured')
darahayes marked this conversation as resolved.
Show resolved Hide resolved
return false
}

for (const role of roles) {
if (context[CONTEXT_KEY].hasRole(role)) {
return true
}
}

return false
}
1 change: 1 addition & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,3 +2,4 @@ export * from './KeycloakSubscriptionHandler'
export * from './KeycloakContext'
export * from './directives'
export * from './api'
export { isAuthorizedByRole } from './directives/utils'