繁体   English   中英

如何从控制器调用yii组件用户身份类

[英]How to call yii component useridentity class from controller

我正在尝试使用Yii创建一个简单的登录名这是我的身份验证控制器

class AuthController  extends Controller
{
    /**
    * Declare class-based actions.
    */
    public function actionLogin()
    {
        $model = new LoginForm;
        $post = Yii::app()->request->getPost('LoginForm');
        // If form is submitted
        if($post) {
            $identity = new UserIdentity($post['username'], $post['password']);
            echo $identity->testing();
            if($identity->authenticate()) {
                echo 'yes';
            } else {
                echo 'no';
            }
            exit;
        }
        $this->render('login', array('model' => $model));   
    }
}

这是我的UserIdentity

class UserIdentity extends CUserIdentity
{


    private $_id;

    public function authenticate()
    {   echo 'testing';
        $user = LoginForm::model()->findByAttributes(array('username' => $this->username));
        if(is_null($user)) {
            %this->errorCode=self::ERROR_USERNAME_INVALID;
        } else if($user->password != $this->password) {
            $this->errorCode=self::ERROR_PASSWORD_INVALID;
        } else {
            $this->_id = $user->id;
            $this->errorCode=self::ERROR_NONE;
        }

        return !$this->errorCode;
    }

    function getId()
    {
        return $this->_id;
    }
}

我已经提到了echo'yes'和echo'no',但是两者都没有显示。 如何纠正

首先,您甚至不会看到这些echo语句,最终用户在Yii中以可视方式呈现的唯一内容就是“视图”。 对于我的登录代码(与您的登录代码略有不同),在确认身份验证后,我的应用程序将重定向到主页。 您的自定义UserIdentity文件看起来不错,但同样,该回声语句甚至都不会被看到。 该UserIdentity文件仅用于在后台执行自定义用户身份验证。

在我的UserController中(与您的AuthController相对),我的actionLogin是:

public function actionLogin()
{
    $model=new LoginForm;

    // if it is ajax validation request
    if(isset($_POST['ajax']) && $_POST['ajax']==='login-form')
    {
        echo CActiveForm::validate($model);
        Yii::app()->end();
    }

    // collect user input data
    if(isset($_POST['LoginForm']))
    {
        $model->attributes=$_POST['LoginForm'];
        // validate user input and redirect to the previous page if valid
        if($model->validate() && $model->login())               
        {
            $this->redirect(Yii::app()->user->returnUrl);
        }
    }
    $this->render('/user/login',array('model'=>$model));
}

例如,从上面的内容,您可以重定向到您所在的上一页,或重定向到“ / site / index”下的主站点视图,在该页面下有一些代码可以执行某些任意功能,或者根据您是否打印出HTML是否登录。 一个过于简单的站点视图示例:

<?php
/* @var $this SiteController */
if (Yii::app()->user->isGuest)
{
    // Do stuff here if user is guest.
    echo 'User is a guest.';
}
else
{
    // Do stuff here if user is authenticated.
    echo 'User is authenticated.';
}
?>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM