public function KeycloakRoleMatcher::applyRoleRules in Keycloak OpenID Connect 8
Applies user role rules to the given user account.
Parameters
\Drupal\user\UserInterface $account: User account.
array $userinfo: Associative array with user information.
bool $save_changes: (Optional) Whether to save the account after the rules have been applied. Defaults to FALSE.
Return value
bool TRUE, if the rules were applied, FALSE otherwise.
File
- src/
Service/ KeycloakRoleMatcher.php, line 198
Class
- KeycloakRoleMatcher
- Role matcher service.
Namespace
Drupal\keycloak\ServiceCode
public function applyRoleRules(UserInterface &$account, array $userinfo, $save_changes = FALSE) {
$rules = $this
->getRoleRules(TRUE);
if (empty($rules)) {
return TRUE;
}
// Extract groups from userinfo.
$groups = $this
->getGroups($this
->getUserGroupsClaimName(), $userinfo);
// Split group paths, if enabled.
if (!empty($groups) && $this
->isSplitGroupsEnabled()) {
$groups = $this
->getSplitGroups($groups, $this
->getSplitGroupsLimit());
}
$roles = $this
->getRoleOptions();
$operations = $this
->getEvalOperationOptions();
// Walk the rules and apply them.
foreach ($rules as $rule) {
$result = $this
->evalRoleRule($groups, $rule);
if ($result) {
switch ($rule['action']) {
case 'add':
if ($this
->isDebugMode()) {
$this
->getLogger()
->debug('Add user role @role to @user, as evaluation "@operation @pattern" matches @groups.', [
'@role' => $roles[$rule['role']],
'@user' => $account
->getAccountName(),
'@operation' => $operations[$rule['operation']],
'@pattern' => $rule['pattern'],
'@groups' => print_r($groups, TRUE),
]);
}
$account
->addRole($rule['role']);
break;
case 'remove':
if ($this
->isDebugMode()) {
$this
->getLogger()
->debug('Remove user role @role from @user, as evaluation "@operation @pattern" matches @groups.', [
'@role' => $roles[$rule['role']],
'@user' => $account
->getAccountName(),
'@operation' => $operations[$rule['operation']],
'@pattern' => $rule['pattern'],
'@groups' => print_r($groups, TRUE),
]);
}
$account
->removeRole($rule['role']);
break;
default:
break;
}
}
}
// Whether to save the user account.
if ($save_changes) {
$account
->save();
}
return TRUE;
}