Yii2 basic validate password - yii2

on my users controller I create to use it like registration, I create
public function actionCreate()
{
$model = new Userlogin();
$model->password = null;
if ($model->load(Yii::$app->request->post()) ) {
$model->password = Yii::$app->getSecurity()->generatePasswordHash($model->password);
$model->save();
return $this->redirect(['view', 'id' => $model->uid]);
} else {
return $this->render('create', [
'model' => $model,
]);
}
}
It's work , it hash the password , but I don't know how to validate the password and make it work in login I did read that I have to use this
if (Yii::$app->getSecurity()->validatePassword($password, $hash)) {
// all good, logging user in
} else {
// wrong password
}
but I don't know how to use it or where I have to use it

create new action , name it login
be sure to get user hash password from db
public function actionLogin() {
$hash = User::find()->where('username='.$_POST['username'])->One();
if (Yii::$app->getSecurity()->validatePassword($_POST['password'], $hash->password_hash)) {
// all good, logging user in
} else {
// wrong password
}
}

I found the solution for someone if he is in the same situation
in create action
public function actionCreate()
{
$model = new Userlogin();
if ($model->load(Yii::$app->request->post()) ) {
$model->password = Yii::$app->security->generatePasswordHash($model->password);
$model->save();
return $this->redirect(['view', 'id' => $model->uid]);
} else {
return $this->render('create', [
'model' => $model,
]);
}
}
and in user model change
/**
* 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;
}
to
/**
* Validates password
*
* #param string $password password to validate
* #return bool if password provided is valid for current user
*/
public function validatePassword($password)
{
return Yii::$app->getSecurity()->validatePassword($password, $this->password);
}
this solution from : https://stackoverflow.com/a/29508651/6562828
I'm using Userlogin as model for user but if anyone is using User model it's in user model

IMHO, the code :
if (Yii::$app->getSecurity()->validatePassword($password, $hash)) {
// all good, logging user in
} else {
// wrong password
}
can be used for POST method when user do login, and inside "// all good, logging user in", you will do something with Web Session, saving session for specify user, then yay, user logged in,
after that, you can use Session for checking, "is user are logged in ?", etc,
here some good link about Yii Session Handling : http://www.yiiframework.com/doc-2.0/guide-runtime-sessions-cookies.html

Related

Login access not working in yii2

Im using yii2 for my project. I need to use two different tables for login (Login page is same). I have two models Admin and User. And i have one LoginFrom for login.
I can login properly but the problem is after logged in i cannot get whether the admin is logged in or the user is logged in.
I have set it in config file (web.php) like below:
'admin' => [
'identityClass' => 'app\models\Admin',
'enableAutoLogin' => false,
'class' => 'yii\web\User',
'authTimeout' => 1200, // in Seconds. 1200 seconds means 20 mins
],
'user' => [
'identityClass' => 'app\models\User',
'enableAutoLogin' => false,
'authTimeout' => 1200
],
So im getting logged in user details by using below method:
\Yii::$app->admin->identity;
\Yii::$app->user->identity;
My problem is if im logged in as admin i can get user values also by using this : \Yii::$app->user->identity; or if im logged in as user i can get admin values by using this : \Yii::$app->admin->identity;.
My LoginForm.php is :
<?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 [
// username 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()) {
$user = $this->getUser();
if (!$user || !$user->validatePassword($this->password)) {
$this->addError($attribute, 'Incorrect username or password.');
}
}
}
public function login()
{
if ($this->validate()) {
if(!empty($this->getUser()['phone_number'])) {
return Yii::$app->admin->login($this->getUser(), $this->rememberMe ? 3600*24*30 : 0);
} else {
return Yii::$app->user->login($this->getUser(), $this->rememberMe ? 3600*24*30 : 0);
}
}
return false;
}
public function getUser()
{
if ($this->_user === false) {
$this->_user = User::findByUsername($this->username);
if(!$this->_user) {
$this->_user = Admin::findByUsername($this->username);
}
}
return $this->_user;
}
}
I cant find the problem and if i logged in identity creating for both the users so i could'nt write access rules in particular controller to allow admin only to access the controller.Please help me :(
From reading the comments I think you should just create a unifying table for the two identities where they both get their IDs from. Then make that the identity class. The reason you are able to see the details in both identity classes is that they have the same ID.

yii 2.0 get logged in user's Session ID

Am new to Yii, this is the login function (path /basic/controllers/siteController.php), once the users is logged in it will render the login template.
After a user is logged in,
How to get the SESSION ID and store to DB. ?
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();
}
return $this->render('login', [
'model' => $model,
]);
}
And the model code (path /models/LoginForm.php)
public function login()
{
if ($this->validate()) {
return Yii::$app->user->login($this->getUser(), $this->rememberMe ? 3600*24*30 : 0);
}
return false;
}
$session = Yii::$app->session->getId();
Will grab the Id. There is a good article on sessions here http://www.bsourcecode.com/yiiframework2/session-handling-in-yii-framework-2-0/
And to save something like:
$model->session = $session;
$model->save();

Yii: How to validatePassword with Edvlerblog\Adldap2 using userprincipalname instead of samaccountname

Question
Currently looking for how other people handled the validate password function when they need to authenticate with the userprincipalname instead of the Edvlerblog\Adldap2 validatePassword function which uses samaccountname.
Please provide feedback in the comments if you are struggling with
anything specific so we can update the documentation.
Current Implementation
For app/common/model/LoginForm
getUser
The Edvlerblog\Adldap2 getUser() function works, and even caches the queryLdapUserObject, allowing you to fetch any of the AD attributes.
protected function getUser()
{
if ($this->_user === null) {
$this->_user = \Edvlerblog\Adldap2\model\UserDbLdap::findByUsername($this->username);
}
return $this->_user;
}
validatePassword()
Currently, the following validatePassword function does not work for me because in my instance AD must authenticate against the userprincipalname instead of the samaccount name.
public function validatePassword($attribute, $params)
{
if (!$this->hasErrors()) {
$user = $this->getUser();
if (!$user || !$user->validatePassword($this->password)) {
$this->addError($attribute, 'Incorrect username or password.');
}
}
}
A solution
Here is one workaround thanks to the Edvlerblog\Adldap2 who recently released 3.0.5 addressing a couple issues and providing some examples in his readme docs.
Please note the addition of findByAttribute(), allowing the following:
$this->_user = \Edvlerblog\Adldap2\model\UserDbLdap::findByUsername($this->username);
validatePassword() w/ userprincipalname
Update your login model: common\models\LoginForm.php
public function validatePassword($attribute, $params)
{
if (!$this->hasErrors()) {
$user = $this->getUser();
if (!$user) {
$this->addError('username', 'Incorrect username.');
} else {
// Note: queryLdapUserObject is a cached object,
// so the ldap fetch does not get called :-).
$userprincipalname = $this->_user->queryLdapUserObject()->getAttribute('userprincipalname');
$auth = Yii::$app->ad->auth()->attempt($userprincipalname[0], $this->password);
if (!$auth) {
$this->addError('password', 'Incorrect password.');
}
}
}
}
getUser() w/userprincipalname
/**
* Finds user by [[username]]
*
* #return User|null
*/
protected function getUser()
{
if ($this->_user === null) {
$this->_user = \Edvlerblog\Adldap2\model\UserDbLdap::findByUsername($this->username);
}
return $this->_user;
}
Yii2 ldap Component Configuration
Reference: https://github.com/Adldap2/Adldap2/blob/master/docs/configuration.md
Config in your frontend\config\main:
'components' => [
'log' => [... ],
'authManager' => [... ],
'ad' => [
'class' => 'Edvlerblog\Adldap2\Adldap2Wrapper',
'providers' => [
'default' => [
'autoconnect' => true,
'config' => [
'domain_controllers' => ['your.ldap.domain.com'],
'base_dn' => "OU=XXX,OU=XXX,DC=ccccccc,DC=xxxx,DC=com",
'admin_username' => "your_username",
'admin_password' => "your_password",
'port' => 389,
],
],
],
],
],

reset password validation in Yii2

I have a form in which I am trying to reset the password. I have 3 fields password, changepassword and re-enterpassword.
First I need to check whether the password field matches with database password.
While user signup I have used the default Yii2 functionality which generates random password and saves that password into database. Also I used the default login functionality while user login.
And now, for validating the password, I am trying to use the same default Yii2 validation which is used in login. But, it is not working fine. It is always giving validation true when I had echoed and checked in the controller with $user->validate(), which you will find in the below code.
I have a view resetProfilePassword.php in which I have a form
<?php $form = ActiveForm::begin(['options' => ['enctype' => 'multipart/form-data']]); ?>
<?php
echo $form->field($resetpasswordmodel, 'password');
echo $form->field($resetpasswordmodel, 'changepassword');
echo $form->field($resetpasswordmodel, 'reenterpassword');
?>
<div class="form-group">
<?= Html::submitButton('Submit', ['class' => 'btn btn-primary']) ?>
</div>
<?php ActiveForm::end(); ?>
I have a model resetProfilePasswordForm.php
<?php
namespace frontend\models;
use common\models\User;
use yii\base\Model;
class ResetProfilePasswordForm extends Model
{
public $password;
public $changepassword;
public $reenterpassword;
public function rules()
{
return [
['password', 'validatePassword'],
['changepassword', 'required'],
['reenterpassword', 'required'],
['reenterpassword', 'compare', 'compareAttribute'=>'changepassword', 'message'=>"Passwords don't match" ]
];
}
public function attributeLabels()
{
return [
//'user_profile_id' => 'User Profile ID',
//'user_ref_id' => 'User Ref ID',
'password' => 'Password',
'changepassword' => 'Change Password',
'reenterpassword' => 'Re-enter Password',
];
}
public function validatePassword($attribute, $params)
{
if (!$this->hasErrors()) {
$user = $this->getUser();
if (!$user || !$user->validatePassword($this->password)) {
$this->addError($attribute, 'Incorrect username or password.');
}
}
}
protected function getUser()
{
if ($this->_user === null) {
$this->_user = User::findByUsername($this->username);
}
return $this->_user;
}
}
This is controller ProfileController.php
public function actionResetProfilePassword()
{
$resetpasswordmodel = new ResetProfilePasswordForm();
if ($resetpasswordmodel->load(Yii::$app->request->post())) {
$user = User::find()->where(['id' => Yii::$app->user->identity->id])->one();
if($user->validate()){
$user->save(false);
}
}
return $this->render('ResetProfilePassword', [
'resetpasswordmodel' => $resetpasswordmodel
]);
}
Please help me where I am facing the issue.
If this is not the right way to validate, please help me in providing the better way to validate password
To apply resetpasswordmodel validation - just run the validate() method and then - update user model like that:
public function actionResetProfilePassword()
{
$resetpasswordmodel = new ResetProfilePasswordForm();
if ($resetpasswordmodel->load(Yii::$app->request->post())) {
$user = User::find()->where(['id' => Yii::$app->user->identity->id])->one();
# here we run our validation rules on the model
if ($resetpasswordmodel->validate()) {
# if it is ok - setting the password property of user
$user->password = $resetpasswordmodel->changepassword;
# and finally save it
$user->save();
}
return $this->render('ResetProfilePassword', [
'resetpasswordmodel' => $resetpasswordmodel
]);
}
you can create new hash and replace it in database with older password
*note: salt is your email account that you want restore it.
$salt= 'omid.ahmadyani#Outlook.com';
$pass = crypt('00000000',$salt);
die($pass);
my new password is 00000000
and my hashed pass is omXXQw/O/i1po
S F My English!

Yii2 REST API BasicAuth not working

Im implementing REST API Authentication module as following step
1. Create user by Admin
2. First tim: login by Basic Auth to return access_token
3. Use access_token at step 2 to Auth user by. QueryParamAuth
as this instruction it work with QueryParamAuth
https://github.com/yiisoft/yii2/blob/master/docs/guide/rest-authentication.md
But it not work at step2. Auth by BasicAuth
I debug it. $this->auth always return null. Although $username and $password right
class HttpBasicAuth extends AuthMethod
/**
* #var callable a PHP callable that will authenticate the user with the HTTP basic auth information.
* The callable receives a username and a password as its parameters. It should return an identity object
* that matches the username and password. Null should be returned if there is no such identity.
*
* The following code is a typical implementation of this callable:
*
* ```php
* function ($username, $password) {
* return \app\models\User::findOne([
* 'username' => $username,
* 'password' => $password,
* ]);
* }
* ```
*
* If this property is not set, the username information will be considered as an access token
* while the password information will be ignored. The [[\yii\web\User::loginByAccessToken()]]
* method will be called to authenticate and login the user.
*/
public $auth;
public function authenticate($user, $request, $response)
{
$username = $request->getAuthUser();
$password = $request->getAuthPassword();
if ($this->auth) {
if ($username !== null || $password !== null) {
$identity = call_user_func($this->auth, $username, $password);
var_dump($identity);
die();
if ($identity !== null) {
$user->switchIdentity($identity);
} else {
$this->handleFailure($response);
}
return $identity;
}
} elseif ($username !== null) {
$identity = $user->loginByAccessToken($username, get_class($this));
if ($identity === null) {
$this->handleFailure($response);
}
return $identity;
}
return null;
}
My question is how can i implement $this->auth function?
HTTP Basic Auth
// controller code
Way 1: user Auth using auth-token
use yii\filters\auth\HttpBasicAuth;
public function behaviors()
{
$behaviors = parent::behaviors();
$behaviors['authenticator'] = [
'class' => HttpBasicAuth::className(),
];
return $behaviors;
}
Above code will validate user by access token (as mentioned in the doc)
when window prompts to enter username & password
username: hErEaccE55T0ken
password:
Way 2:
To implement custom auth using username & password, sample code (chris code works)
i m using user_email, user_password
public $user_password;
public function behaviors()
{
$behaviors = parent::behaviors();
$behaviors['authenticator'] = [
'class' => HttpBasicAuth::className(),
'auth' => [$this, 'auth']
];
return $behaviors;
}
/**
* Finds user by user_email and user_password
*
* #param string $username
* #param string $password
* #return static|null
*/
public function Auth($username, $password) {
// username, password are mandatory fields
if(empty($username) || empty($password))
return null;
// get user using requested email
$user = \app\models\User::findOne([
'user_email' => $username,
]);
// if no record matching the requested user
if(empty($user))
return null;
// hashed password from user record
$this->user_password = $user->user_password;
// validate password
$isPass = \app\models\User::validatePassword($password);
// if password validation fails
if(!$isPass)
return null;
// if user validates (both user_email, user_password are valid)
return $user;
}
I implement HttpBasicAuth->auth in my controller where I attach HttpBasicAuth as a behavior like so:
class MyController extends Controller
{
public function behaviors()
{
$behaviors = parent::behaviors();
$behaviors['authenticator'] = [
'class' => HttpBasicAuth::className(),
'auth' => [$this, 'auth']
]
return $behaviors;
}
public function auth($username, $password)
{
// Do whatever authentication on the username and password you want.
// Create and return identity or return null on failure
}
// ... Action code ...
}