I can not update the value in the database. Here's the code:
if($user = User::model()->findByAttributes(array('username'=>$verification->username)))
{
// Generating 8 random symbols for new password
$new_password = substr(str_shuffle(str_repeat("0123456789abcdefghijklmnopqrstuvwxyz", 8)), 0, 8);
// Transfering password to MD5 hash with salt!
$new_password = md5('salt'.$new_password);
$user->password = $new_password;
if($user->save())
{...
The debugger shows that the value and get it replaced (password), but when you save
if($user->save())
{
Gives false and resets to the most recent line of code:
$this->render('forget');
Questions:
How to find out what happened and why did not update the value?
How to find the error (error code, ...)?
As your last comment, If you have no repeat_password field into your table, add it by hand in your model. (User model). (Actually there is no need to have this field in your table.)
public $repeat_password
Then, define rules for the field. (for example, required and so on...)
To get validation error you can do like below:
CVarDumper::dump($model->getErrors(),56789,true);
Related
My problem is that I'm using CodeIgniter. I created an Administrator Panel which I use to create users and passwords. I use password_hash before sending them to database (in fact, in the database I can see the hashed password).
The problem is... When I try to log in, it doesn't. I can only access with administrator account, which I created before I started using CodeIgniter.
I can log in with admin account, but not with the accounts created with the admin panel.
I tried to use a very simple php file (outside CI) to copy and paste the hash to one of the user's fields in my database and it worked. I don't understand why this doesn't work within CodeIgniter.
Here's the part of my code:
public function insert_user($username, $passw, $perm){
$hashed_pass = password_hash($passw, PASSWORD_DEFAULT);
$data = array(
"username" => $username,
"passw" => $hashed_pass,
"perms" => $perm
);
$this->db->insert('usuarios', $datos);
}
The function above inserts correctly data in the database. I can see the password hashed, but when I try to log in with created users from admin panel, it just doesn't work (but it does with admin account, and they all are using the same function to log in).
public function login($username, $password){
$query = $this->db->query("select passw, perms from users where username = '".$username."'");
$result = $query->row();
$p_hashed = $result->passw;
$perms= $result->perms;
if(password_verify($password, $p_hashed)){
$info= array(
"is_valid" => true,
"username" => $username,
"perms" => $perms
);
return $info;
}
else {
$info= array(
"is_valid" => false,
"username" => ""
);
return $info;
}
}
I checked database and CI charset, all is utf8. I don't understand why is not working... I would appreciate any help.
P.S.: if the name of variables are no correlated or are not the same is because I translated it to English (I'm not native English speaker, so I'm not using English in this project).
Thank you.
EDIT
I've changed the code to use md5 instead of password_hash and I'm having the same issue.
EDIT 2
I detected the problem: I was comparing the 2 password (the first one and the confirm password). After that comparison, I passed the data to the model... But the variable of the password I was sending to model was a new variable with no data. I was hashing a not initialized variable.
There doesn't seem to be any problem in the code you show. As I commented, the likely problem is that the passw column in the table is truncating the data being inserted.
Check the documentation for password_hash to find what the return data size is for the various algorithms and adjust your table structure accordingly. For PASSWORD_DEFAULT the suggested size is 255 characters.
The code below isn't an answer, but I have time and thought you might find a refactored version of login() interesting.
It is assumed that you have properly validated and sanitized the values being passed to the login() method.
public function login($username, $password)
{
//use query binding so values are automatically escaped, producing a safer query
$query = $this->db->query("select username, perms, passw
from users where username = ?", [$username]);
// make sure query worked and found a record
if($query && $query->num_rows() > 0)
{
// get an row array so you don't need to make an array
$row = $query->row_array();
if(password_verify($password, $row['passw']))
{
unset($row['passw']); // remove passw from array
$row['is_valid'] = true;
return $row;
}
}
return array( "is_valid" => false, "username" => "");
}
I try to update/save a custom Field of User Profile on Drupal 8.
I am lucky to get Values but not to save them back.
Here is my Code, any1 knows why this won’t work?
I've tried different variations of these already.
$user = \Drupal\user\Entity\User::load(1); // Load USER of ID=1
$user->set(‚field_user_curpage‘,38); //set my custom field = 38 !!!
$user->save(); // save …
This is how I Load these fields:
$user = \Drupal\user\Entity\User::load(1); // Load user with id = 1
$curpage_load = $user->get(‚field_user_curpage‘); // Load custom field from User Profile
$curpage = preg_replace(‚/[^0-9]/‚, ‚‘, $curpage_load->value); // filter for No. only
return $curpage; // return output this
The Entity Load function returns a static object.
Try loading the user with this instead.
\Drupal::entityTypeManager()->getStorage('user')->load($id);
This is one of my first applications out of tutorials so I don't know how to express my issue well.
Well I have these 2 tables:
User ( id, code )
Hours ( id, user_id, created)
I want to know how I can add an entry to the Hours table using the user_code.
I tried to grab the data of the User table with the code value and then findBy and pass for the patchEntity but it did not work.
I don't have a whole lot of information to work with, but I'll give it a go.
I want to know how I can add an entry to the Hours table using the
user_code
You mention using patchEntity, so that's updating information that's already there. Assuming user_code is the 'code' column you're talking about there, first find the user by his code:
$users_tbl = TableRegistry::get('Users');
// find the user
$user = $users_tbl->findByCode($user_code)->first();
if ($user) {
// replace '$this->request->data() with whatever patch data you wanted
$users_tbl->patchEntity($user, $this->request->data(), [
'associated' => ['Hours']
]
if ($users_tbl->save($user)) {
// success!
} else {
// error!
}
} else {
// error!
}
It will also depend on how you have the data you passed in (where my '$this->request->data() is, or whatever your array might be) - it needs to match the right column names and be in the correct format listed here.
However, this is updating the data. Just adding the data, you can load the hours table and add a new entry with the user_id acquired from the user search:
$hours_tbl = TableRegistry::get('Hours');
$hours = $hours_tbl->newEntity([
'user_id' => $user->id // $user populated from same method earlier
]);
/* assumed 'id' was autoincrementing and 'created' was populated
through Timestamp behavior */
if ($hours_tbl->save($hours)) {
// yay!
} else {
// boo
}
My case is for change password option. I already have current password in object $pass. I want to validate this $pass against textbox form input current_password to proceed to create a new password for the user. How to validate with same validator. Sorry I'm new to laravel.
$rules = array('password_current' => "required|same:$pass");
doesn't work.
since same: used to ensure that the value of current field is the same as another field defined by the rule parameter (not object). so you can't use this function take a look this example code below.
$data = Input::all();
$rules = array(
'email' => 'required|same:old_email',
);
the above code will check if current email field is same as old_email field.
so i think you can you simple if else
in your handle controller function assume
public function handleCheck(){
$current_password = Input::get('current_password');
$pass = //your object pass;
if($current_password == $pass){
// password correct , show change password form
}else{
// password incorrect , show error
}
}
let me know if it works. see Laravel Validation same
If you have password stored in $pass already just inject $pass in the request and use its field instead for e.g.
$request->request->add(['password_old' => $pass]);
Then, you can validate it like
$rules = array('password_current' => "required|same:password_old");
I have a sit developed in cakephp, and I have a page to edit user.
My user table has many field and one of this is password in md5.
The user can modify all its fields and password but if he leave blank this field I have t take from the database the old password and save it.
But return me error on save on the password field.
This is my action into the controller:
if ($this->request->is ('post')){
$this->User->id = $this->request->data['User']['id'];
if($this->request->data['User']['password'] == ''){
$user = $this->User->find('first',array('conditions'=>array('User.id' => $this->request->data['User']['id'])));
$this->request->data['User']['password'] = md5($user['User']['password']);
$this->request->data['User']['password_confirm'] = md5($user['User']['password']);
}
if ($this->User->save($this->request->data)) {
$this->redirect (array ('action'=>'index'));
}
else{
debug($this->User->validationErrors);
$this->Session->write('flash_element','error');
$this->Session->setFlash ('Errore di salvataggio dello user.');
}
}
And this is the method beforeSave into the UserModel:
public function beforeSave(){
if (isset($this->data['User']['password'])){
$this->data['User']['password'] = AuthComponent::password($this->data['User']['password']);
}
}
The problem is when I try to save return me error on the field password lie is inappropriate type.
If I print the field password before save I see something like: ***** but if I print the variable md5($user['User']['password']) return me the right value of password crypted.
Thanks
IMO, don't have the "password" field where the user edits his profile information.
You can have 2 forms on the page, where the second one is a change password form. This way, if the user changes their "first name" (which is in the first form) for example, your code does not have to check or do anything with their password.
After seeing many different frameworks, and creating systems myself, I can't say I recall anything where I have seen in the "wild" something handled like your doing. You are doing an extra step by getting their old password and "putting it back" just so you don't lose their password in the database when they want to change their profile details.
If its for security, you can make them "confirm" their password so it must match before changing the profile details.
Having the "password" box on the "edit profile" form is just bad code logic.
First comment, there is nothing wrong using md5 but I would use sha1.
Second, you can use only one form, not 2.
Then, in your controller you just need to check if user entered a new password, which you are already doing, if the field is empty then you unset that field, so cake won't update that field.
if ($this->request->is ('post')){
$this->User->id = $this->request->data['User']['id'];
if ($this->request->data['User']['password'] == '') {
unset($this->request->data['User']['password'], $this->request->data['User']['password_confirm']);
}
if ($this->User->save($this->request->data)) {
$this->redirect (array ('action'=>'index'));
}
else{
debug($this->User->validationErrors);
$this->Session->write('flash_element','error');
$this->Session->setFlash ('Errore di salvataggio dello user.');
}
}
By the way, I would change this
$this->User->id = $this->request->data['User']['id'];
For something like
$this->request->data['User']['id'] = $this->Session->read('Auth.id');
in order to prevent data tampering, but due I don't know if you are keeping the user id in a session I didn't write it in the example code