• 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Mythauth - update password form

#1
Hey all,

I have the following problem: I have created a form with which the user should be able to update his password.
When the new password is entered and submitted, the "password_hash" field in the database table "users" is updated. However, I cannot log in with the new password afterwards.

Does anyone have any idea what my mistake is?


My current code:


Code:
namespace App\Models;
use CodeIgniter\Model;

class User_Model extends Model {

    protected $table = 'users';
    protected $primaryKey = 'id';

    protected $allowedFields = ['id','password_hash','updated_at'];        

}

Code:
/**
UPDATE FUNCTION IN THE CONTROLLER
**/

public function updatePassword() {
  $model = new User_Model();

  //Costs for the creation of the password hash.
  $hashOptions = [
      'cost' => 5,
  ];

  //Get input and hash password
  $password = $this->request->getPost('new-password');
  $hashed_password = password_hash(base64_encode(hash('sha384', $password, true)),PASSWORD_DEFAULT,$hashOptions);

  //Get id of current user
  $user_id = user_id();

  //Get current timestamp for updated_at field in the record
  $updated_at = date('c', time());

  //Create data array for the update of the record
  $data = [
      'password_hash' => $hashed_password,
      'updated_at' => $updated_at
  ];

  //Update the record
  $model->update($user_id,$data);
}

Code:
<form action="<?php echo base_url('Security_Settings_Controller/updatePassword'); ?>" method="post">
  <?= csrf_field() ?>
   <div class="form-group">
       <label for="old-password">Old Password</label>
       <input class="form-control" id="old-password" type="password">
   </div>
   <div class="form-group">
      <label for="new-password">New Password</label>
      <input class="form-control" id="new-password" type="password">
   </div>
   <div class="form-group">
      <label for="confirm-new-password">Confirm Password</label>
      <input class="form-control" id="confirm-new-password" type="password">
   </div>
   <button class="btn btn-primary btn-block" type="submit">Update Password</button>
</form>
Reply

#2
Because if you look at the code you will see that it is also creating a token and cookie.
On login it looks for that token and cookie.

Best to look at the Myth/Auth code and see what it is doing.

SEE: Entities/User.php - setPassword() method.
What did you Try? What did you Get? What did you Expect?

Joined CodeIgniter Community 2009.  ( Skype: insitfx )
Reply

#3
Hey InsiteFX,
thanks for your quick response!

I already have taken a look on the source code. However the only cookie and token I have seen are used for the remember me functionality which is not in use on my web project.

I have looked at the following files:
- Entities/User
- AuthController
- Authentication/LocalAuthenticator
- Authentication/AuthenticatonBase
- Commands/CreateUser
- Commands/SetPassword

Seems like I'm missing or misunderstanding something.
Can you tell me where I can find the code to the token / cookie?

Best regards
Schwaluck
Reply

#4
(03-21-2021, 08:49 PM)InsiteFX Wrote: Because if you look at the code you will see that it is also creating a token and cookie.
On login it looks for that token and cookie.

Best to look at the Myth/Auth code and see what it is doing.

SEE: Entities/User.php - setPassword() method.

Thanks for adapting your post.

I had already taken a look at the function and adapted my password_hash() function based on that before. However, I can't find the creation of a token or cookie anywhere here.

I have attached the code once below and added my "explanations". Am I misunderstanding something here?

In any case, thank you very much for your help!

Code:
public function setPassword(string $password) {

        //Getting the config from the Auth.php file including the hash algorithm I want to use.

        $config = config('Auth');

        //Check if I want to use ARGON as the hash algorithm. So everything in this if clause is only relevant for the
        //use of ARGON.  

        if (
            (defined('PASSWORD_ARGON2I') && $config->hashAlgorithm == PASSWORD_ARGON2I)
                ||
            (defined('PASSWORD_ARGON2ID') && $config->hashAlgorithm == PASSWORD_ARGON2ID)
            )
        {
            $hashOptions = [
                'memory_cost' => $config->hashMemoryCost,
                'time_cost'   => $config->hashTimeCost,
                'threads'     => $config->hashThreads
                ];
        }
        //If I do not use ARGON, in the else clause the music plays, because I use PASSWORT_DEFAULT.
        //So first the costs are defined and then the password is hashed. The code after that is only relevant
        //if the reset function is used (in my situation not the case).
        else
        {
            $hashOptions = [
                'cost' => $config->hashCost
                ];
        }

        $this->attributes['password_hash'] = password_hash(
            base64_encode(
                hash('sha384', $password, true)
            ),
            $config->hashAlgorithm,
            $hashOptions
        );

        /*
            Set these vars to null in case a reset password was asked.
            Scenario:
                user (a *dumb* one with short memory) requests a
                reset-token and then does nothing => asks the
                administrator to reset his password.
            User would have a new password but still anyone with the
            reset-token would be able to change the password.
        */
        $this->attributes['reset_hash'] = null;
        $this->attributes['reset_at'] = null;
        $this->attributes['reset_expires'] = null;
    }
Reply

#5
You need to use what Myth/Auth is using or it will not match up with the database password.

Take a look at the Registration form it should lead you to what you need.

But kept the hash options the same as Myth/Auth.
What did you Try? What did you Get? What did you Expect?

Joined CodeIgniter Community 2009.  ( Skype: insitfx )
Reply

#6
use given user entity class to  get hash of new password.
Code:
$entity = new User();
$newPassword = $this->request->getPost('new_password');
$entity->setPassword($newPassword);
$hash  = $entity->password_hash;
$users->update($id,['password_hash' => $hash]);
Reply

#7
(03-22-2021, 10:37 PM)ikesela Wrote: use given user entity class to  get hash of new password.
Code:
$entity = new User();
$newPassword = $this->request->getPost('new_password');
$entity->setPassword($newPassword);
$hash  = $entity->password_hash;
$users->update($id,['password_hash' => $hash]);

Hey ikesela,
actually an obvious solution, but I didn't think of it. Thank you , it works like a charm now! Smile

Have a nice day!
Reply

#8
(03-23-2021, 03:04 AM)schwaluck Wrote:
(03-22-2021, 10:37 PM)ikesela Wrote: use given user entity class to  get hash of new password.
Code:
$entity = new User();
$newPassword = $this->request->getPost('new_password');
$entity->setPassword($newPassword);
$hash  = $entity->password_hash;
$users->update($id,['password_hash' => $hash]);

Hey ikesela,
actually an obvious solution, but I didn't think of it. Thank you , it works like a charm now! Smile

Have a nice day!
Hello,can i see your full source for change password ? Im so frustased right now because dont understand,thank you. Sorry for my bad english language.
Reply

#9
(03-31-2021, 08:49 AM)fuzna28 Wrote:
(03-23-2021, 03:04 AM)schwaluck Wrote:
(03-22-2021, 10:37 PM)ikesela Wrote: use given user entity class to  get hash of new password.
Code:
$entity = new User();
$newPassword = $this->request->getPost('new_password');
$entity->setPassword($newPassword);
$hash  = $entity->password_hash;
$users->update($id,['password_hash' => $hash]);

Hey ikesela,
actually an obvious solution, but I didn't think of it. Thank you , it works like a charm now! Smile

Have a nice day!
Hello,can i see your full source for change password ? Im so frustased right now because dont understand,thank you. Sorry for my bad english language.
Hey fuzna28,

I think the interesting part for you is the update function in the controller. So here is what i did:
Code:
namespace App\Controllers;

use Config\Services;
use Myth\Auth\Models\UserModel;
use Myth\Auth\Entities\User;

class Test extends BaseController
{

public function updatePassword() {
                
        //Rules for the update password form
        $rules = [
            'old-password' => [
                'label'  => 'old password',
                'rules'  => 'required|checkOldPasswords',
                'errors' => [
                    'required' => 'Put your message here',
                    'checkOldPasswords' => 'Put your message here',
                    ]
            ],        
            'new-password' => [
                'label'  => 'new password',
                'rules'  => 'required',
                'errors' => [
                    'required' => 'Put your message here',

                ]
            ],        
            'confirm-new-password' => [
                'label'  => 'confirm password',
                'rules'  => 'required|matches[new-password]',
                'errors' => [
                    'required' => 'Put your message here',
                    'matches' => 'Put your message here'
                    ]
            ],            
        ];    
        
        if ($this->request->getMethod() === 'post' && $this->validate($rules)) {
            
            //Create new instance of the MythAuth UserModel
            $users = model(UserModel::class);
            
            //Get the id of the current user
            $user_id = user_id();
            
            //Create new user entity
            $entity = new User();
                        
            //Get current password from input field
            $newPassword = $this->request->getPost('new-password');
            
            //Hash password using the "setPassword" function of the User entity
            $entity->setPassword($newPassword);
            
            //Save the hashed password in the variable "hash"
            $hash  = $entity->password_hash;
            
            //update the current users password_hash in the database with the new hashed password.
            $users->update($user_id,['password_hash' => $hash]);

            //Return back with success message
            return redirect()->to('/test')->with('success', "Put your message here");    
        }
        else {
            //Return with errors
            return redirect()->to('/test')->withInput()->with('error', "Put your message here");                    
        }

    }
}
I hope that helps. If you have any questions, just ask! Smile
Reply

#10
(04-01-2021, 01:22 AM)schwaluck Wrote:
(03-31-2021, 08:49 AM)fuzna28 Wrote:
(03-23-2021, 03:04 AM)schwaluck Wrote:
(03-22-2021, 10:37 PM)ikesela Wrote: use given user entity class to  get hash of new password.
Code:
$entity = new User();
$newPassword = $this->request->getPost('new_password');
$entity->setPassword($newPassword);
$hash  = $entity->password_hash;
$users->update($id,['password_hash' => $hash]);

Hey ikesela,
actually an obvious solution, but I didn't think of it. Thank you , it works like a charm now! Smile

Have a nice day!
Hello,can i see your full source for change password ? Im so frustased right now because dont understand,thank you. Sorry for my bad english language.
Hey fuzna28,

I think the interesting part for you is the update function in the controller. So here is what i did:
Code:
namespace App\Controllers;

use Config\Services;
use Myth\Auth\Models\UserModel;
use Myth\Auth\Entities\User;

class Test extends BaseController
{

public function updatePassword() {
                
        //Rules for the update password form
        $rules = [
            'old-password' => [
                'label'  => 'old password',
                'rules'  => 'required|checkOldPasswords',
                'errors' => [
                    'required' => 'Put your message here',
                    'checkOldPasswords' => 'Put your message here',
                    ]
            ],        
            'new-password' => [
                'label'  => 'new password',
                'rules'  => 'required',
                'errors' => [
                    'required' => 'Put your message here',

                ]
            ],        
            'confirm-new-password' => [
                'label'  => 'confirm password',
                'rules'  => 'required|matches[new-password]',
                'errors' => [
                    'required' => 'Put your message here',
                    'matches' => 'Put your message here'
                    ]
            ],            
        ];    
        
        if ($this->request->getMethod() === 'post' && $this->validate($rules)) {
            
            //Create new instance of the MythAuth UserModel
            $users = model(UserModel::class);
            
            //Get the id of the current user
            $user_id = user_id();
            
            //Create new user entity
            $entity = new User();
                        
            //Get current password from input field
            $newPassword = $this->request->getPost('new-password');
            
            //Hash password using the "setPassword" function of the User entity
            $entity->setPassword($newPassword);
            
            //Save the hashed password in the variable "hash"
            $hash  = $entity->password_hash;
            
            //update the current users password_hash in the database with the new hashed password.
            $users->update($user_id,['password_hash' => $hash]);

            //Return back with success message
            return redirect()->to('/test')->with('success', "Put your message here");    
        }
        else {
            //Return with errors
            return redirect()->to('/test')->withInput()->with('error', "Put your message here");                    
        }

    }
}
I hope that helps. If you have any questions, just ask! Smile
Thank you very much,very helpfull with the code that you provide.
Reply


Digg   Delicious   Reddit   Facebook   Twitter   StumbleUpon  


  Theme © 2014 iAndrew  
Powered By MyBB, © 2002-2021 MyBB Group.