Hello friends
I need create a simple login using data base, so I changed my User model and LoginForm model, I don’t receive error message but I can’t login, I receive the message:
Incorrect user or password.
in my table i have this fields and values to test:
username: bb
password: 123
auth_key: 123
I put the values directly in table, I don’t create a action to input data in this moment.
I’m using this tutorial:
http://www.bsourcecode.com/yiiframework2/yii-2-user-login-from-database/#change-sitecontroller
Whats my error?
This is my model:
<?php
namespace app\models;
use Yii;
use yii\base\NotSupportedException;
use yii\db\ActiveRecord;
use yii\helpers\Security;
use yii\web\IdentityInterface;
class User extends \yii\db\ActiveRecord implements IdentityInterface
{
public static function tableName()
{
return 'tb_users';
}
public function rules()
{
return [
[['name', 'username', 'password', 'email', 'level', 'created_at', 'id_user','auth_key'], 'required'],
[['created_at', 'updated_at'], 'safe'],
[['modified', 'status', 'id_user'], 'integer'],
[['name', 'username', 'password', 'email', 'level','password_reset_token'], 'string', 'max' => 250]
];
}
public function attributeLabels()
{
return [
'id' => 'ID',
'name' => 'Name',
'username' => 'User',
'password' => 'Password',
'email' => 'Email',
'level' => 'Level',
'created_at' => 'Created At',
'updated_at' => 'Updated At',
'modified' => 'Modified',
'status' => 'Status',
'id_user' => 'Id User',
];
}
public function getAuthKey() {
return $this->auth_key;
}
public function getId() {
return $this->getPrimaryKey();
}
public function validateAuthKey($authKey) {
return $this->getAuthKey() === $authKey;
}
public static function findIdentity($id) {
return static::findOne($id);
}
public static function findIdentityByAccessToken($token, $type = null) {
return static::findOne(['access_token' => $token]);
}
public static function findByUsername($username)
{
return static::findOne(['username' => $username]);
}
public static function findByPasswordResetToken($token)
{
$expire = \Yii::$app->params['user.passwordResetTokenExpire'];
$parts = explode('_', $token);
$timestamp = (int) end($parts);
if ($timestamp + $expire < time()) {
// token expired
return null;
}
return static::findOne([
'password_reset_token' => $token
]);
}
public function validatePassword($password)
{
return $this->password === sha1($password);
}
public function setPassword($password)
{
$this->password_hash = Security::generatePasswordHash($password);
}
public function generateAuthKey()
{
$this->auth_key = Security::generateRandomKey();
}
public function generatePasswordResetToken()
{
$this->password_reset_token = Security::generateRandomKey() . '_' . time();
}
public function removePasswordResetToken()
{
$this->password_reset_token = null;
}
}
My LoginForm:
<?php
namespace app\models;
use Yii;
use yii\base\Model;
class LoginForm extends Model
{
public $username;
public $password;
public $rememberMe = true;
private $_user = false;
public function rules()
{
return [
// user and password are both required
[['username', 'password'], 'required'],
// rememberMe must be a boolean value
['rememberMe', 'boolean'],
// password is validated by validatePassword()
['password', 'validatePassword'],
];
}
public function validatePassword($attribute, $params)
{
if (!$this->hasErrors()) {
$username = $this->getUser();
if (!$username || !$username->validatePassword($this->password)) {
$this->addError($attribute, 'Incorrect user or password.');
}
}
}
public function login()
{
if ($this->validate()) {
return Yii::$app->user->login($this->getUser(), $this->rememberMe ? 3600*24*30 : 0);
} else {
return false;
}
}
public function getUser()
{
if ($this->_user === false) {
$this->_user = User::findByUsername($this->username);
}
return $this->_user;
}
}
My SiteController
<?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;
class SiteController extends Controller
{
public $layout='adm/default';
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');
return $this->redirect('index.php?r=site/login');
}
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,
]);
}
}
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->render('contact', [
'model' => $model,
]);
}
}
public function actionAbout()
{
return $this->render('about');
}
}