Skip to content

Instantly share code, notes, and snippets.

@nickopris
Last active August 29, 2015 14:03
Show Gist options
  • Save nickopris/6bd9fac7c8d59c07e86c to your computer and use it in GitHub Desktop.
Save nickopris/6bd9fac7c8d59c07e86c to your computer and use it in GitHub Desktop.
Allow to impersonate as an user account based on information from a content type.
/**
* Allow Masquerade role users to impersonate Role1 or Role2 accounts.
* Note that these users will never see their own account for editing or otherwise.
* As soon as they log in they will act on behalf of the account
* that we specify they can masquerade as.
*
* Only administrators should be able to control the list of users
* allowed to masquerade.
*
* @param $edit
* @param $account
*/
function yourmodule_user_login(&$edit, $account){
global $user;
$managed_uid = null;
if (!isset($_POST['form_id']) || $_POST['form_id'] != 'user_pass_reset') {
/**
* Select from masquerading Content Type the user that has same id with logged in user
*/
$query = new EntityFieldQuery();
$result = $query->entityCondition("entity_type", 'node')
->entityCondition('bundle', 'masquerading')
->fieldCondition('field_user_who_can_masquerade', 'target_id', $user->uid, '=')
->range(0,1)
->execute();
/**
* If found, get the user that is to be impersonated and login as them
* [no session needs saving as we never need it]
*/
if(count($result) >0 ) {
$node = reset($result['node']);
$node_loaded = node_load($node->nid);
$wrapper = entity_metadata_wrapper('node', $node_loaded);
$managed_uid = $wrapper->field_impersonated_account->raw();
/**
* Just an extra caution to make sure we never impersonate an admin
* and that the user we impersonate is of the roles we actually allow.
*/
if($managed_uid != null) {
$managed_user = user_load($managed_uid);
if(isset($managed_user)) {
if(!array_intersect($managed_user->roles, array('Art Organisation', 'Gallery'))) {
return;
}
if($managed_uid > 1) {
$user = user_load($managed_uid);
$edit['redirect'] = 'node/486';
}
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment