Yii2 loginform无法正常工作

时间:2016-10-17 10:37:40

标签: php yii2

yii2中的Loginform无法正确验证密码。我输入了正确的密码但它说密码错误。 这是我的控制器     

use frontend\models\SignupForm;
use Yii;
use yii\base\InvalidParamException;
use yii\web\BadRequestHttpException;
use yii\web\Controller;
use yii\filters\VerbFilter;
use yii\filters\AccessControl;
use common\models\LoginForm;
use frontend\models\PasswordResetRequestForm;
use frontend\models\ResetPasswordForm;
use frontend\models\User;
use frontend\models\ContactForm;
use yii\widgets\ActiveForm;

/**
 * Site controller
 */
class SiteController extends Controller
{
    /**
     * @inheritdoc
     */
    public function behaviors()
    {
        return [
            'access' => [
                'class' => AccessControl::className(),
                'only' => ['logout', 'signup'],
                'rules' => [
                    [
                        'actions' => ['signup','language'],
                        'allow' => true,
                        'roles' => ['?'],
                    ],
                    [
                        'actions' => ['logout','set-cookie','show-cookie'],
                        'allow' => true,
                        'roles' => ['@'],
                    ],
                ],
            ],
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'logout' => ['post'],
                ],
            ],
        ];
    }

    /**
     * @inheritdoc
     */
    public function actions()
    {
        return [
            'error' => [
                'class' => 'yii\web\ErrorAction',
            ],
            'captcha' => [
                'class' => 'yii\captcha\CaptchaAction',
                'fixedVerifyCode' => YII_ENV_TEST ? 'testme' : null,
            ],
        ];
    }

    /**
     * Displays homepage.
     *
     * @return mixed
     */
    public function actionIndex()
    {
        return $this->render('index');
    }

    /**
     * Logs in a user.
     *
     * @return mixed
     */
    public function actionLogin()
    {
        if (!Yii::$app->user->isGuest) {
            return $this->goHome();
        }

        $model = new LoginForm();
        if ($model->load(Yii::$app->request->post()) && $model->login()) {
            return $this->goBack();
        } else {
            return $this->render('login', [
                'model' => $model,
            ]);
        }
    }

    /**
     * Logs out the current user.
     *
     * @return mixed
     */
    public function actionLogout()
    {
        Yii::$app->user->logout();

        return $this->goHome();
    }

    /**
     * Displays contact page.
     *
     * @return mixed
     */
    public function actionContact()
    {
        $model = new ContactForm();
        if ($model->load(Yii::$app->request->post()) && $model->validate()) {
            if ($model->sendEmail(Yii::$app->params['adminEmail'])) {
                Yii::$app->session->setFlash('success', 'Thank you for contacting us. We will respond to you as soon as possible.');
            } else {
                Yii::$app->session->setFlash('error', 'There was an error sending email.');
            }

            return $this->refresh();
        } else {
            return $this->render('contact', [
                'model' => $model,
            ]);
        }
    }

    /**
     * Displays about page.
     *
     * @return mixed
     */
    public function actionAbout()
    {
        return $this->render('about');
    }

    /**
     * Signs user up.
     *
     * @return mixed
     */
    public function actionSignup()
    {
        $model = new SignupForm();
        if ($model->load(Yii::$app->request->post())) {
            if ($user = $model->signup()) {
                if (Yii::$app->getUser()->login($user)) {
                    return $this->goHome();
                }
            }
        }

        return $this->render('signup', [
            'model' => $model,
        ]);
    }



    /**
     * Languages.
     */
    public function actionLanguage()
    {
        if(isset($_POST['lang'])){
            Yii::$app->language = $_POST['lang'];
            $cookie = new \yii\web\Cookie([
                'name' => 'lang',
                'value' => $_POST['lang']
            ]);

            Yii::$app->getResponse()->getCookies()->add($cookie);
        }
    }

    /**
     * Requests password reset.
     *
     * @return mixed
     */
    public function actionRequestPasswordReset()
    {
        $model = new PasswordResetRequestForm();
        if ($model->load(Yii::$app->request->post()) && $model->validate()) {
            if ($model->sendEmail()) {
                Yii::$app->session->setFlash('success', 'Check your email for further instructions.');

                return $this->goHome();
            } else {
                Yii::$app->session->setFlash('error', 'Sorry, we are unable to reset password for email provided.');
            }
        }

        return $this->render('requestPasswordResetToken', [
            'model' => $model,
        ]);
    }

    /**
     * Resets password.
     *
     * @param string $token
     * @return mixed
     * @throws BadRequestHttpException
     */
    public function actionResetPassword($token)
    {
        try {
            $model = new ResetPasswordForm($token);
        } catch (InvalidParamException $e) {
            throw new BadRequestHttpException($e->getMessage());
        }

        if ($model->load(Yii::$app->request->post()) && $model->validate() && $model->resetPassword()) {
            Yii::$app->session->setFlash('success', 'New password was saved.');

            return $this->goHome();
        }

        return $this->render('resetPassword', [
            'model' => $model,
        ]);
    }
}

这是我的模特

<?php
namespace common\models;

use Yii;
use yii\base\Model;

/**
 * Login form
 */
class LoginForm extends Model
{
    public $username;
    public $password;
    public $rememberMe = true;

    private $_user;


    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            // username and password are both required
            [['username', 'password'], 'required'],
            // rememberMe must be a boolean value
            ['rememberMe', 'boolean'],
            // password is validated by validatePassword()
            ['password', 'validatePassword'],
        ];
    }

    /**
     * Validates the password.
     * This method serves as the inline validation for password.
     *
     * @param string $attribute the attribute currently being validated
     * @param array $params the additional name-value pairs given in the rule
     */
    public function validatePassword($attribute, $params)
    {
        if (!$this->hasErrors()) {
            $user = $this->getUser();
            if (!$user || !$user->validatePassword($this->password)) {
                $this->addError($attribute, 'Incorrect username or password.');
            }
        }
    }

    /**
     * Logs in a user using the provided username and password.
     *
     * @return boolean whether the user is logged in successfully
     */
    public function login()
    {
        if ($this->validate()) {
            return Yii::$app->user->login($this->getUser(), $this->rememberMe ? 3600 * 24 * 30 : 0);
        } else {
            return false;
        }
    }

    /**
     * Finds user by [[username]]
     *
     * @return User|null
     */
    protected function getUser()
    {
        if ($this->_user === null) {
            $this->_user = User::findByUsername($this->username);
        }

        return $this->_user;
    }
}

我有注册和用户创建页面。当我使用注册用户的数据时就可以了,当我使用创建用户的数据时,一切都是错误的。

这是UserController,我认为此控制器的generatePasswordHash()函数actionCreate中的问题

<?php

namespace frontend\controllers;

use Yii;
use frontend\models\User;
use frontend\models\UserSearch;
use frontend\models\Schedule;
use frontend\models\Photo;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
use yii\widgets\ActiveForm;

/**
 * UserController implements the CRUD actions for User model.
 */
class UserController extends Controller
{
    /**
     * @inheritdoc
     */
    public function behaviors()
    {
        return [
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'delete' => ['POST'],
                ],
            ],
        ];
    }

    /**
     * Lists all User models.
     * @return mixed
     */
    public function actionIndex()
    {
        $searchModel = new UserSearch();
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);

        return $this->render('index', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
        ]);
    }

    /**
     * Displays a single User model.
     * @param integer $id
     * @return mixed
     */
    public function actionView($id)
    {
        return $this->render('view', [
            'model' => $this->findModel($id),
        ]);
    }

    /**
     * Creates a new User model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     * @return mixed
     */
    public function actionCreate()
    {
        $model = new User();
        $schedule = new Schedule();

        $pass = Yii::$app->request->post('password_hash');

        if ($model->load(Yii::$app->request->post()) && $schedule->load(Yii::$app->request->post()) && $schedule->save()) {
            $model->password_hash = Yii::$app->security->generatePasswordHash($model->password_hash);
            $model->auth_key = Yii::$app->security->generateRandomString();
            if ($model->save()) {

                $photoList = $_FILES['files']['name'];
                foreach ($photoList as $value) {
                    $newPhoto = new Photo;
                    $newPhoto->user_id = $model->id;
                    $newPhoto->photo = $value;
                    $newPhoto->save();
                }
            }

            return $this->redirect(['view', 'id' => $model->id]);
        } else {
            return $this->render('create', [
                'model' => $model,
                'schedule' => $schedule,
            ]);
        }
    }

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

        if(Yii::$app->request->isAjax && $model->load(Yii::$app->request->post()))
        {
            Yii::$app->response->format = 'json';
            return ActiveForm::validate($model);
        }
    }

    /**
     * Updates an existing User model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param integer $id
     * @return mixed
     */
    public function actionUpdate($id)
    {
        $model = User::findOne($id);
        if (!$model) {
            throw new NotFoundHttpException("The user was not found.");
        }

        $schedule = Schedule::findOne($model->id);

        if (!$schedule) {
            throw new NotFoundHttpException("Error");
        }

        if ($model->load(Yii::$app->request->post()) && $schedule->load(Yii::$app->request->post())) {
            $isValid = $model->validate();
            $isValid = $schedule->validate() && $isValid;
            if ($isValid) {
                $model->save(false);
                $schedule->save(false);
                return $this->redirect(['user/view', 'id' => $id]);
            }
        }

        return $this->render('update', [
            'model' => $model,
            'schedule' => $schedule,
        ]);
    }

    /**
     * Deletes an existing User model.
     * If deletion is successful, the browser will be redirected to the 'index' page.
     * @param integer $id
     * @return mixed
     */
    public function actionDelete($id)
    {
        $this->findModel($id)->delete();

        return $this->redirect(['index']);
    }

    /**
     * Finds the User model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param integer $id
     * @return User the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModel($id)
    {
        if (($model = User::findOne($id)) !== null) {
            return $model;
        } else {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
    }
}

查看文件

<?php

use yii\helpers\Html;
use yii\helpers\Url;
use yii\widgets\ActiveForm;
use yii\helpers\ArrayHelper;
use frontend\models\Countries;
use kartik\date\DatePicker;
use kartik\time\TimePicker;
use kartik\file\FileInput;

/* @var $this yii\web\View */
/* @var $model frontend\models\User */
/* @var $form yii\widgets\ActiveForm */
?>

<div class="user-form">

    <?php $form = ActiveForm::begin(['id' => $model->formName(), 'enableAjaxValidation' => true, 'validationUrl' => Url::toRoute('user/validation')]); ?>

    <?= $form->field($model, 'username')->textInput(['maxlength' => true]) ?>

    <?= $form->field($model, 'name')->textInput(['maxlength' => true]) ?>

    <?= $form->field($model, 'lastname')->textInput(['maxlength' => true]) ?>

    <?= $form->field($model, 'email')->textInput(['maxlength' => true]) ?>

    <?= $form->field($model, 'phone')->textInput() ?>

    <?= $form->field($model, 'notes')->textInput(['maxlength' => true]) ?>

    <?= $form->field($model, 'password_hash')->passwordInput(['maxlength' => true]) ?>


    <?= $form->field($model, 'country')->dropDownList(ArrayHelper::map(Countries::find()->all(),'id','name'),
        [
            'prompt' => 'Страна',
            'onchange' => '
                        $.post( "../states/lists?id='.'"+$(this).val(), function( data ) {
                        $( "select#user-state" ).html( data );
                        });'
        ]); ?>

    <?= $form->field($model, 'state')->dropDownList([],
        [
            'prompt' => 'Регион',
            'onchange' => '
                        $.post( "../cities/lists?id='.'"+$(this).val(), function( data ) {
                        $( "select#user-city" ).html( data );
                        });'
        ]); ?>

    <?= $form->field($model, 'city')->dropDownList([],[ 'prompt' => 'Город' ]); ?>


    <?= $form->field($model, 'salary')->textInput() ?>

    <?= $form->field($model, 'hiredate')->widget(DatePicker::classname(), [
        'options' => ['placeholder' => 'Enter hire date ...'],
        'pluginOptions' => [
            'autoclose'=>true,
            'format'=> 'yyyy-mm-dd'
        ]
    ]); ?>

    <?= $form->field($model, 'birthday')->widget(DatePicker::classname(), [
        'options' => ['placeholder' => 'Enter birthday ...'],
        'pluginOptions' => [
            'autoclose'=>true,
            'format'=> 'yyyy-mm-dd'
        ]
    ]); ?>

    <?= $form->field($model, 'address')->textInput(['maxlength' => true]) ?>




    <?= $form->field($schedule, 'monday_start')->widget(TimePicker::classname(), [
        'name' => 't1',
        'pluginOptions' => [
            'showSeconds' => true,
            'showMeridian' => false,
            'minuteStep' => 1,
            'secondStep' => 5,
        ]
    ]); ?>

    <?= $form->field($schedule, 'monday_end')->widget(TimePicker::classname(), [
        'name' => 't1',
        'pluginOptions' => [
            'showSeconds' => true,
            'showMeridian' => false,
            'minuteStep' => 1,
            'secondStep' => 5,
        ]
    ]); ?>

    <?= $form->field($schedule, 'tuesday_start')->widget(TimePicker::classname(), [
        'name' => 't1',
        'pluginOptions' => [
            'showSeconds' => true,
            'showMeridian' => false,
            'minuteStep' => 1,
            'secondStep' => 5,
        ]
    ]); ?>

    <?= $form->field($schedule, 'tuesday_end')->widget(TimePicker::classname(), [
        'name' => 't1',
        'pluginOptions' => [
            'showSeconds' => true,
            'showMeridian' => false,
            'minuteStep' => 1,
            'secondStep' => 5,
        ]
    ]); ?>

    <?= $form->field($schedule, 'wednesday_start')->widget(TimePicker::classname(), [
        'name' => 't1',
        'pluginOptions' => [
            'showSeconds' => true,
            'showMeridian' => false,
            'minuteStep' => 1,
            'secondStep' => 5,
        ]
    ]); ?>

    <?= $form->field($schedule, 'wednesday_end')->widget(TimePicker::classname(), [
        'name' => 't1',
        'pluginOptions' => [
            'showSeconds' => true,
            'showMeridian' => false,
            'minuteStep' => 1,
            'secondStep' => 5,
        ]
    ]); ?>

    <?= $form->field($schedule, 'thursday_start')->widget(TimePicker::classname(), [
        'name' => 't1',
        'pluginOptions' => [
            'showSeconds' => true,
            'showMeridian' => false,
            'minuteStep' => 1,
            'secondStep' => 5,
        ]
    ]); ?>

    <?= $form->field($schedule, 'thursday_end')->widget(TimePicker::classname(), [
        'name' => 't1',
        'pluginOptions' => [
            'showSeconds' => true,
            'showMeridian' => false,
            'minuteStep' => 1,
            'secondStep' => 5,
        ]
    ]); ?>

    <?= $form->field($schedule, 'friday_start')->widget(TimePicker::classname(), [
        'name' => 't1',
        'pluginOptions' => [
            'showSeconds' => true,
            'showMeridian' => false,
            'minuteStep' => 1,
            'secondStep' => 5,
        ]
    ]); ?>

    <?= $form->field($schedule, 'friday_end')->widget(TimePicker::classname(), [
        'name' => 't1',
        'pluginOptions' => [
            'showSeconds' => true,
            'showMeridian' => false,
            'minuteStep' => 1,
            'secondStep' => 5,
        ]
    ]); ?>

    <?= $form->field($schedule, 'saturday_start')->widget(TimePicker::classname(), [
        'name' => 't1',
        'pluginOptions' => [
            'showSeconds' => true,
            'showMeridian' => false,
            'minuteStep' => 1,
            'secondStep' => 5,
        ]
    ]); ?>

    <?= $form->field($schedule, 'saturday_end')->widget(TimePicker::classname(), [
        'name' => 't1',
        'pluginOptions' => [
            'showSeconds' => true,
            'showMeridian' => false,
            'minuteStep' => 1,
            'secondStep' => 5,
        ]
    ]); ?>

    <?= $form->field($schedule, 'sunday_start')->widget(TimePicker::classname(), [
        'name' => 't1',
        'pluginOptions' => [
            'showSeconds' => true,
            'showMeridian' => false,
            'minuteStep' => 1,
            'secondStep' => 5,
        ]
    ]); ?>

    <?= $form->field($schedule, 'sunday_end')->widget(TimePicker::classname(), [
        'name' => 't1',
        'pluginOptions' => [
            'showSeconds' => true,
            'showMeridian' => false,
            'minuteStep' => 1,
            'secondStep' => 5,
        ]
    ]); ?>



    <?= $form->field($model, 'dismission')->widget(DatePicker::classname(), [
        'options' => ['placeholder' => 'Enter dismission date ...'],
        'pluginOptions' => [
            'autoclose'=>true,
            'format'=> 'yyyy-mm-dd'
        ]
    ]); ?>

    <div class="cont">
      <div class="demo-gallery">
        <ul id="lightgallery">
          <li data-responsive="/bridalpro/frontend/web/uploads/dodge.jpg 375, /bridalpro/frontend/web/uploads/dodge.jpg 480, /frontend/web/uploads/dodge.jpg 800" data-src="/bridalpro/frontend/web/uploads/dodge.jpg"
          data-sub-html="<h4>Fading Light</h4><p>Classic view from Rigwood Jetty on Coniston Water an old archive shot similar to an old post but a little later on.</p>">
            <a href="">
              <img class="img-responsive" src="/bridalpro/frontend/web/uploads/dodge.jpg">
              <div class="demo-gallery-poster">
                <img src="/bridalpro/frontend/web/img/zoom.png">
              </div>
            </a>
            <div class="glyphicon glyphicon-trash gallery_delete" data-name="dodge.jpg"></div>
          </li>
        </ul>
      </div>
    </div>

    <div id="content">
        <input type="file" name="files[]" id="filer_input1" multiple="multiple">
    </div>

    <div id="content">
        <input type="file" name="files[]" id="filer_input2" multiple="multiple">
    </div>

    <div class="form-group">
        <?= Html::submitButton($model->isNewRecord ? 'Create' : 'Update', ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?>
    </div>

    <?php ActiveForm::end(); ?>

</div>

2 个答案:

答案 0 :(得分:0)

这个问题主要出在你的UserController。请查看actionCreate中的以下行:

    $pass = Yii::$app->request->post('password_hash');

    if ($model->load(Yii::$app->request->post()) && $schedule->load(Yii::$app->request->post()) && $schedule->save()) {
                $model->password_hash = Yii::$app->security->generatePasswordHash($model->password_hash);
.......

再看一下片段的最后一行:

$model->password_hash = Yii::$app->security->generatePasswordHash($model->password_hash);

不应该像上面那样,应该是:

$model->password_hash = Yii::$app->security->generatePasswordHash($pass);

答案 1 :(得分:0)

在您的用户模型中,您应该添加一个纯文本来请求密码,然后在控制器中对其进行哈希处理。

这是一个例子。

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

        if ($model->load(Yii::$app->request->post())) {
            $model->created_at = date('Y-m-d h:i:s');
            $model->setPassword($model->password);
            $model->generateAuthKey();
            $model->status = User::STATUS_ACTIVE;
            $model->save();
            return $this->redirect(['view', 'id' => $model->getPrimaryKey()]);
        } else {
            return $this->render('create', [
                'model' => $model,
            ]);
        }
    }

$ model-&gt; password是您在用户模型中手动添加的字段。