我有一個應用程序白色兩個用戶角色(成員和管理員)。管理員可以查看所有用戶的列表。現在,管理員應該有可能以另一個用戶的身份登錄,以便像用戶那樣查看應用程序。ZF2切換用戶會話作爲管理員
在不失去管理員身份的情況下切換用戶的最佳解決方案是什麼?
我有一個應用程序白色兩個用戶角色(成員和管理員)。管理員可以查看所有用戶的列表。現在,管理員應該有可能以另一個用戶的身份登錄,以便像用戶那樣查看應用程序。ZF2切換用戶會話作爲管理員
在不失去管理員身份的情況下切換用戶的最佳解決方案是什麼?
我爲我的一些網絡應用程序開發了這個解決方案,工作完美無瑕。讓我們假定一些事實開始:
我開發了一個AdminController散列從中我可以看到在一個列表中的每個用戶,並且該控制器內部有一個動作呼叫接收來自URL的參數「loginasAction」(閱讀下面的代碼):
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的與loged用戶和adminData與我們的「管理員用戶」,我們用一個容器會話容器會話。
我們如何回到我們的管理員用戶?
我的登錄操作可以從URL中讀取一個名爲「loguotas」的參數,在這種情況下,我們將檢查是否存在保存在會話容器中的管理會話。在這種情況下,我們將清除當前的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');
}
}
這是不容易的,也不能太複雜,但你需要坐下來想想了幾分鐘。我希望這能夠很好地服務於你,或者至少爲你的網絡應用程序提供了一個起點。
使用不同的帳戶是不是更好? – Wilt
你對不同的帳戶有什麼意義? –