2012-06-11 10 views
2

나는 최근에 젠드 프레임 워크를 사용하기 시작했는데 난 아직도 꽤으로 session_start하는 데 사용하고있어, 특정 세션 이름에 변수를 할당 : 나는 시도하고 (즉, $ _SESSION [ '이름'] == $ 사용자 이름)Zend_Auth 세션 ID를 저장하고 변경하는 방법은 무엇입니까?

Zend에서 이와 비슷한 작업을 수행하는 방법을 알아 내야합니다. 지금, 내 인증 스크립트는 내 AD 서버에 대해 LDAP를 사용하여 자격 증명을 확인하고, 성공하면 사용자를 인증합니다.

admin 사용자가 다른 사람의 세션을 쉽게 "입력"할 수있게 해주는 스크립트를 만들고 싶습니다. admin1이 활성 세션을 가지고 있고 user1의 세션으로 전환하려고한다고 가정 해 보겠습니다. 일반적으로 $ _SESSION [ 'username'] 변수를 변경하고 로그인 한 사용자의 신원을 효과적으로 변경합니다.

하지만 Zend를 사용하면 세션 정보를 변경하는 방법을 잘 모르겠습니다. 가치가있는 내용은 다음과 같습니다.

class LoginController extends Zend_Controller_Action 
{ 
    public function getForm() 
    { 
     return new LoginForm(array(
      'action' => '/login/process', 
      'method' => 'post', 
     )); 
    } 

    public function getAuthAdapter(array $params) 
    { 
     $username = $params['username']; 
     $password = $params['password']; 
     $auth = Zend_Auth::getInstance(); 

     require_once 'Zend/Config/Ini.php'; 
     $config = new Zend_Config_Ini('../application/configs/application.ini', 'production'); 
     $log_path = $config->ldap->log_path; 
     $options = $config->ldap->toArray(); 
     unset($options['log_path']); 

     require_once 'Zend/Auth/Adapter/Ldap.php'; 
     $adapter = new Zend_Auth_Adapter_Ldap($options, $username, $password); 

     $result = $auth->authenticate($adapter); 

     if ($log_path) { 
      $messages = $result->getMessages(); 

      require_once 'Zend/Log.php'; 
      require_once 'Zend/Log/Writer/Stream.php'; 
      require_once 'Zend/Log/Filter/Priority.php'; 
      $logger = new Zend_Log(); 
      $logger->addWriter(new Zend_Log_Writer_Stream($log_path)); 
      $filter = new Zend_Log_Filter_Priority(Zend_Log::DEBUG); 
      $logger->addFilter($filter); 

      foreach ($messages as $i => $message) { 
       if ($i-- > 1) { // $messages[2] and up are log messages 
        $message = str_replace("\n", "\n ", $message); 
        $logger->log("Ldap: $i: $message", Zend_Log::DEBUG); 
       } 
      } 
     } 
     return $adapter; 
    } 
    public function preDispatch() 
    { 
     if (Zend_Auth::getInstance()->hasIdentity()) { 
      // If the user is logged in, we don't want to show the login form; 
      // however, the logout action should still be available 
      if ('logout' != $this->getRequest()->getActionName()) { 
       $this->_helper->redirector('index', 'index'); 
      } 
     } else { 
      // If they aren't, they can't logout, so that action should 
      // redirect to the login form 
      if ('logout' == $this->getRequest()->getActionName()) { 
       $this->_helper->redirector('index'); 
      } 
     } 
    } 
    public function indexAction() 
    { 
     $this->view->form = $this->getForm(); 
    } 
    public function processAction() 
    { 
     $request = $this->getRequest(); 

     // Check if we have a POST request 
     if (!$request->isPost()) { 
      return $this->_helper->redirector('index'); 
     } 

     // Get our form and validate it 
     $form = $this->getForm(); 
     if (!$form->isValid($request->getPost())) { 
      // Invalid entries 
      $this->view->form = $form; 
      return $this->render('index'); // re-render the login form 
     } 

     // Get our authentication adapter and check credentials 
     $adapter = $this->getAuthAdapter($form->getValues()); 
     $auth = Zend_Auth::getInstance(); 
     $result = $auth->authenticate($adapter); 
     if (!$result->isValid()) { 
      // Invalid credentials 
      $form->setDescription('Invalid credentials provided'); 
      $this->view->form = $form; 
      return $this->render('index'); // re-render the login form 
     } 

     // We're authenticated! Redirect to the home page 

     $this->_helper->redirector('index', 'index'); 

    } 
    public function logoutAction() 
    { 
     Zend_Auth::getInstance()->clearIdentity(); 
     $this->_helper->redirector('index'); // back to login page 
    } 
} 

내가 설명한 내용을 수행 할 방법이 있습니까? 어떤 제안을 주셔서 감사합니다.

답변

2

코드가 주어지면 인증 결과는 Zend_Auth_Storage_Session 개체를 통해 PHP 세션에 저장됩니다.

Zend_Auth::getIdentity()을 호출하면 저장 장치에 액세스 할 수 있고 비어 있지 않은 경우 결과가 반환됩니다. 마찬가지로 기본 저장소에 액세스하고 그 값을 변경하여 저장된 ID를 변경할 수 있습니다. Zend_Auth_Adapter_Ldap으로 인증 한 결과로 저장된 실제 ID는 LDAP 사용자 이름을 나타내는 문자열 값일뿐입니다.

효과적으로 당신이 할 수 있으며, 사용자 로그인 변경하려면 :

Zend_Auth::getInstance()->getStorage()->write('newUserName'); 

이것은 코드 주어진 장소에 있어야 기본 동작을 가정합니다.

인증 성공 후 내 응용 프로그램에서 수행하는 작업은 일부 사용자 모델의 새 객체를 만들고이를 Zend_Auth 세션에 작성하여 각 세션에서 사용할 수있는 사용자에 대한 자세한 정보를 제공하므로 사용자는 응용 프로그램에 따라 저장소에 다른 것들이있을 수 있습니다.

내가 예를 들어 할 것입니다 : 내가 Zend_Auth::getInstance()->getIdentity()를 호출 내 응용 프로그램의 아무 곳이나 지금

$auth  = new Zend_Auth(...); 
$authResult = $auth->authenticate(); 

if ($authResult->isValid() == true) { 
    $userobj = new Application_Model_UserSession(); 
    // populate $userobj with much information about the user 
    $auth->getStorage()->write($userobj); 
} 

을 내가 문자열보다는 다시 Application_Model_UserSession 개체를 얻을; 그러나 나는 빗 나간다. 당신을 도움이 될 것

정보는 다음과 같습니다

$user = Zend_Auth::getInstance()->getIdentity(); // reads from auth->getStorage() 

Zend_Auth::getInstance()->getStorage()->write($newUser); 
+0

당신의 선생님, 생명의 은인입니다. 그것은 트릭을했다. 이제 다소 관련이 있지만 관련이없는 질문이 있습니다. $ user 오브젝트의 현재 결과는 \ MYDIRECTORY \ username입니다. \ MYDIRECTORY \ 값은 본질적으로 내 application.ini 파일에서'ldap.server2.accountDomainNameShort'로 정의한 내용입니다. 이유는 무엇입니까? –

+0

접두어는 LDAP 어댑터에만 해당되며 HTTP 인증은 영역과 비슷한 기능을 수행합니다. 이 도메인이 앞에 추가됩니까? 제 생각에는 인증 된 곳을 돌아보고 알 수 있습니다. 응용 프로그램이 어떻게 든 의존한다면 세션을 수동으로 수정할 때만 세션을 미리 추가해야합니다. 그렇지 않으면 안전하게 생략 할 수 있습니다. – drew010

관련 문제