Yii登录不接受正确的密码 [英] Correct password is not accepted in Yii login

查看:15
本文介绍了Yii登录不接受正确的密码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对 yii 框架很陌生,目前正在尝试通过数据库身份验证建立登录.但是当我尝试登录时,我收到此错误消息

<块引用>

请修正以下输入错误:密码不正确.

但是当我检查数据库表时,我输入了正确的密码.

有没有人可以帮帮我

这里是控制器

render('index');}公共函数 actionError(){if($error=Yii::app()->errorHandler->error){if(Yii::app()->request->isAjaxRequest)echo $error['message'];别的$this->render('error', $error);}}公共函数 actionContact(){$model=new ContactForm;if(isset($_POST['ContactForm'])){$model->attributes=$_POST['ContactForm'];if($model->validate()){$name='=?UTF-8?B?'.base64_encode($model->name).'?=';$subject='=?UTF-8?B?'.base64_encode($model->subject).'?=';$headers="发件人:$name <{$model->email}>
".回复:{$model->email}
"."MIME 版本:1.0
".内容类型:文本/纯文本;字符集=UTF-8";邮件(Yii::app()->params['adminEmail'],$subject,$model->body,$headers);Yii::app()->user->setFlash('contact','感谢您联系我们,我们会尽快回复您.');$this->refresh();}}$this->render('contact',array('model'=>$model));}公共函数 actionLogin(){$form=新登录表单;if(isset($_POST['LoginForm'])){$form->attributes=$_POST['LoginForm'];if($form->validate() && $form->login()) $this->redirect(Yii::app()->user->returnUrl);}$this->render('login',array('form'=>$form));}公共函数 actionLogout(){Yii::app()->user->logout();$this->redirect(Yii::app()->homeUrl);}

}

介绍模型

'Email Address');}公共功能身份验证($attribute,$params){if(!$this->hasErrors())//我们只想在没有输入错误时进行身份验证{$identity=new UserIdentity($this->email,$this->password);$identity->authenticate();开关($identity->errorCode){案例 UserIdentity::ERROR_NONE:Yii::app()->user->login($identity);休息;案例 UserIdentity::ERROR_USERNAME_INVALID:$this->addError('email','电子邮件地址不正确.');休息;默认值://UserIdentity::ERROR_PASSWORD_INVALID$this->addError('密码','密码不正确.');休息;}}}公共函数登录(){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天Yii::app()->user->login($this->_identity,$duration);返回真;}别的返回假;}

}

这里是视图

pageTitle=Yii::app()->name .' - 登录';$this->breadcrumbs=array('登录',);?><h1>登录</h1><p>请使用您的登录凭据填写以下表格:</p><div class="form"><?php $myWidget=$this->beginWidget('CActiveForm', array('id'='=>'登录表单','enableClientValidation'=>真,'clientOptions'=>数组('validateOnSubmit'=>真,),));?><p class="note">带有 <span class="required">*</span> 的字段</p><div><?php echo CHtml::beginForm();?><?php echo CHtml::errorSummary($form);?><div><?php echo CHtml::activeLabel($form,'email');?><?php echo CHtml::activeTextField($form,'email') ?>

<div><?php echo CHtml::activeLabel($form,'password');?><?php echo CHtml::activePasswordField($form,'password') ?>

<div><?php echo CHtml::submitButton('Login');?>

<?php echo CHtml::endForm();?>

endWidget();?>

解决方案

您必须在 UserIdentity 类中编写身份验证逻辑,而不是在 LoginForm 模型中.

  1. 登录表单模型例如:-

     公共函数身份验证($attribute, $params){如果 (!$this->hasErrors()) {$this->_identity = new UserIdentity($this->email, $this->password);if (!$this->_identity->authenticate())$this->addError('password', '用户名或密码不正确.');}}公共函数登录(){if ($this->_identity === null) {$this->_identity = new UserIdentity($this->email, $this->password);$this->_identity->authenticate();}if ($this->_identity->errorCode === UserIdentity::ERROR_NONE) {$duration = $this->rememberMe ?3600 * 24 * 30 : 0;//30天Yii::app()->user->login($this->_identity, $duration);返回真;} 别的返回假;}

  2. 对于数据库身份验证,您必须使用 componentsUserIdentity.php 在身份验证函数中添加您的身份验证逻辑

    公共函数authenticate() {Yii::app()->getModule('auth')->getModule('user');#导入你的模块.$记录 = 用户::模型()->findByAttributes(array('email' => CHtml::encode($this->email)));#数据库调用if ($record === null)$this->errorCode = self::ERROR_USERNAME_INVALID;#else if ($record->password !== crypt($this->password, $record->password))else if ($record->password !== $this->password)$this->errorCode = self::ERROR_PASSWORD_INVALID;别的 {$this->_uid = $record->user_id;$this->setState('title', $record->user_name);$this->setState('uid', $this->_uid);$this->errorCode = self::ERROR_NONE;}返回 !$this->errorCode;

    }

  3. 如果您有基于角色的登录,那么您必须在 config/main.php 中添加 WebUser 类.

    components' =>大批('用户' =>大批(//启用基于 cookie 的身份验证'类' =>'网络用户','允许自动登录' =>真的,'loginUrl'=>array('/site/login'),'returnUrl'=>array('/site/index'),),}

  4. 对于基于角色的评估检查,您必须编写 componentsWebUser.php 类 -

     class WebUser 扩展 CWebUser {公共函数 checkAccess($operation, $params = array()) {如果(空($this->id)){//未识别 =>没有权利返回假;}$role = $this->getState("roles");如果($角色 === '3'){返回真;//超级管理员角色可以访问所有内容}else if ($role === '1') {返回真;//admin(manager) 角色可以访问所有内容}//如果操作请求是当前用户的角色,则允许访问返回($operation === $role);}}

有关更多信息,请查看身份验证和授权

Hi i'm quite new to yii framework, currently trying to establish a login through database authentication. but while im trying to log in i get this error saying

Please fix the following input errors: Password is incorrect.

but when i check the database table im typing the correct password.

can anybody help me out if this

Heres the Controller

<?php

class SiteController extends Controller

{

public function actions()
{
    return array(

        'captcha'=>array(
            'class'=>'CCaptchaAction',
            'backColor'=>0xFFFFFF,
        ),

        'page'=>array(
            'class'=>'CViewAction',
        ),
    );
}
public function actionIndex()
{

    $this->render('index');
}


public function actionError()
{
    if($error=Yii::app()->errorHandler->error)
    {
        if(Yii::app()->request->isAjaxRequest)
            echo $error['message'];
        else
            $this->render('error', $error);
    }
}


public function actionContact()
{
    $model=new ContactForm;
    if(isset($_POST['ContactForm']))
    {
        $model->attributes=$_POST['ContactForm'];
        if($model->validate())
        {
            $name='=?UTF-8?B?'.base64_encode($model->name).'?=';
            $subject='=?UTF-8?B?'.base64_encode($model->subject).'?=';
            $headers="From: $name <{$model->email}>
".
                "Reply-To: {$model->email}
".
                "MIME-Version: 1.0
".
                "Content-Type: text/plain; charset=UTF-8";

            mail(Yii::app()->params['adminEmail'],$subject,$model->body,$headers);
            Yii::app()->user->setFlash('contact','Thank you for contacting us. We will respond to you as soon as possible.');
            $this->refresh();
        }
    }
    $this->render('contact',array('model'=>$model));
}


public function actionLogin()
{
        $form=new LoginForm;
        if(isset($_POST['LoginForm']))
        {
            $form->attributes=$_POST['LoginForm'];
            if($form->validate()  && $form->login()) $this->redirect(Yii::app()->user->returnUrl);
        }

            $this->render('login',array('form'=>$form));
}

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

}

herers the model

<?php

class LoginForm extends CFormModel

{
    public $email;
    public $password;


    private $_identity;

public function rules()
    {
        return array(
        array('email, password', 'required'),
        array('email', 'email'),
        array('password', 'authenticate'),
);
    }
public function attributeLabels()
{
            return array('email'=>'Email Address');
}
public function authenticate($attribute,$params)
{
            if(!$this->hasErrors())  // we only want to authenticate when no input errors
                {
                $identity=new UserIdentity($this->email,$this->password);
                $identity->authenticate();
                switch($identity->errorCode)
                {
                    case UserIdentity::ERROR_NONE:
                Yii::app()->user->login($identity);
                break;
                    case UserIdentity::ERROR_USERNAME_INVALID:
                $this->addError('email','Email address is incorrect.');
                break;
        default: // UserIdentity::ERROR_PASSWORD_INVALID
                $this->addError('password','Password is incorrect.');
                break;
                }
            }
    }
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;
}

}

here the view

<?php
/* @var $this SiteController */
/* @var $model LoginForm */
/* @var $form CActiveForm  */

$this->pageTitle=Yii::app()->name . ' - Login';
$this->breadcrumbs=array(
    'Login',
);
?>
<h1>Login</h1>

<p>Please fill out the following form with your login credentials:</p>

<div class="form">
<?php $myWidget=$this->beginWidget('CActiveForm', array(
    'id'=>'login-form',
    'enableClientValidation'=>true,
    'clientOptions'=>array(
        'validateOnSubmit'=>true,
    ),
)); ?>

    <p class="note">Fields with <span class="required">*</span> are required.</p>
<div>
    <?php echo CHtml::beginForm(); ?>

    <?php echo CHtml::errorSummary($form); ?>

    <div>
    <?php echo CHtml::activeLabel($form,'email'); ?>
    <?php echo CHtml::activeTextField($form,'email') ?>
    </div>

    <div>
    <?php echo CHtml::activeLabel($form,'password'); ?>
    <?php echo CHtml::activePasswordField($form,'password') ?>
    </div>

    <div>
    <?php echo CHtml::submitButton('Login'); ?>
    </div>

    <?php echo CHtml::endForm(); ?>

endWidget(); ?>

解决方案

You have to write your authentication logic inside UserIdentity class not in LoginForm model.

  1. LoginForm model ex:-

     public function authenticate($attribute, $params) {
        if (!$this->hasErrors()) {
           $this->_identity = new UserIdentity($this->email, $this->password);
           if (!$this->_identity->authenticate())
            $this->addError('password', 'Incorrect username or password.');
      }
    }
    
    public function login() {
    
      if ($this->_identity === null) {
          $this->_identity = new UserIdentity($this->email, $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;
    }
    

  2. For database authentication you must have to add your authetication logic inside authenticate function using componentsUserIdentity.php

    public function authenticate() {
    
    Yii::app()->getModule('auth')->getModule('user'); #import your module.
    
    $record = User::model()
            ->findByAttributes(array('email' => CHtml::encode($this->email))); #database call
    
    if ($record === null)
        $this->errorCode = self::ERROR_USERNAME_INVALID;
    #else if ($record->password !== crypt($this->password, $record->password))
    else if ($record->password !== $this->password)
        $this->errorCode = self::ERROR_PASSWORD_INVALID;
    else {
        $this->_uid = $record->user_id;
        $this->setState('title', $record->user_name);
        $this->setState('uid', $this->_uid);
        $this->errorCode = self::ERROR_NONE;
    }
    return !$this->errorCode;
    

    }

  3. If you have role based login then you have to add WebUser class in config/main.php.

    components' => array(
            'user' => array(
                // enable cookie-based authentication
                'class' => 'WebUser',
                'allowAutoLogin' => true,
                'loginUrl'=>array('/site/login'),
                'returnUrl'=>array('/site/index'),
            ),
    }
    

  4. For role based assess check you have to write componentsWebUser.php Class -

     class WebUser extends CWebUser {
    
    public function checkAccess($operation, $params = array()) {
        if (empty($this->id)) {
            // Not identified => no rights
            return false;
        }
        $role = $this->getState("roles");
        if ($role === '3') {            
            return true; // super admin role has access to everything
        }else if ($role === '1') {            
            return true; // admin(manager) role has access to everything
        }         
        // allow access if the operation request is the current user's role
        return ($operation === $role);
    }
    
    }
    

For more information check Authentication and Authorization

这篇关于Yii登录不接受正确的密码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
PHP最新文章
热门教程
热门工具
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆