I dont want to update the password fields.how to use this.Im using md5 encode for password.So i dont want to update the password field in yii framework.any help appreciated??
I think a better approach would be to not use the scenario in this case. The next code in the rules just says to the scenario: the next fields are required. But not: skip the other else.
array('name, username, email', 'required', 'on' => 'update'),
For example, if we limit the length of the password up to 32 characters, but in a database is stored in a format sha1 (length 40), then we have a problem because the validator will block the database query.This is because when you make updating, the "validatŠµ" method checks all class properties (regards database table mapping), not just the new ones delivered by post.
Could use the method "saveAttributes", but then I noticed another problem. If the column "email" is unique in the database and in case edited email duplicate one of the existing, then the Yii message system defined in the rules can not notify and throws error code regards database query.
The easiest approach I think is: don't set scenario in this case. Just send as an argument the properties you want. This will keep the all CRUD features created by GII.
In your code it looks like this:
(in model)
public function rules() {
return array(
array('name, username, email, password', 'required'),
);
}
(in controller)
if($id==Yii::app()->user->id){
$model=$this->loadModel($id);
if(isset($_POST['JbJsJobResume'])) {
$model->attributes=$_POST['JbJsJobResume'];
if($model->save(true, array('name', 'username', 'email')))
$this->redirect(array('view','id'=>$model->id));
}
$this->render('update',array( 'model'=>$model, ));
}
I noticed that you do not use RBAC. It is very convenient and flexible - try it.
http://www.yiiframework.com/doc/guide/1.1/en/topics.auth#role-based-access-control
In your model you must do something like this:
public function rules() {
return array(
array('name, username, email, password', 'required', 'on' => 'create'),
array('name, username, email', 'required', 'on' => 'update'),
);
}
Lets say that the scenario that you run now is the update. So I don't require the password there. I require it only in the create scenario that you may have. So in the view file that you have you remove the password field and inside the action that you have you include this:
$model->setScenario('update');
so it will not require the password and it will remain the same.
For the password change you can create a new action (ex. actionPassChange) where you will require to type twice the new password.
$model->attributes=$_POST['JbJsJobResume'];
instead of assign all attributes just assign those only you want to save,
as
$model->name=$_POST['JbJsJobResume']['name'];
$model->save();
1st option Just unset password field before setting it:
function update(){
$model=$this->loadModel($id);
unset($_POST['JbJsJobResume']['password']);
$model->attributes=$_POST['JbJsJobResume'];
$model->save();
}
2nd option: Use temp variable:
function update(){
$model=$this->loadModel($id);
$temPassword = $model->passwrod;
$model->attributes=$_POST['JbJsJobResume'];
$model->passwrod = $temPassword;
$model->save();
}
3rd option: use scenarios
I am not sure why this is a problem, and some code could help us to understand why. If you do not wish to capture / update the password, then why is the password field in the form?
If you remove the password field from the view, the value of the password field will not be posted back to controller and then it will not be updated.
There is a possibility that the above method does not work and this could be that in your User model, you are encrypting the password in the afterValidate method?:
protected function afterValidate()
{
parent::afterValidate();
$this->password = $this->encrypt($this->password);
}
public function encrypt($value)
{
return md5($value);
}
In this scenario, if you remove the password field from the view, and just update the name, username or email, then the md5 hash of the password will be re-hashed automatically and you will lose the real password.
One method to get around this is to md5 the password in the afterValidate method (create or update) however if the user wishes to change profile details, in the same form, ask the user to verify their password again.
FORM: user changes name and verifies password
Form posted
Controller calls authenticate method.
If authenticate true, overwrite the entry in user table (including verified pw)
I think #Gravy's answer is right,Thanks Gravy and Nikos Tsirakis. I have fixed nearly same issue as #faizphp. I add scenario for User model as Nikos Tsirakis said, but got same issue also. Then I found I encrypt password in User.afterValidate, so when update the User model everytime, the program encrypt the password in database again to wrong password. So i changed my function from
protected function afterValidate()
{
parent::afterValidate();
if (!$this->hasErrors())
$this->password = $this->hashPassword($this->password);
}
</code>
to
protected function afterValidate()
{
parent::afterValidate();
if (!$this->hasErrors() && $this->scenario==="create")
$this->password = $this->hashPassword($this->password);
}
.
It seems work.
Related
I want to change the default auth fields name in Laravel 5.6, it looks like to work for the username but not for the password.
I looked this questions How to change / Custom password field name for Laravel 4 and Laravel 5 user authentication and the Sample data to test works but not in my login form.
username is useUsername
password is usePassword
On my login form, I tested to kind of data
When I try to log with a user with the password hash in db, I get These credentials do not match our records.
When I log with a user without password hash in db, I get an issue Undefined index: password in the vendor/laravel/framework/src/Illuminate/Auth/EloquentUserProvider.php-> validateCredentials(UserContract $user, array $credentials)
what I changed in the loginController.php
protected function validateLogin(Request $request)
{
$this->validate($request, [
$this->username() => 'required',
'usePassword' => 'required',
]);
}
public function username()
{
return 'useUsername';
}
protected function credentials(Request $request)
{
return $request->only($this->username(), 'usePassword');
}
In Users.php
protected $table = 't_user';
public function getAuthPassword()
{
return $this->usePassword;
}
I hope you could help me to solve this issue, I don't really understand why I get these different error with hash or not hash and how I could solve it.
MYT.
I thing you can use a Hashing Password by Using Bcrypt in Laravel.
like
$password = Hash::make('yourpassword');
Basically, you'll do it when creating/registering a new user
then hash password will be store into database.
when you log in then you can remember your password otherwise it will give you error ...
if you forgot your hash password then you can bcrypt password by using this one
$password = bcrypt('admin');
I hope this will help you...
for more information of Hashing you can visit
Hashing in laravel
I solved my problem by doing a custom AuthController. It was easiest for what I wanted to do.
I'm just starting out with Laravel 5, I come from Laravel 4 environment so it shouldn't be too hard.
I heard L5 comes with a built-in authentication system which is neat.
I've set everything up from database to views.
The registration process is working correctly and after that it logs me in automatically. but when I log out and try to log back in, I get this error:
These credentials do not match our records.
I'm not sure what's wrong. do I have to write the login controller manually or how does it work in L5?
I had the same issue. The reason for mine was that
I defined setPasswordAttribute in my User model so every time, I enter plain password, it hashes before sending to DB.
public function setPasswordAttribute($password)
{
$this->attributes['password'] = \Hash::make($password);
}
and in my db:seed, I was creating a user with hashed password with Hash::make("password"), too. So laravel hashes hashed password :)
In laravel version 5.* you don't need to hash input password for Auth, because Auth manages it itself. you just have to pass {{csrf_field()}} through form.
In addition to #mervasdayi solution, a good way to hash passwords in setPasswordAttribute avoiding rehashing problems could be this:
public function setPasswordAttribute($password){
$this->attributes['password'] = Hash::needsRehash($password) ? Hash::make($password) : $password;
}
Further to what #mervasdayi & Gerard Reches have suggested. Just thought I'd make a note that you will need to include
use Illuminate\Support\Facades\Hash;
at the top of your User model when adding in these fixes.
I think that it is later but i found two solutions to solve this problem.
Firstly you can use bcrypt function if you use laravel 5.3. Look at the below function. It means that your get your data in array.
public function create(array $data)
{
return User::create([
'password' => bcrypt($data['password']),
]);
}
Secondly you can use mutator to fix it like this:
public function setPasswordAttribute($password)
{
$this->attributes['password'] = \Hash::make($password);
}
Hope that it can help others. Best regards
In my case, I attempt too many times with the wrong password, and then I am unable to login with the user for some hour, and at the same time, I am able to log in with other users.
I'm using Cake 2.1.1 and trying to write an ajax function to reset a users password to a specific format. I have been able to change the password, but unable to make it so that the new password actually works to log the user in.
I have this function in my Users controller:
function ajax_reset_password(){
$this->autoRender=false;
$user = $this->User->find('first',array(
'conditions'=>array('User.email'=>$_GET['email'])
));
$this->User->id = $user['User']['id'];
$pass = $_GET['name'].'2014';
$passHashed= $this->Auth->password($pass);
$this->User->set('password', $pass);
$this->User->set('updated_at',date("Y-m-d H:i:s"));
$this->User->save();
//... code to email user new password
}
And this is my Users Controller beforeSave:
public function beforeSave(){
if (isset($this->data['User']['password'])) {
$this->data['User']['password'] = AuthComponent::password($this->data['User']['password']);
}
return true;
}
If I run this function and check my database, I can see that the value of password has changed literally to "name2014", but I cannot login with that password.
If I set the password to $passHashed and check my database, I see that the value of password has changed to a hashed value, but again, I cannot use the new password to login.
There is also a 'salt' field in my Users table that never changes.
I am guessing that the issue is that the salt needs to update with the password hash in order to properly decyrpt it, but I'm unsure of how to update the salt. Can I get it in my controller and set the value directly, or is this handled some other way with the AuthComponent?
Other posts about this topic seem to work fine with the code I have been using, but I also haven't found any that trying to set the password value directly.
Use what you have in the beforeSave(). (Don't try the route of hashing in the Controller).
If it's not hashing, just do some standard debugging and find out why it's not getting into that part of the code:
debug($this->data);
exit;
if (isset($this->data['User']['password'])) {
// IT'S NOT GETTING HERE
//...
This is one of those where the "answer" is just a nudge toward debugging your code, since it's clear where you can find out exactly what's going on and why by just seeing what's in the data and when.
I am currently working with CakePHP now if my users forgot their password i wish to allow them to reset it. (i.e me sending a mail to them with their new temp password).
But there is a problem. Passwords stored in my Database are hashed by the Auth component which means that if i try to select all from my User model i will get a hashed version of the password. Futher more i don't know how i will be able to save the password HASHED after generating a new one.
Ive been googling aroung for some time to find an answer to this but couldn't seem to find any examples of how this would be done.
Has anyone tried something similar or know how i can be done?
Ok, 2.x definitely gives more control. I only hash the passwords in my User model's beforeSave method just like you do:
public function beforeSave() {
if (isset($this->data['User']['password'])) {
$this->data['User']['password'] = AuthComponent::password($this->data['User']['password']);
}
return true;
}
This allows you to create a password in your Controller's password reset action as plain text, email it to the user, and then you set the password in the User model and persist it (password is hashed before it hits the database). The important thing here is that your password stays plain text until your controller calls the save method.
Generally I always add an unset on the password field in controller actions that will save the User record just to make sure it won't get rehashed. A second option would be to add an afterFind callback to your user model that does the unset each time the User model(s) are loaded.
About the one time reset key.... I have an additional field in my User object that I use in two cases. Email verification and password reset. When the user is created it is set to the SHA1( + + ). A link is emailed to the user that sends them to the User controller's validate action. Once that key is verified, that column gets cleared out in the database.
Same with the password reset. When they request a reset, the value gets generated in the same way and a link to the User controller's reset action gets emailed to the user. They enter their userid and if the key in the link matches the one in their database row, they can change their password. When their password is changed, this value is again cleared.
The biggest issue with sending temporary passwords is that it creates a DoS mechanism (against users, not your site). If I decided to harass someone, I could create a task that keeps resetting their password every hour. They can't get in until they check their email, but then it'll change again. Using a key, they'll get an email with a reset link, but their current password will still work as the presence of a reset code would not keep them from logging in.
I think you cannot convert encrypt password to decrypt.
So, if you want to read out how you can reset password then read out CakeDC plugin of cakephp.
https://github.com/CakeDC/users
this is the standard plugin of cakephp.
try this
function admin_reset($token = null) {
/**
* if logged in, send to home/dashboard page
*/
if (count($this->Session->read("Auth.User"))) {
return $this->redirect('/');
}
$this->set('title_for_layout', 'Reset Password');
$this->layout = 'admin';
$this->User->recursive = -1;
if (!empty($token)) {
$u = $this->User->findBytokenhash($token);
if ($u) {
$this->User->id = $u['User']['id'];
if (!empty($this->data)) {
$this->User->data = $this->data;
$this->User->data['User']['username'] = $u['User']['username'];
$new_hash = sha1($u['User']['username'] . rand(0, 100)); //created token
$this->User->data['User']['tokenhash'] = $new_hash;
if ($this->User->save($this->User->data, false)) {
$this->Session->setFlash(__('Password has been updated.'), 'default', array('class' => 'alert alert-success'));
$this->redirect(array('controller' => 'users', 'action' => 'login'));
}
}
} else {
$this->Session->setFlash(__('Token corrupted. Reset link work only for once, please try again.'), 'default', array('class' => 'alert alert-success'));
}
} else {
//$this->redirect('/');
}
}
I have a form to edit a UserProfile which is stored in mysql db. Which includes the following custom configuration:
public function configure()
{
$this->widgetSchema['password']=new sfWidgetFormInputPassword();
$this->validatorSchema['password']->setOption('required', false); // you don't need to specify a new password if you are editing a user.
}
When the user tries to save the executeUpdate method is called to commit the changes.
If the password is left blank, the password field is set to '', but I want it to retain the old password instead of overwriting it.
What is the best (/most in the symfony ethos) way of doing this? My solution was to override the setter method on the model (which i had done anyway for password encryption), and ignore blank values.
public function setPassword( $password )
{
if ($password=='') return false; // if password is blank don't save it.
return $this->_set('password', UserProfile ::encryptPassword( $password ));
}
It seems to work fine like this, but is there a better way?
If you're wondering I cannot use sfDoctrineGuard for this project as I am dealing with a legacy database, and cannot change the schema.
It looks fine to me:
public function setPassword($password)
{
if (!$password) return false;
return $this->_set('password', UserProfile::encryptPassword($password));
}
I've got a few forms where I need to update sfGuardUser password along with other form fields that relate to different models, and I've ended up with something like this:
$id = // sfGuardUser primary key
$values['password'] = // the form post value returned
if ($values['password']) {
$user = Doctrine::getTable('sfGuardUser')->find($id);
$user->setPassword($values['password']);
$user->save();
}
... saves a value if a value was posted in the form.