Welcome Guest, Not a member yet? Register   Sign In
Why Does CodeIgniter Shield Hash Passwords After User Data Insertion?
#1

Hi everyone!

I'm studying the CodeIgniter Shield code and noticed that the password hash seems to be done after inserting the user's data into the database. Could someone confirm if this is correct and explain why this approach was chosen?Here is a part of the UserModel and User entity code showing this:UserModel.php

UserModel.php
PHP Code:
protected $afterInsert  = ['saveEmailIdentity'];
protected 
$afterUpdate  = ['saveEmailIdentity'];

protected function 
saveEmailIdentity(array $data): array
{
    if ($this->tempUser === null) {
        return $data;
    }

    if ($this->tempUser->id === null) {
        $user $this->find($this->db->insertID());
        $this->tempUser->id $user->id;

        $user->email $this->tempUser->email ?? '';
        $user->password $this->tempUser->password ?? '';
        $user->password_hash $this->tempUser->password_hash ?? '';

        $user->saveEmailIdentity();
        $this->tempUser null;

        return $data;
    }

    $this->tempUser->saveEmailIdentity();
    $this->tempUser null;

    return $data;



User.php
PHP Code:
public function saveEmailIdentity(): bool
{
    if (empty($this->email) && empty($this->password) && empty($this->password_hash)) {
        return true;
    }

    $identity $this->getEmailIdentity();
    if ($identity === null) {
        $this->createEmailIdentity([
            'email' => $this->email,
            'password' => '',
        ]);

        $identity $this->getEmailIdentity();
    }

    if (!empty($this->email)) {
        $identity->secret $this->email;
    }

    if (!empty($this->password)) {
        $identity->secret2 service('passwords')->hash($this->password);
    }

    if (!empty($this->password_hash) && empty($this->password)) {
        $identity->secret2 $this->password_hash;
    }

    $identityModel model(UserIdentityModel::class);

    try {
        $identityModel->save($identity);
    } catch (DataException $e) {
        if (in_array($e->getMessage(), [
            lang('Database.emptyDataset', ['insert']),
            lang('Database.emptyDataset', ['update']),
        ], true)) {
            return true;
        }

        throw $e;
    }

    return true;


Why is the password hashed after insertion and not before?
Reply




Theme © iAndrew 2016 - Forum software by © MyBB