i am looking for a way how i (logged in as Administrator) can log me in as a specific user (that i select from a list of users, list is already present) onclick without knowing it’s password?
All users have different passwords, so equal passwords are not an option.
OK, Question closed. Here is the solution:
P.S. group with id 2 is my Admin Group.
function loginasuser($user_id = null) {
if (!$user_id) {
$this->Session->setFlash(__('Invalid User.', true));
$this->redirect(array('action'=>'index'));
}
$data = $this->Auth->user();
if($data['User']['group_id'] == 2 || $_SESSION['Auth']['Admin']['id']==$user_id) {
$user_data = $this->User->find('first', array('conditions' => array('User.id' => $user_id)));
if ($user_data['User']['group_id']==2 && $user_data['User']['id']<>$_SESSION['Auth']['Admin']['id']) {
$this->Session->setFlash(__('You can only log in as user', true));
$this->redirect($this->Auth->redirect('/users'));
}
$_SESSION['Auth']['User']['id']=$user_data['User']['id'];
$_SESSION['Auth']['User']['username']=$user_data['User']['username'];
$_SESSION['Auth']['User']['group_id']=$user_data['User']['group_id'];
$_SESSION['Auth']['User']['client_id']=$user_data['User']['client_id'];
$_SESSION['Auth']['User']['created']=$user_data['User']['created'];
$_SESSION['Auth']['User']['modified']=$user_data['User']['modified'];
$_SESSION['Auth']['Admin']['id']=$data['User']['id'];
if($_SESSION['Auth']['User']['group_id']==2) {
$this->redirect($this->Auth->redirect('/ADMINHOME'));
}
else {
$this->redirect($this->Auth->redirect('/USERSHOME'));
}
}
else {
$this->Session->setFlash(__('Only admins are alowed to do so!', true));
$this->redirect(array('action'=>'index'));
}
}
And to go back as admin, you could do:
<? if($_SESSION['Auth']['Admin']['id']>0) { ?>
<a href="/loginasuser/<?=$_SESSION['Auth']['Admin']['id'];?>">Go Back as Admin</a><? }
You can use “username” (email Id) to create session.
On Onclick , trigger an Ajax call, pass the username and set the session using that username.
(Just trigger this call when admin change the selection box,
onChange(this.value))Then just redirect user to end user home page. Put a link to come back to admin dashboard. This helps admin can login as other user.
(Use different session namespace for admin and end user)
$_SESSION[‘user’] for end user and $_SESSIION[‘admin’] for admin user.