Yii2 authentication - php

I'm modifying the User.php model from the basic installation.
This is what I have now:
<?php
namespace app\models;
use yii\db\ActiveRecord;
class User extends ActiveRecord implements \yii\web\IdentityInterface
{
public $id;
public $username;
public $password;
/**
* #inheritdoc
*/
public static function tableName()
{
return 'user';
}
/**
* #inheritdoc
*/
public static function findIdentity($id)
{
return isset(self::$users[$id]) ? new static(self::$users[$id]) : null;
}
/**
* #inheritdoc
*/
public static function findIdentityByAccessToken($token, $type = null)
{
return null;
}
/**
* Finds user by username
*
* #param string $username
* #return static|null
*/
public static function findByUsername($username)
{
return static::findOne(['username' => $username]);
}
/**
* #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 === \Yii::$app->getSecurity()->generatePasswordHash($password);
}
}
The LoginForm.php is calling it in:
public function getUser()
{
if ($this->_user === false) {
$this->_user = User::findByUsername($this->username);
}
return $this->_user;
}
The problem I have is, when the program reaches validatePassword of User.php, $this->password is always null and validation fails.
I am sure that the record is found as I can see the values in LoginForm.php's $this->_user. Else it'll be null when I tried to find some random user.
How can I populate User.php's $this->password with the one found in the static function?

You don't have do define attributes ('id', 'username', 'password') that are already stored in User db table. As a matter of fact you are redefining your database values with null here.
Also change validatePassword to
/**
* Validates password
*
* #param string $password password to validate
* #return boolean if password provided is valid for current user
*/
public function validatePassword($password)
{
return \Yii::$app->getSecurity()->validatePassword($password, $this->password);
}

Related

error-Call to a member function validatePassword() on null in Yii framework

I'm new in this framework actually this is my first time to use framework
Can someone help me on this error I don't know how to fix this error? here is my code:
The problem- Call to a member function validatePassword() on null
the actual problem I am getting here
public function validatePassword($attribute, $params)
{
//in loginForm.php file model
loginForm.php model
namespace app\models;
use Yii;
use yii\base\Model;
/**
* LoginForm is the model behind the login form.
*
* #property User|null $user This property is read-only.
*
*/
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();
echo"<pre>";
if (!$user || !$user->validatePassword($this->password)) {
$this->addError($attribute, 'Incorrect username or password.');
}
}
}
/**
* Logs in a user using the provided username and password.
* #return bool 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);
}
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;
}
}
I am unable to find out what the exact cause of error.
this is user.php model file
<?php
namespace app\models;
class User extends \yii\base\Object implements \yii\web\IdentityInterface
{
public $id;
public $username;
public $password;
public $admin_email;
public $authKey;
public $accessToken;
public static function tableName()
{
return 'admin_info';
}
/**
* #inheritdoc
*/
public function rules()
{
return [
#[['username', 'admin_email', 'password'], 'required'],
[['username','password'],'required'],
[['username', 'password'], 'string', 'max' => 20],
[['admin_email'], 'string', 'max' => 50],
['admin_email','email'],
['password','password'],
];
}
/**
* #inheritdoc
*/
public function attributeLabels()
{
return [
'admin_id' => 'Admin ID',
'username' => 'Username',
'admin_email' => 'Admin Email',
'password' => 'Password',
];
}
/**
* #inheritdoc
*/
public static function findIdentity($id)
{
return isset(self::$users[$id]) ? new static(self::$users[$id]) : null;
}
/**
* #inheritdoc
*/
public static function findIdentityByAccessToken($token, $type = null)
{
foreach (self::$users as $user) {
if ($user['accessToken'] === $token) {
return new static($user);
}
}
return null;
}
/**
* Finds user by username
*
* #param string $username
* #return static|null
*/
public static function findByUsername($username)
{
foreach (self::$users as $user) {
if (strcasecmp($user['username'], $username) === 0) {
return new static($user);
}
}
return null;
}
/**
* #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 bool if password provided is valid for current user
*/
public function validatePassword($password)
{
return $this->password === $password;
}
public static function findByUsername($username){
return static::findOne(['username' => $username]);
}
}
Yii2 has an excellent debugger, but you have to be in the dev environment to use it so from a command line, so cd to the root of your project run php init-dev.
Whether in your controller or for example in loginForm.php temporarily place
Yii::info('password is:' . $this->passwrod); in the validatePassword() function to ensure you are getting the expected output.
Now attempt your login and review the log for your critical info:
If nothing there, maybe add more info logging at previous touchpoints.
Remember to not use debug in your production environment and to remove your debugging code.

Yii2 Authentication fails

Today i came across with a probleme in Yii2 Authentication. I implemented succesfully but when i try to log in every time it shows me the following error:
After i refresh the page 1 or 2 times the error goes off and everything works properly. My first tought was to add the database field auth_key (32) varchar but it didn't solved the issue.
Here is my User.php:
<?php
namespace app\models;
use yii\base\NotSupportedException;
use yii\db\ActiveRecord;
use yii\helpers\Security;
use yii\web\IdentityInterface;
class User extends ActiveRecord implements \yii\web\IdentityInterface
{
/**
* #inheritdoc
*/
public static function tableName()
{
return 'felhasznalo';
}
/**
* #inheritdoc
*/
public static function findIdentity($id)
{
return static::findOne($id);
}
/**
* #inheritdoc
*/
public static function findIdentityByAccessToken($token, $type = null)
{
return static::findOne(['access_token' => $token]);
}
/**
* Finds user by username
*
* #param string $username
* #return static|null
*/
public static function findByFelhasznalonev($felhasznalonev)
{
return static::findOne(['felhasznalonev' => $felhasznalonev]);
}
/**
* #inheritdoc
*/
public function getId()
{
return $this->getPrimaryKey();
}
/**
* #inheritdoc
*/
public function getAuthKey()
{
return $this->auth_Key;
}
/**
* Generates "remember me" authentication key
*/
public function generateAuthKey()
{
$this->auth_key = Yii::$app->security->generateRandomString();
}
/**
* #inheritdoc
*/
public function validateAuthKey($authKey)
{
return $this->auth_Key === $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->jelszo === sha1($password);
}
}
The login action:
public function actionLogin()
{
if (!\Yii::$app->user->isGuest) {
if (empty($_SESSION['ablak_id'])) {
$_SESSION['ablak_id'] = Yii::$app->request->post('a_id');
}
else {
return $this->redirect(Url::to(['ugyfelhivo/muszerfal/' . $_SESSION['ablak_id']]));
}
}
$model = new LoginForm();
if ($model->load(Yii::$app->request->post()) && $model->login()) {
$session = Yii::$app->session;
$session->set('ablak_id', Yii::$app->request->post('ablak_id'));
return $this->redirect(Url::to(['ugyfelhivo/muszerfal/' . $_SESSION['ablak_id']]));
}
//Lekérdezzük az elérhető rendelők nevét majde elküldjük kimenetre
$ablakok = Ablak::find()->all();
return $this->render('login', [
'model' => $model,
'ablakok' => $ablakok,
]);
}
And the LoginForm.php:
<?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);
}
return false;
}
/**
* Finds user by [[username]]
*
* #return User|null
*/
public function getUser()
{
if ($this->_user === false) {
$this->_user = User::findByFelhasznalonev($this->username);
}
return $this->_user;
}
}
This is the table structure for the users table(felhasznalok == users in hungary)
Any ideas for the problem?
Thank your for Your answers!
Gábor
It is simply a typo, you should use auth_key instead of auth_Key :
public function validateAuthKey($authKey)
{
return $this->auth_key === $authKey;
}
try changing the getUser function in your LoginForm into:
public function getUser()
{
if ($this->_user === false) {
$this->_user = User::findByFelhasznalonev($this->username);
//generate auth_key for a new created User
$this->_user->generateAuthKey();
}
return $this->_user;
}

Yii2 user model with relational tables

I'm new to Yii and I have problem with its User and login system .
I should use 3 tables for login check but when I use custom query I face
"Argument 1 passed to yii\web\User::login() must implement interface yii\web\IdentityInterface, ActiveQuery given"
my tables are like :
user : user_id, name, family, birthday, ...
email : email_user_fk, email_addr, email_active, email_cdt
passwd : passwd_user_fk, passwd_hashed, passwd_active, passwd_cdt
and my query is like :
SELECT
user.user_id, email.email_addr, email.email_active,
passwd.passwd_hashed, passwd_passwd_active , ...
FROM user
JOIN email ON user.user_id = email.email_user_fk
JOIN passwd ON user.user_id = passwd.passwd_user_fk
WHERE
email.email_addr = :email
Is there any Idea ,Please ??
class User extends ActiveRecord implements IdentityInterface
{
const STATUS_DELETED = 0;
const STATUS_ACTIVE = 10;
/**
* #inheritdoc
*/
public static function tableName()
{
return 'user';
}
public static function primaryKey(){
return 'user_id';
}
/**
* #inheritdoc
*/
public function behaviors()
{
return [
TimestampBehavior::className(),
];
}
/**
* #inheritdoc
*/
public static function find
Identity($id)
{
return static::findOne(['id' => $id, 'status' => self::STATUS_ACTIVE]);
}
/**
* #inheritdoc
*/
public static function findIdentityByAccessToken($token, $type = null)
{
throw new NotSupportedException('"findIdentityByAccessToken" is not implemented.');
}
/**
* Finds user by username
*
* #param string $username
* #return static|null
*/
public static function findByUsername($username)
{
return static::findOne(['email' => $username]);
}
public static function findByEmail($email)
{
return User::find()
->joinWith(['emails'])
->where("email.email_address = 'me#mail.com' ")
->one();
}
public static function findByMobile($email)
{
return User::find()
->joinWith(['mobiles'])
->where("mobile.mobile_address = '0931515124' ")
->one();
}
/**
* Finds user by password reset token
*
* #param string $token password reset token
* #return static|null
*/
public static function findByPasswordResetToken($token)
{
if (!static::isPasswordResetTokenValid($token)) {
return null;
}
return static::findOne([
'password_reset_token' => $token,
'status' => self::STATUS_ACTIVE,
]);
}
/**
* Finds out if password reset token is valid
*
* #param string $token password reset token
* #return boolean
*/
public static function isPasswordResetTokenValid($token)
{
if (empty($token)) {
return false;
}
$expire = Yii::$app->params['user.passwordResetTokenExpire'];
$parts = explode('_', $token);
$timestamp = (int) end($parts);
return $timestamp + $expire >= time();
}
/**
* #inheritdoc
*/
public function getId()
{
return $this->getPrimaryKey();
}
/**
* #inheritdoc
*/
public function getAuthKey()
{
return $this->auth_key;
}
/**
* #inheritdoc
*/
public function validateAuthKey($authKey)
{
return $this->getAuthKey() === $authKey;
}
/**
* Validates password
*
* #param string $password password to validate
* #return boolean if password provided is valid for current user
*/
public function validatePassword($password)
{
return Yii::$app->security->validatePassword($password, $this->password_hash);
}
/**
* Generates password hash from password and sets it to the model
*
* #param string $password
*/
public function setPassword($password)
{
$this->password_hash = Yii::$app->security->generatePasswordHash($password);
}
/**
* Generates "remember me" authentication key
*/
public function generateAuthKey()
{
$this->auth_key = Yii::$app->security->generateRandomString();
}
/**
* Generates new password reset token
*/
public function generatePasswordResetToken()
{
$this->password_reset_token = Yii::$app->security->generateRandomString() . '_' . time();
}
/**
* Removes password reset token
*/
public function removePasswordResetToken()
{
$this->password_reset_token = null;
}
public function rules()
{
return [
[['user_name', 'user_family', 'user_birthday'], 'required'],
[['user_gender', 'city_id_fk', 'user_status'], 'integer'],
[['user_birthday', 'user_cdt'], 'safe'],
[['user_name'], 'string', 'max' => 32],
[['user_family'], 'string', 'max' => 48],
[['user_tel', 'user_postcode'], 'string', 'max' => 12],
[['user_address'], 'string', 'max' => 128],
[['user_profile_image', 'user_cover_image'], 'string', 'max' => 256]
];
}
/**
* #return \yii\db\ActiveQuery
*/
public function getEmails()
{
return $this->hasMany(Email::className(), ['email_user_id_fk' => 'user_id']);
}
/**
* #return \yii\db\ActiveQuery
*/
public function getMobiles()
{
return $this->hasMany(Mobile::className(), ['mobile_user_id_fk' => 'user_id']);
}
/**
* #return \yii\db\ActiveQuery
*/
public function getPasswds()
{
return $this->hasMany(Passwd::className(), ['passwd_user_id_fk' => 'user_id']);
}
}
What this error is showing is that when you execute Yii::$app->user->login() at some point you must pass a User object that implements identity interface as a parameter (and it seems you are passing another type of object).
What this method does is allow you to save the information from the user after logging. First the user provides a username, then it has to retrieve info for this username from the database and instatiate a user object with this info. This is the object that you have to pass to the Yii::$app->user->login() function.
Read about the User class here.
and find a good sample here.

Yii 2.0 login from database not working

Right i am working on yii 2.0 trying to amend the login system. It works when the users are just a hand coded array. Instead i want to make this work from a database.
I will show you what the initial Model looks like:
<?php
namespace app\models;
class User extends \yii\base\Object implements \yii\web\IdentityInterface
{
public $id;
public $username;
public $password;
public $authKey;
public $accessToken;
private static $users = [
'100' => [
'id' => '100',
'username' => 'admin',
'password' => 'admin',
'authKey' => 'test100key',
'accessToken' => '100-token',
],
'101' => [
'id' => '101',
'username' => 'demo',
'password' => 'demo',
'authKey' => 'test101key',
'accessToken' => '101-token',
],
];
/**
* #inheritdoc
*/
public static function findIdentity($id)
{
return isset(self::$users[$id]) ? new static(self::$users[$id]) : null;
}
/**
* #inheritdoc
*/
public static function findIdentityByAccessToken($token, $type = null)
{
foreach (self::$users as $user) {
if ($user['accessToken'] === $token) {
return new static($user);
}
}
return null;
}
/**
* Finds user by username
*
* #param string $username
* #return static|null
*/
public static function findByUsername($username)
{
foreach (self::$users as $user) {
if (strcasecmp($user['username'], $username) === 0) {
return new static($user);
}
}
return null;
}
/**
* #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;
}
}
okay so as you can see it is working on the hand coded array called $users. So i have made a table called "Users" and made the columns id username password authkey and accessToken.
Hoping that it would do the same thing with a database table, however i am getting an error when i try to log in. This is my new code
<?php
namespace app\models;
/**
* This is the model class for table "Cases".
*
* #property integer $id
* #property string $username
* #property string $password
* #property string $authkey
* #property string $accessToken
*/
class User extends \yii\db\ActiveRecord
{
/**
* #inheritdoc
*/
public static function tableName()
{
return 'users';
}
public function rules()
{
return [
[['id','username','password','authkey','accessToken'], 'required'],
[['id'], 'integer'],
];
}
/**
* #inheritdoc
*/
public function attributeLabels()
{
return [
'id' => 'id',
'username' => 'username',
'password' => 'password',
'authkey' => 'authkey',
'accessToken' => 'accessToken',
];
}
/**
* #inheritdoc
*/
public static function findIdentity($id)
{
return isset(self::$users[$id]) ? new static(self::$users[$id]) : null;
}
/**
* #inheritdoc
*/
public static function findIdentityByAccessToken($token, $type = null)
{
foreach (self::$users as $user) {
if ($user['accessToken'] === $token) {
return new static($user);
}
}
return null;
}
/**
* Finds user by username
*
* #param string $username
* #return static|null
*/
public static function findByUsername($username)
{
foreach (self::$Users as $user) {
if (strcasecmp($user['username'], $username) === 0) {
return new static($user);
}
}
return null;
}
/**
* #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;
}
}
The error message i am getting when i try to log in is "Access to undeclared static property: app\models\User::$Users".
If you need to see my LoginForm Model and Controller action i will post them underneath here.
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,
]);
}
}
and LoginForm model is:
<?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;
}
}
Can any one advise what i should do , once again the error i get is:
Access to undeclared static property: app\models\User::$Users
and this error corresponds to this section of code
foreach (self::$Users as $user) {
if (strcasecmp($user['username'], $username) === 0) {
return new static($user);
}
}
In your new User class change this methods:
public static function findIdentity($id)
{
return static::findOne(['id' => $id, 'status' => self::STATUS_ACTIVE]);
}
/**
* #inheritdoc
*/
public static function findIdentityByAccessToken($token, $type = null)
{
throw new NotSupportedException('"findIdentityByAccessToken" is not implemented.');
}
/**
* Finds user by username
*
* #param string $username
* #return static|null
*/
public static function findByUsername($username)
{
return static::findOne(['username' => $username, 'status' => self::STATUS_ACTIVE]);
}
See more in Yii2 Advanced template - https://github.com/yiisoft/yii2-app-advanced/blob/master/common/models/User.php#L61
Or take this class(from Yii2 Advanced template) in your app.
Use one Object for User Model instead your three different objects.
class User extends ActiveRecord implements IdentityInterface
{
const LOGIN_SCENARIO = 'login';
const CREATE_SCENARIO = 'create';
const UPDATE_SCENARIO = 'update';
/**
* Table name
*
* #return string
*/
public static function tableName()
{
return 'user';
}
/**
* Primary key
*/
public static function primaryKey()
{
return ['id'];
}
/**
* Set attribute labels
*
* #return array
*/
public function attributeLabels()
{
return [
'login' => Yii::t('app', 'Login'),
'password' => Yii::t('app', 'Password')
];
}
/**
* Rules
*
* #return array
*/
public function rules()
{
return [
[
[
'login',
'password'
],
'required',
'on' => self::LOGIN_SCENARIO
],
[
'password',
'validatePassword',
'on' => self::LOGIN_SCENARIO
],
[
[
'role',
'login',
'confirm',
'password',
],
'required',
'on' => self::CREATE_SCENARIO
],
[
[
'role',
'login',
],
'required',
'on' => self::UPDATE_SCENARIO
],
[
[
'name',
'status',
'password',
'create_dt',
'update_dt'
],
'safe',
],
];
}
/**
* Password validation
*/
public function validatePassword($attribute)
{
// Validate pass
}
/**
* #param null $id
*
* #return bool|mixed
*/
public function saveUser($id = null)
{
/** #var self $user */
$user = $this->findIdentity($id) ? $this->findIdentity($id) : $this;
$user->setScenario($this->scenario);
// Make Save
}
/**
* #param $id
*
* #throws \Exception
*/
public function deleteUser($id)
{
/** #var self $user */
if($user = $this->findIdentity($id)) {
// Make Delete
}
}
/**
* Finds an identity by the given ID.
*
* #param string|integer $id the ID to be looked for
*
* #return IdentityInterface the identity object that matches the given ID.
* Null should be returned if such an identity cannot be found
* or the identity is not in an active state (disabled, deleted, etc.)
*/
public static function findIdentity($id)
{
return static::findOne($id);
}
/**
* Returns an ID that can uniquely identify a user identity.
* #return string|integer an ID that uniquely identifies a user identity.
*/
public function getId()
{
return $this->getPrimaryKey();
}
}
And one User Model working with users, with different scenarios, can create, delete, make login etc.
And at html, for login form, put code like this:
<?php $model = new namespace\User() ?>
<?php $form = ActiveForm::begin(); ?>
<?= $form->field($model, 'login') ?>
<?= $form->field($model, 'password')->passwordInput() ?>
And for login, in controller, put code like this:
/**
* Login action
*
* #return mixed
*/
public function actionLogin()
{
$user = new namespace\User();
$user->setScenario(namespace\User::LOGIN_SCENARIO);
$user->load(Yii::$app->request->post());
if($user->validate()) {
// Make Login
return true;
}
return false;
}

yii2 login always return false

I am trying to implement login function with database using Yii 2.0. I have tried for 3 days but it still not working. What did i do wrong?
Here is my user and loginform class
loginform.php
<?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;
use yii\base\NotSupportedException;
use yii\helpers\Security;
use yii\web\IdentityInterface;
class User extends \yii\db\ActiveRecord implements \yii\web\IdentityInterface
{
public static function tableName()
{
return 'usys.usex';
}
public function rules()
{
return [
[['passwd', 'user_name'], 'required'],
[['user_type_uid', 'user_status_uid', 'msisdn', 'passwd_strength', 'banned', 'created'], 'integer']
];
}
public function attributeLabels()
{
return [
'usex_uid' => 'User id',
'username' => 'Username',
'password' => 'Password'
];
}
/**
* #inheritdoc
*/
public static function findIdentity($id)
{
return isset(self::$users[$id]) ? new static(self::$users[$id]) : null;
}
/**
* #inheritdoc
*/
public static function findIdentityByAccessToken($token, $type = null)
{
foreach (self::$users as $user) {
if ($user['accessToken'] === $token) {
return new static($user);
}
}
return null;
}
/**
* Finds user by username
*
* #param string $username
* #return static|null
*/
public static function findByUsername($username) {
$user = self::find()
->where(["user_uid" => $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;
}
}
I try to trace validation function to validateAnswer but when i tried to print $this->password it doesn't have any value.
Anyone has a clue?

Categories