<?php

/**
 * LoginController
 * 
 * @author Luk� Havl��ek
 * @version 1.0
 */

class LoginController extends Zend_Controller_Action {
	
	public function init()
	{
		$this->_helper->layout->disableLayout();
	}

	/**
	 * The default action - show the home page
	 */
	
	public function indexAction()
	{
		if ($this->_request->isPost()) {
            
			// collect the data from the user
            $f = new Zend_Filter_StripTags();
            $login    = $f->filter($this->_request->getPost('login'));
            $password = $f->filter($this->_request->getPost('password'));
            $remember = (int) $this->_request->getPost('remember');
            
            if (empty($login)) {
                $this->view->msg = 'msg-login-no-login-given';
            } else {
                
            	// setup Zend_Auth adapter for a database table
                $dbAdapter = Zend_Registry::get('db');
                
                $authAdapter = new Zend_Auth_Adapter_DbTable($dbAdapter);
                $authAdapter->setTableName('iso_users');
                $authAdapter->setIdentityColumn('login');
                $authAdapter->setCredentialColumn('password');
                $authAdapter->setCredentialTreatment('sha1(?) AND user_active = 1');
                
                // Set the input credential values to authenticate against
                $authAdapter->setIdentity($login);
                $authAdapter->setCredential($password);
                
                // do the authentication
                $auth = Zend_Auth::getInstance();
                
                $storage = new Zend_Auth_Storage_Session('iso');
                
                $auth->setStorage($storage);
                
                if (!isset($storage->initialized)) {
    				//Zend_Session::regenerateId();
    				$storage->initialized = true;
				}
                
                $result = $auth->authenticate($authAdapter);
                if ($result->isValid()) {
                	
                    // success: store database row to auth's storage
                    // system. (Not the password though!)
                    $data = $authAdapter->getResultRowObject(array('id_user', 'super_admin'));
                    $auth->getStorage()->write($data);
                    
                    $this->_redirect('http://www.xroad.cz/iso');
                } else {
                    // failure: clear database row from session
                    $this->view->msg = 'msg-login-login-failure';
                                      
                }
            }
        }
        
        $settings = new Settings();
        $this->view->regAllowed = $settings->getValue('registrace-povolena-f');
        	
		$this->render();
	}
	
	public function logoutAction()
	{
		$auth = Zend_Auth::getInstance();
        $auth->setStorage(new Zend_Auth_Storage_Session('iso'));
        $auth->clearIdentity();
        $this->_redirect('http://www.xroad.cz/iso/login');
	}
}
?>