LoginController.php 2.61 KB
<?php
/**
 *  Controls authorization moments or request to identify who is logged in currently
 * 
 */

class LoginController extends WRestController
{
    /**
     * Authorize identity
     */
    private $_identity;
    
    /**
     * Use model with this controller
     */
    protected $_modelName = "manager";
    
    
    /**
     * Default action
     */
    public $defaultAction = "Identity";
    
    
    /**
     * Link List action to the identity
     */
    public function actionList() {
        $this->actionIdentity();
    } // end actionList()
    
    
    /**
     * Link Get action to the identity
     */
    public function actionGet() {
        $this->actionIdentity();
    } // end actionGet()
    
    
    /**
     * Default actions
     */
    public function actionIdentity()
    {
        if(Yii::app()->user->isGuest) {
            $this->sendResponse(401, array(
                "success" => false
            ));
        }
        else {
            $this->sendResponse(200, array(
                "success" => true,
                "results" => array(
                    "login" => Yii::app()->user->getLogin(),
                    "name" => Yii::app()->user->getFullName()
                )
            ));
        }
    } // end actionIdentity()
    
    
    /**
     * Authorization method
     */
    public function actionAuthorize()
    {
        if(Yii::app()->user->isGuest) {
            $login = $this->getRequest()->getParam("login");
            $pass = $this->getRequest()->getParam("pass");
            
            $this->_identity = new UserIdentity($login, $pass);
            
            if(!$this->_identity->authenticate()) {
                $this->sendResponse(401, array(
                    "success" => false,
                    "details" => 'Wrong authentication data'
                ));
            }
            else {
                Yii::app()->user->login($this->_identity);
                
                $this->sendResponse(200, array(
                    "success" => true,
                    "results" => array(
                        "login" => Yii::app()->user->getLogin(),
                        "name" => Yii::app()->user->getFullName()
                    )
                ));
            }
        }
    }
    
    
    /**
     * Logs out the current user and redirect to home page.
     */
    public function actionLogout()
    {
        Yii::app()->user->logout();
        if(!Yii::app()->request->isAjaxRequest) {
            $this->redirect(Yii::app()->homeUrl);
        }
        else {
            $this->sendResponse(200, array("url" => Yii::app()->homeUrl));
        }
    }
}