Yii2基本模板 - 如何从mysql数据库登录

时间:2014-12-06 17:15:27

标签: php yii login yii2

我尝试在Yii基本模板中实现User Model和LoginForm Model来验证用户登录。我创建了一个数据库并连接到它。作为表用户的数据库和名为username,password,authKey和acessToken的字段填充了值。从ActiveRecord扩展用户模型并实现\ yii \ web \ IdentityInterface,以使内置的Yii2功能完成其工作。还写了这个方法:

public static function tableName() { return 'user'; }

每次我尝试登录时都会抛出 - >用户名或密码不正确,来自LoginForm模型中的validatepassword()

这是我的代码:

LoginForm模型:

<?php

namespace app\models;

use Yii;
use yii\base\Model;

/**
 * LoginForm is the model behind the login form.
 */
class LoginForm extends Model
{
    public $username;
    public $password;
    public $rememberMe = true;

    private $_user = false;

    /**
     * @return array the validation rules.
     */
    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
     */
    public function getUser()
    {
        if ($this->_user === false) {
            $this->_user = User::findByUsername($this->username);
        }

        return $this->_user;
    }
}

...这是我的User.php模型:

<?php

namespace app\models;

use yii\db\ActiveRecord;

class User extends ActiveRecord implements \yii\web\IdentityInterface
{
    public $id;
    public $username;
    public $password;
    public $authKey;
    public $accessToken;

    public static function tableName() { return 'user'; }

       /**
     * @inheritdoc
     */
    public static function findIdentity($id) {
        $user = self::find()
                ->where([
                    "id" => $id
                ])
                ->one();
        if (!count($user)) {
            return null;
        }
        return new static($user);
    }

    /**
     * @inheritdoc
     */
    public static function findIdentityByAccessToken($token, $userType = null) {

        $user = self::find()
                ->where(["accessToken" => $token])
                ->one();
        if (!count($user)) {
            return null;
        }
        return new static($user);
    }

    /**
     * Finds user by username
     *
     * @param  string      $username
     * @return static|null
     */
    public static function findByUsername($username) {
        $user = self::find()
                ->where([
                    "username" => $username
                ])
                ->one();
        if (!count($user)) {
            return null;
        }
        return new static($user);
    }

    /**
     * @inheritdoc
     */
    public function getId() {
        return $this->id;
    }

    /**
     * @inheritdoc
     */
    public function getAuthKey() {
        return $this->authKey;
    }

    /**
     * @inheritdoc
     */
    public function validateAuthKey($authKey) {
        return $this->authKey === $authKey;
    }

    /**
     * Validates password
     *
     * @param  string  $password password to validate
     * @return boolean if password provided is valid for current user
     */
    public function validatePassword($password) {
        return $this->password === $password;
    }

}

我不知道我该怎么办,也许在验证密码或查找用户名方面存在问题,在Yii2调试中它显示正确连接到mysql数据库。

不要使用siteController actionLogin(),因为它等同于高级模板,我认为保持这种方式是正确的。

简而言之,以下功能不断抛出&#34;不正确的用户名或密码。&#34;:

public function validatePassword($attribute, $params)
{
    if (!$this->hasErrors()) {
        $user = $this->getUser();

        if (!$user || !$user->validatePassword($this->password)) {
            $this->addError($attribute, 'Incorrect username or password.');
        }
    }
}

我不想放弃,但我考虑回到旧的Yii1.xx.在那里,我可以轻松地查询数据库并使一个良好的登录系统正常工作。

我花了将近72个小时来解决此登录问题,并且没有解决方案解决了基本的Yii2模板。

我不想使用默认包中的静态$users

编辑2
siteController.php

<?php

namespace app\controllers;

use Yii;
use yii\filters\AccessControl;
use yii\web\Controller;
use yii\filters\VerbFilter;
use app\models\LoginForm;
use app\models\ContactForm;
use yii\helpers\url;

class SiteController extends Controller
{
    public function behaviors()
    {
        return [
            'access' => [
                'class' => AccessControl::className(),
                'only' => ['logout'],
                'rules' => [
                    [
                        'actions' => ['logout'],
                        'allow' => true,
                        'roles' => ['@'],
                    ],
                ],
            ],
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'logout' => ['post'],
                ],
            ],
        ];
    }

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

    public function actionIndex()
    {
        return $this->render('index');
    }

    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->redirect(Url::toRoute(['contacto/index'])); 
        } else {
            return $this->render('login', [
                'model' => $model,
            ]);
        }
    }

    public function actionLogout()
    {
        Yii::$app->user->logout();

        return $this->goHome();
    }

    public function actionContact()
    {
        $model = new ContactForm();
        if ($model->load(Yii::$app->request->post()) && $model->contact(Yii::$app->params['adminEmail'])) {
            Yii::$app->session->setFlash('contactFormSubmitted');

            return $this->refresh();
        } else {

                return $this->redirect(Url::toRoute(['contacto/create2']));
        }
    }

    public function actionAbout()
    {
        return $this->render('about');
    }

    public function actionSkills()
    {
        return $this->render('skills');
    }

    public function actionPortfolio()
    {
        return $this->render('portfolio');
    }

    // tradução do site
    public function beforeAction($action) {
        if (Yii::$app->session->has('lang')) {
            Yii::$app->language = Yii::$app->session->get('lang');
        } else {
            Yii::$app->language = 'us';
        }
        return parent::beforeAction($action);
    }

    public function actionLangus(){  
        Yii::$app->session->set('lang', 'us'); //or $_GET['lang']
        return $this->redirect(Url::toRoute(['site/index']));   
    }

    public function actionLangpt(){  
        Yii::$app->session->set('lang', 'pt'); //or $_GET['lang']
        return $this->redirect(Url::toRoute(['site/index']));
    }
}

1 个答案:

答案 0 :(得分:2)

1)停止创建重复的问题 2)删除变量的公共声明。

class User extends ActiveRecord implements \yii\web\IdentityInterface
{
public $id;
public $username;
public $password;
public $authKey;
public $accessToken;
因此,

$ user-&gt;密码将为空。而不是使用魔术方法来获取实际上声明它们的值......当你使用它们时它们将永远是空的。