我已经为我的一些网络应用程序开发了这个解决方案并且可以完美运行。让我们先假设一些事实:
- 您将散列的用户密码保存在您的数据库中
- 用户需要输入电子邮件和密码才能登录。
我开发了一个 AdminController,我可以从中看到列表中的每个用户,并且在该控制器内部有一个动作调用“loginasAction”,它从 URL 接收一个参数(阅读下面的代码):
public function loginasAction() {
$params = $this->params()->fromQuery();
//this is the email of the user we want to log in as
$user=$params['loginas'];
//the current session data
$userSession = new Container('appData');
//a new session container built for the ocassion
$adminSession = new Container('adminData');
//save your admin user session as "originalUser" in the new session container,
//because the original one is going to be cleared
$adminSession->originalUser = $userSession->user;
//retrieve the user data and asave it into the new session container too
$userModel = new UserModel();
$user= $userModel->getUser($user);
$adminSession->clientAdmin = $clientAdmin;
//redirect to my LogController Login action.
return $this->redirect()->toRoute('login', array(), array('query' => array('loginas' => '')));
}
让我们看看登录操作有什么:
//check if it comes form admin panel
$params = $this->params()->fromQuery();
if (isset($params['loginas'])) {
$adminSession = new Container('adminData');
if (isset($adminSession->userToLog)) {
//let's use the destination user to log in as
$user = $adminSession->userToLog;
unset($adminSession->userToLog);
//clear previous user session
$session = new Container('appData');
$session->getManager()->getStorage()->clear('appData');
//log new user and redirect
//userSession is a function that save the user data
//in my appData container session in the way I need it
$this->userSession($user);
//since I have loged in the user, we can redirect ourselves to home page
return $this->redirect()->toRoute('home');
}
}
现在我们有登录用户的 appData 容器会话和我们使用的“管理员用户”的 adminData 容器会话。
我们如何返回到我们的管理员用户?
我的登录操作可以从名为“loguotas”的 URL 读取参数,在这种情况下,我们将检查 adminData 会话容器中是否保存了管理会话。在这种情况下,我们将清除当前的 appData 会话并在那里保存我们在流程开始时保存的 adminData 用户,即我们的管理员用户。
//check if it is an admin user that want to return to view clients list
if (isset($params['logoutas'])) {
$adminSession = new Container('adminData');
if (isset($adminSession->originalUser)) {
$originalUser = $adminSession->originalUser;
//clean sessions
$session = new Container('appData');
$session->getManager()->getStorage()->clear();
//log in original user and redirect
$this->userSession($originalUser);
return $this->redirect()->toRoute('admin');
}
}
这既不容易也不太复杂,但你需要坐下来思考几分钟。我希望这能很好地为您服务,或者至少为您的网络应用程序提供一个起点。