Skip to content

Instantly share code, notes, and snippets.

@sukum
Forked from karlingen/switch_user.php
Last active April 23, 2021 15:21
Show Gist options
  • Save sukum/44dcc9432f65c659594c0626c187dcca to your computer and use it in GitHub Desktop.
Save sukum/44dcc9432f65c659594c0626c187dcca to your computer and use it in GitHub Desktop.
SugarCRM user switching / login as another user
<?php
if (!defined('sugarEntry')) {
define('sugarEntry', true);
}
require_once('include/entryPoint.php');
require_once 'include/MVC/SugarApplication.php';
$app = new SugarApplication();
$app->startSession();
$app->loadUser();
$app->loadGlobals();
if (empty($current_language)) {
$current_language = $sugar_config['default_language'];
}
$app_list_strings = return_app_list_strings_language($current_language);
$app_strings = return_application_language($current_language);
/**
* Login as another user in SugarCRM and switch back to admin user
*
* Simply put this file into a custom entry point file and
* browse to it with the parameters 'user_name' or 'back_to_sudo'
*
* Usage:
* http://xxxxxxxxx/index.php?entryPoint=my_awesome_entry_point&user_name=mylittlepony
* http://xxxxxxxxx/index.php?entryPoint=my_awesome_entry_point&back_to_sudo=1
*
* @author Karl Metum <[email protected]>
* @link http://www.codehacker.se
*/
if(!empty($_REQUEST['user_name']) && $GLOBALS['current_user']->is_admin)
{
echo "Verified admin user...<br/>";
$user_focus = BeanFactory::getBean('Users');
$user_focus->retrieve_by_string_fields(array('user_name' => $_REQUEST['user_name']));
if(!empty($user_focus->id))
{
echo "target user found...<br/>";
if(empty($_SESSION['sudo_user_id'])) {
$_SESSION['sudo_user_id'] = $GLOBALS['current_user']->id;
echo "original user backed up...<br/>";
}
$GLOBALS['current_user'] = $user_focus;
$_SESSION['authenticated_user_id'] = $user_focus->id;
echo "Successfully logged in as " . $GLOBALS['current_user']->user_name;
return;
}
}
elseif(!empty($_REQUEST['back_to_sudo']) && !empty($_SESSION['sudo_user_id']))
{
echo "original user backup found...<br/>";
$user_focus = BeanFactory::getBean('Users');
$user_focus->retrieve($_SESSION['sudo_user_id']);
if($user_focus->is_admin)
{
echo "original user is admin...<br/>";
$_SESSION['sudo_user_id'] = null;
$GLOBALS['current_user'] = $user_focus;
$_SESSION['authenticated_user_id'] = $user_focus->id;
echo "Successfully logged back to sudo user: " . $GLOBALS['current_user']->user_name;
return;
}
}
die("No dice.");
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment