Yii登录时不接受正确的密码 [英] Correct password is not accepted in Yii login
问题描述
您好,我是yii框架的新手,目前试图通过数据库身份验证建立登录。但是在尝试登录时,我收到此错误提示
请修复以下输入错误:
密码不正确。 / p>
但是当我检查数据库表时输入正确的密码。
< ;?php
类SiteController扩展控制器
{
public function actions()
{
return array b
$ b'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}> \r\\\
。
回复:{$ model->电子邮件} \r\\\
。
MIME-Version:1.0 \r\\\
。
Content-Type:text / plain; charset = UTF-8;
mail(Yii :: app() - > params ['adminEmail'],$ subject,$ model-> body,$ headers);
Yii :: app() - > user-> setFlash('contact','谢谢您与我们联系,我们会尽快回复您。
$ 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模型
<?php
类LoginForm扩展CFormModel
{
public $ email;
public $ password;
private $ _identity;
public function rules()
{
return array(
array('email,password','required'),
array ','email'),
array('password','authenticate'),
);
}
public function attributeLabels()
{
return array('email'=>'Email Address');
}
public function authenticate($ attribute,$ params)
{
if(!$ this-> hasErrors())//我们只想在没有输入错误
{
$ identity = new UserIdentity($ this-> email,$ this-> password);
$ identity-> authenticate();
switch($ identity-> errorCode)
{
case UserIdentity :: ERROR_NONE:
Yii :: app() - > user-> login ;
break;
case UserIdentity :: ERROR_USERNAME_INVALID:
$ this-> addError('email','电子邮件地址不正确。
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-& 3600 * 24 * 30:0; // 30 days
Yii :: app() - > user-> login($ this-> _identity,$ duration);
return true;
}
else
return false;
}
}
这里的视图
<?php
/ * @var $ this SiteController * /
/ * @var $ model LoginForm * /
/ * @var $ form CActiveForm * /
$ this-> pageTitle = Yii :: app() - > name。 ' - 登录';
$ this-> breadcrumbs = array(
'Login',
);
?>
< h1>登录< / h1>
< p>请使用您的登录凭据填写以下表单:< / p>
< div class =form>
<?php $ myWidget = $ this-> beginWidget('CActiveForm',array(
'id'=>'login-form',
'enableClientValidation'=& true,
'clientOptions'=> array(
'validateOnSubmit'=> true,
),
) ?>
< 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>
< 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(); ?>
您必须在UserIdentity类中不在LoginForm模型中写入您的认证逻辑。
-
LoginForm模型ex: -
public function authenticate($ attribute,$ params){
if(!$ this-> hasErrors()){
$ this-> _identity = new UserIdentity($ this-> email,$ this-> password);
if(!$ this-> _identity-> authenticate())
$ this-> addError('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;
}
-
对于数据库身份验证,您必须在authenticate函数使用
components\UserIdentity.php
{
Yii :: app() - > getModule('auth') - > getModule('user'); #import您的模块。
$ 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;
}
-
有基于角色的登录,那么你必须添加WebUser类在config / main.php。
components'=> array(
'user'=> array(
//启用基于Cookie的身份验证
'class'=>'WebUser',
'allowAutoLogin'=> true ,
'loginUrl'=> array('/ site / login'),
'returnUrl'=> array('/ site / index'),
),
}
-
对于基于角色的评估检查,您必须写
\WebUser.php
Class -class WebUser extends CWebUser {
public function checkAccess($ operation,$ params = array()){
if(empty($ this-> id)){
//未识别=>无权限
返回false;
}
$ role = $ this-> getState(roles);
if($ role ==='3'){
return true; // super admin role has access to everything
} else if($ role ==='1'){
return true; //管理员角色有访问权限
}
//如果操作请求是当前用户的角色,则允许访问
return($ 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}>\r\n".
"Reply-To: {$model->email}\r\n".
"MIME-Version: 1.0\r\n".
"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.
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; }
For database authentication you must have to add your authetication logic inside authenticate function using
components\UserIdentity.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;
}
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'), ), }
For role based assess check you have to write
components\WebUser.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屋!