if(!($modx->user->isMember($UserGroupName))) {
The function joinGroup()
already checks, whether the user is in the group and just returns true
, if that’s the case. The function also checks, if the group and the role exist.
$user = $modx->getObject('modUser', array('username' => $username));
This line is not needed. The current user is already available under $modx->user
.
Here is a more elaborated version:
<?php
$UserGroupName = $modx->getOption('group',$scriptProperties,'');
$RoleName = $modx->getOption('role',$scriptProperties,'');
$context = $modx->getOption('context',$scriptProperties,$modx->context->get('key'));
//check if user is logged in
if (!$modx->user->hasSessionContext($context)){
$modx->log(modX::LOG_LEVEL_ERROR,'user not logged in');
return 'user not logged in';
}
//check if properties are missing
if (empty($UserGroupName)) {
$modx->log(modX::LOG_LEVEL_ERROR,'group missing');
return 'group missing';
}
if (empty($RoleName)) {
$modx->log(modX::LOG_LEVEL_ERROR,'role missing');
return 'role missing';
}
//ensure that it can’t be made to set a random user to Administrator
//would probably be safer to have lists with allowed groups and roles
$prohibited_groups = array('administrator', 'another_prohibited_group');
if (in_array(strtolower(trim($UserGroupName)), $prohibited_groups)) {
$modx->log(modX::LOG_LEVEL_ERROR,'group not allowed');
return 'group not allowed';
}
$prohibited_roles = array('super user', 'another_prohibited_role');
if (in_array(strtolower(trim($RoleName)), $prohibited_roles)) {
$modx->log(modX::LOG_LEVEL_ERROR,'role not allowed');
return 'role not allowed';
}
// Assign current user to User Group and Role
if ($modx->user->joinGroup($UserGroupName,$RoleName)){
return '';
} else {
$modx->log(modX::LOG_LEVEL_ERROR,'joinGroup failed');
return 'joinGroup failed';
}
Snippet call:
[[!setUserGroup? &group=`Members` &role=`Member`]]