<?php
/**
 * Zásuvný modul sloužící k autorizaci
 *
 * @package    MaBoBlog
 * @author     Marian Böhmer
 */
class MyWeb_Controller_Plugin_Authentication extends Zend_Controller_Plugin_Abstract
{
	
	private $_auth;
    /**
     * Metoda volaná před dispečerem
     *
     * @param  Zend_Controller_Request_Abstract $request
     * @return void
     */
    public function dispatchLoopStartup(Zend_Controller_Request_Abstract $request)
    {
    	$this->_doAuthentication($request);
        // získání uživatelské role
        $role = Zend_Auth::getInstance()->hasIdentity() ? Zend_Auth::getInstance()->getIdentity()->role_role : 'guest';
        $acl = MyWeb_Acl::getInstance($request->getModuleName());
        
        // otestování oprávnění
        if (!$acl->isAllowed(strtolower($role), strtolower($request->getControllerName()), strtolower($request->getActionName()))) {
        	
        	$newAction = ('guest' == $role) ? 'login' : 'forbidden';
        	$newController = 'user';
        	
             //$request->setModuleName('default');
             //$request->setControllerName($newController);
             //$request->setActionName($newAction);
             //$request->setDispatched(false);
             $redirector = Zend_Controller_Action_HelperBroker::getStaticHelper('redirector');
             $redirector->gotoUrl($newController.'/'.$newAction.'/');
             //$redirector->gotoUrl('rergrg/');
        }
    }
    
    
    
    protected function _doAuthentication(Zend_Controller_Request_Abstract $request)
    {
    	$frontController = Zend_Controller_Front::getInstance();
    	$bootstrap = $frontController->getParam('bootstrap');
    	$db = $bootstrap->getResource('db');
    	$authAdapter = new Zend_Auth_Adapter_DbTable($db,'user','user_userName','user_passwd','MD5(?)');
    	$select = $authAdapter->getDbSelect();
    	$select	//->	from(array('U' => 'user'),
        		//				array('id_user','user_name','user_userName','user_registrationDateTime','user_passwd','State_id_state'))
        
    			->	join(array('UR' => 'userhasrole'),
        			'User.id_user = UR.User_id_user',
        			array('User.id_user'))
        		->	join(array('R' => 'role'),
        			'UR.Role_id_role = R.id_role',
        			array('R.role_role'))
        		->	where('UR.User_id_user = User.id_user');
    	
        //echo "<p>".$select."</p>";
    	$post = $request->getPost();
    	if (isset($post['submit_login'])){
    		$username = Zend_Filter::filterStatic($post['user_userName'], 'Alnum');
    		$password = Zend_Filter::filterStatic($post['user_passwd'], 'Alnum');
    		
    		$authAdapter->setTableName('user');
    		$authAdapter->setIdentity($username);
    		$authAdapter->setCredential($password);
    		
    		$auth = Zend_Auth::getInstance();
        	$result = $auth->authenticate($authAdapter);
        	
    		if (!$result->isValid()) {
    			// Authentication failed; print the reasons wh
    			foreach ($result->getMessages() as $message) {
    				echo "$message\n";
    			}
    		}else {
    			if(!$result){
    				Zend_Auth::getInstance()->clearIdentity();
    			}else {
    				
    				$row = $authAdapter->getResultRowObject();
    				//echo "<p>row: ".$row->role_role."</p>";
    				//print_r($row);
    				
    				$identity = Zend_Auth::getInstance()->getIdentity();
    				Zend_Auth::getInstance()->getStorage()->write($row);
    			}
    		}
    	}
    	elseif (isset($post['submit_logout'])){
    		Zend_Auth::getInstance()->clearIdentity();
    	}
    }
}
