Login access not working in yii2 - 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.

Related

Yii2 basic validate password

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

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,
],
],
],
],
],

Yii2 dektrium add new field to user model and change it in account form

I have added a new field to user model 'paypal' and need to change it in overridden account form.
Override user model
<?php
namespace common\models;
class User extends \dektrium\user\models\User
{
public function scenarios()
{
$scenarios = parent::scenarios();
$scenarios['create'][] = 'paypal';
$scenarios['update'][] = 'paypal';
$scenarios['register'][] = 'paypal';
return $scenarios;
}
public function rules()
{
$rules = parent::rules();
$rules['paypalLength'] = ['paypal', 'string', 'max' => 255];
return $rules;
}
}
Override SettingsForm model
<?php
namespace common\models;
class SettingsForm extends \dektrium\user\models\SettingsForm
{
public $paypal;
public function rules()
{
$rules = parent::rules();
$rules['paypalLength'] = ['paypal', 'string', 'max' => 255];
return $rules;
}
}
Configure module
'user' => [
'class' => 'dektrium\user\Module',
'modelMap' => [
'User' => 'common\models\User',
'RegistrationForm' => 'common\models\RegistrationForm',
'SettingsForm' => 'common\models\SettingsForm',
],
'controllerMap' => [
...
And I have overridden account form view. When I'm trying to change paypal field in user/settings/account it doesn't change it. What should I do to make it work?
Thanks.
Also you must override view paths:
'view' => [
'theme' => [
'pathMap' => [
'#dektrium/user/views' => '#app/views/user',
],
],
],
And after that open #vendor/dektrium/yii2-user/views and make a folder on #app/views based on dektrium view folders. For example create a folder named admin (because you have on #vendor/dektrium/yii2-user/views a folder named admin) and create corresponded folder on app views, i.e. #app/views/admin.
After that create your view file that you want to change on #app/views/[dektrium-folder] and change it.

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!

HybridAuth CakePHP3.X,how to save user after successful login?

I have read the description over,
Once a user is authenticated through the provider the authenticator gets the user profile from the identity provider and using that tries to find the corresponding user record in your app's users table. If no user is found and registrationCallback option is specified the specified method from the User model is called. You can use the callback to save user record to database.
But where to define/declare registrationCallback
If you want user to register if not exist then this code will execute :
if (!empty($this->_config['registrationCallback'])) {
$return = call_user_func_array(
[
TableRegistry::get($userModel),
$this->_config['registrationCallback']
],
[$provider, $providerProfile]
);
if ($return) {
$user = $this->_fetchUserFromDb($conditions);
if ($user) {
return $user;
}
}
You need to define the registration function in config ( in __construct) and regarding call_user_func_array read this link - https://php.net/call-user-func-array
To Store user in database after login
1>defines the function in UsersTabel.php
public function registration($provider, $profile) {
$user = $this->newEntity([
'username' => $profile->displayName,
'provider' => $provider,
'provider_uid' => $profile->identifier
]);
if(!$this->save($user))
{
Log::write(LOG_ERR, 'Failed to create new user record');
return false;
}
return true;
}
2>Replace the function of file vendor ▸ admad ▸ cakephp-hybridauth ▸ src ▸ Auth▸ HybridAuthAuthenticate.php
public function __construct(ComponentRegistry $registry, $config)
{
$this->config([
'fields' => [
'provider' => 'provider',
'provider_uid' => 'provider_uid',
'openid_identifier' => 'openid_identifier'
],
'hauth_return_to' => null,
'registrationCallback'=>'registration'
]);
parent::__construct($registry, $config);
}