简体   繁体   English

如何在yii框架中使用登录表单进行身份验证

[英]How to authentication with login form in yii framework

Hello friends i am beginner in yii framework and i wanna to create login form with authentication but i have this error: 您好朋友,我是yii框架的初学者,我想创建带有身份验证的登录表单,但是我遇到此错误:

Fatal error: Call to undefined method User::model() in C:\\xampp\\htdocs\\pro_c\\protected\\components\\UserIdentity.php on line 47 致命错误:在第47行的C:\\ xampp \\ htdocs \\ pro_c \\ protected \\ components \\ UserIdentity.php中调用未定义的方法User :: model()

UserIdentity.php UserIdentity.php

    public function authenticate()
    {


    $users = User::model()->findByAttributes(array('username'=>$this->username));


            if(!isset($users[$this->username]))
                    $this->errorCode=self::ERROR_USERNAME_INVALID;
            elseif($users[$this->username]!==$this->password)
                    $this->errorCode=self::ERROR_PASSWORD_INVALID;
            else
                    $this->errorCode=self::ERROR_NONE;
            return !$this->errorCode;
      }
   }

    ?>

UserController.php UserController.php

    class UserController extends Controller
    {

    public function actionIndex()
    {
            // renders the view file 'protected/views/site/index.php'
            // using the default layout 'protected/views/layouts/main.php'
            $this->render('index');
    }


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


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


    public function actionLogout()
    {
            Yii::app()->user->logout();
            $this->redirect(Yii::app()->homeUrl);
    }
   }
  ?>

User.php user.php的

    /**
      * LoginForm class.
      * LoginForm is the data structure for keeping
      * user login form data. It is used by the 'login' action of 'SiteController'.
      */
    class User extends CFormModel
    {
    public $username;
    public $password;
    public $rememberMe;

    private $_identity;

    /**
     * Declares the validation rules.
     * The rules state that username and password are required,
     * and password needs to be authenticated.
     */
    public function rules()
    {
            return array(
                    // username and password are required
                    array('username, password', 'required'),
                    // rememberMe needs to be a boolean
                    array('rememberMe', 'boolean'),
                    // password needs to be authenticated
                    array('password', 'authenticate'),
            );
    }

    /**
     * Declares attribute labels.
     */
    public function attributeLabels()
    {
            return array(
                    'rememberMe'=>'Remember me next time',
            );
    }

    /**
     * Authenticates the password.
     * This is the 'authenticate' validator as declared in rules().
     */
    public function authenticate($attribute,$params)
    {
            if(!$this->hasErrors())
            {
                    $this->_identity=new UserIdentity($this->username,$this->password);
                    if(!$this->_identity->authenticate())
                            $this->addError('password','Incorrect username or password.');
            }
    }

    /**
     * Logs in the user using the given username and password in the model.
     * @return boolean whether login is successful
     */
    public function login()
    {
            if($this->_identity===null)
            {
                    $this->_identity=new UserIdentity($this->username,$this->password);
                    $this->_identity->authenticate();
            }
            if($this->_identity->errorCode===UserIdentity::ERROR_NONE)
            {
                    $duration=$this->rememberMe ? 3600*24*30 : 0; // 30 days
                    Yii::app()->user->login($this->_identity,$duration);
                    return true;
            }
            else
                    return false;
    }
   }
  ?>

when i use this code in UserIdentity 当我在UserIdentity中使用此代码时

    $users=array(
        // username => password
        'demo'=>'demo',
        'admin'=>'admin',

    );

return true but when i using 返回true,但是当我使用

     $users = Pi::model()->findByAttributes(array('username'=>$this->username));

return me this error 给我这个错误

     Fatal error: Call to undefined method Pi::model() in C:\xampp\htdocs\pro_c\protected\components\UserIdentity.php on line 47

please help me 请帮我

Well, you have a model called User that is of the type CFormModel (it is a form model). 好吧,您有一个名为User的模型,该模型的类型为CFormModel(它是一个表单模型)。 But you are trying to access User::model()->findByAttributes (a database model) that is used for the type CActiveModel. 但是,您试图访问用于CActiveModel类型的User :: model()-> findByAttributes(数据库模型)。 You should rename your class User to something else. 您应该将您的类User重命名为其他名称。 Here for example, your User class is called UserIdentity. 例如,在这里,您的User类称为UserIdentity。 http://www.yiiframework.com/doc/guide/1.1/en/topics.auth http://www.yiiframework.com/doc/guide/1.1/en/topics.auth

You have to make quite a few changes to your code to work. 您必须对代码进行相当多的更改才能起作用。 Just see the Yii blog demo to get you to the right track. 只需查看Yii博客演示,即可正确入门。

Your code looks to be on the right path, but Yii seems to be unable to find the User class. 您的代码似乎在正确的路径上,但是Yii似乎无法找到User类。

You could manually import the class, or better still, automatically load this using the 'import' directive in the file protected/config/main. 您可以手动导入该类,或者更好的是,使用protected / config / main文件中的“ import”指令自动加载该类。

This tells yii to load all models in protected/models/ directory, assuming that is where the User.php class file resides. 这告诉yii将所有模型加载到protected / models /目录中,假设这是User.php类文件所在的位置。

// autoloading model and component classes
'import'=>array(
    'application.models.*',
    'application.components.*',
),

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

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