-
Polymorphism Junior Member
 
-
Posts: 16
Threads: 9
Joined: Jun 2020
Reputation:
0
06-09-2021, 01:28 AM
(This post was last modified: 06-09-2021, 01:29 AM by Polymorphism.)
I'm building a simple signup form that has a password confirmation field and it uses the 'matches' validation rule. I can't get it to return true though even though I can var_dump the values and see that they are both the same.
Here is my UserModel:
PHP Code: class UserModel extends Model { protected $DBGroup = 'default'; protected $table = 'users'; protected $primaryKey = 'id'; protected $useAutoIncrement = true; protected $insertID = 0; protected $returnType = 'object'; protected $useSoftDelete = false; protected $protectFields = true; protected $allowedFields = ['username', 'email', 'password'];
// Dates protected $useTimestamps = false; protected $dateFormat = 'datetime'; protected $createdField = 'created_at'; protected $updatedField = 'updated_at'; protected $deletedField = 'deleted_at'; // Validation protected $validationRules = [ 'username' => 'required|min_length[2]|alpha_numeric', 'email' => 'required|valid_email', 'password' => 'required', 'password-confirm' => 'required|matches[password]' ];
protected $validationMessages = []; protected $skipValidation = false; protected $cleanValidationRules = true;
// Callbacks protected $allowCallbacks = true; protected $beforeInsert = []; protected $afterInsert = []; protected $beforeUpdate = []; protected $afterUpdate = []; protected $beforeFind = []; protected $afterFind = []; protected $beforeDelete = []; protected $afterDelete = []; }
Here is the method that deals with signing up the user:
PHP Code: /** * Create a new resource object, from "posted" parameters * * @return mixed */ public function create() { $user = new User();
/**------------------------------------------------------------------------------ * Validation ------------------------------------------------------------------------------*/ if (! $this->validate($user->validationRules)) { echo view('login/signup', [ 'validation' => $this->validation, ]); } else { $username = $this->request->getVar('username'); $email = $this->request->getVar('email'); $password = $this->request->getVar('password');
$userFound = $user->where('username', $username)->first(); $emailFound = $user->where('email', $email)->first();
/**------------------------------------------------------------------------------ * Check if username or email already exist. ------------------------------------------------------------------------------*/ if ($userFound) { $this->session->setFlashdata('message', "The username <strong>{$username}</strong> has already been taken. Please try another one."); return redirect()->to('signup'); } else if($emailFound) { $this->session->setFlashdata('message', "Another user is already using <strong>{$email}</strong>. Please try another one."); return redirect()->to('signup');
} else { $data = [ 'username' => $username, 'email' => $email, 'password' => password_hash($password, PASSWORD_DEFAULT), 'password-confirm' => $password ];
dump($user->insert($data));
dump($this->request->getVar('password')); dump($this->request->getVar('password-confirm'));
dump($user->errors());
$this->session->setFlashdata("message", "An account for <strong>{$username}</strong> has been created. Now you can login!"); return redirect()->to('/login'); } }
What am I doing wrong? I have used no quotes, double quotes and single quotes in the validation rule and I still get the correct result.
Some help would be greatly appreciated.
-
InsiteFX Super Moderator
     
-
Posts: 6,729
Threads: 344
Joined: Oct 2014
Reputation:
246
I think it has to do with the hyphen - sign in the rule name.
PHP Code: 'password-confirm' => 'required|matches[password]'
// change to this in all your code and form _ 'password_confirm' => 'required|matches[password]'
What did you Try? What did you Get? What did you Expect?
Joined CodeIgniter Community 2009. ( Skype: insitfx )
-
Polymorphism Junior Member
 
-
Posts: 16
Threads: 9
Joined: Jun 2020
Reputation:
0
06-09-2021, 05:05 AM
(This post was last modified: 06-09-2021, 05:22 AM by Polymorphism.)
(06-09-2021, 03:34 AM)InsiteFX Wrote: I think it has to do with the hyphen - sign in the rule name.
PHP Code: 'password-confirm' => 'required|matches[password]'
// change to this in all your code and form _ 'password_confirm' => 'required|matches[password]'
Thanks for helping me out with this. I ran a global find and replace for this and I'm still getting this error. Is there a very particular way to use the 'matches' rule?
I did also notice that I get an error saying that the 'password_confirm' field is missing from the $data array with I try to insert a new user, even though that its not a field in the database or on the $allowedFields array for the User class. I'm not sure that that is related though.
-
paliz Member
  
-
Posts: 236
Threads: 19
Joined: Oct 2020
Reputation:
1
06-09-2021, 10:54 AM
(This post was last modified: 06-09-2021, 09:10 PM by InsiteFX.)
[quote pid="387484" dateline="1623240301"]
donnot for got entity
look at my code model controler entity and view
PHP Code: <?php namespace CoreCommon\Controllers;
use CoreCommon\Entities\UsersEntity; use CoreCommon\Libraries\CustomFileSystem; use CoreCommon\Models\UsersModel; use CodeIgniter\HTTP\ResponseInterface;
class Profile extends ApiController {
/** * index function * @method : GET */ public function index() {
$this->setupAuthClasses(); $userModel = new UsersModel(); $user = $userModel->where('id', $this->userId)->get()->getResultObject();
return $this->respond([ 'data' => $user ], ResponseInterface::HTTP_OK, lang('Common.api.receive')); }
public function create() {
$userModel = new UsersModel(); $userEntity = new UsersEntity(); $usersMythAuth = new \Myth\Auth\Models\UserModel(); $isPassword = false; $customConfig = new \CoreCommon\Config\CoreAppConfig(); $imageService = \CodeIgniter\Config\Services::image(); $handyFunction = new CustomFileSystem();
if ($this->request) { //get request from Vue Js
$rules = [ 'first_name' => 'if_exist|required|max_length[255]', 'last_name' => 'if_exist|required|max_length[255]', 'address' => 'if_exist|required|max_length[255]', 'phone' => 'if_exist|required|max_length[11]', 'password' => 'if_exist|required', 'pass_confirm' => 'if_exist|required|matches[password]', 'gender' => 'if_exist|required', 'country' => 'if_exist|required|max_length[255]', 'city' => 'if_exist|required|max_length[255]', 'image' => 'if_exist|uploaded[image]|max_size[image,4096]|ext_in[avatar,png,jpg,jpeg,webp]',
];
if (!$this->validate($rules)) {
return $this->respond([ 'error' => $this->validator->getErrors(), 'success' => false ], ResponseInterface::HTTP_NOT_ACCEPTABLE, lang('Common.api.validation'));
}
$user = $usersMythAuth->where('id', $this->userId) ->first(); if (isset($this->request->getJSON()->password)) {
$user->password = $this->request->getJSON()->password; $user->reset_hash = null; $user->reset_at = null; $user->reset_expires = null; $user->force_pass_reset = false; $isPassword = true;
} else if (isset($this->request->getJSON()->first_name)) {
$userEntity->first_name = $this->request->getJSON()->first_name; $userEntity->last_name = $this->request->getJSON()->last_name; $userEntity->gender = $this->request->getJSON()->gender; } else if (isset($this->request->getJSON()->address)) { $userEntity->address = $this->request->getJSON()->address; $userEntity->country = $this->request->getJSON()->country; $userEntity->city = $this->request->getJSON()->city;
}
if (isset($_FILES['image'])) { $path = $userModel->where('id', $this->userId) ->first(); $handyFunction->removeSingleFile(ROOTPATH . $path->image); $avatar = $this->request->getFile('image'); $avatar->move($customConfig->uploadDirectory . '/profile', time() . '.' . $avatar->getClientExtension()); $userEntity->image = $avatar->getName(); $userEntity->editImage(); $imageService->withFile(ROOTPATH . $userEntity->image) ->withResource()->fit(100, 100, 'center') ->save(ROOTPATH . $userEntity->image, 90); }
if (is_null($user->phone) && isset($this->request->getJSON()->phone)) { $userEntity->phone = $this->request->getJSON()->phone;
} else if (is_null($user->email) && isset($this->request->getJSON()->email)) { $userEntity->email = $this->request->getJSON()->email; }
if ($isPassword == true) { if (!$usersMythAuth->save($user)) {
return $this->respond([ 'data' => $usersMythAuth->errors(), 'success' => false, ], ResponseInterface::HTTP_BAD_REQUEST, lang('Common.api.reject'));
} } else { if (!$userModel->update($this->userId, $userEntity)) {
return $this->respond([ 'data' => $userModel->errors(), 'success' => false, ], ResponseInterface::HTTP_BAD_REQUEST, lang('Common.api.reject'));
} }
return $this->respond([ 'success' => true,
], ResponseInterface::HTTP_CREATED, lang('Common.api.save')); }
}
}
<?php namespace CoreCommon\Entities;
use \CodeIgniter\Entity; use CodeIgniter\I18n\Time;
class UsersEntity extends Entity {
protected $id; protected $first_name; protected $last_name; protected $phone; protected $image; protected $address; protected $password_hash; protected $gender; protected $country; protected $city; protected $email;
protected $attributes = [ 'id' => null, 'first_name' => null, 'last_name' => null, 'phone' => null, 'email' => null, 'address' => null, 'image' => null, 'password_hash' => null, 'gender' => null, 'country' => null, 'city' => null, 'reset_hash' => null, 'reset_at' => null, 'reset_expires' => null, 'force_pass_reset' => null, ]; protected $datamap = [ ];
protected $dates = [];
protected $casts = [];
protected $permissions = [];
protected $roles = [];
public function setPassword() { $config = new \Myth\Auth\Config\Auth();
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 ]; } else { $hashOptions = [ 'cost' => $config->hashCost ]; }
$this->attributes['password_hash'] = password_hash( base64_encode( hash('sha384', $this->password_hash, 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; $this->attributes['force_pass_reset'] = false;
}
public function editImage() {
$this->attributes['image'] = 'public/upload/profile/' . $this->attributes['image'];
return $this; } }
<?php namespace CoreCommon\Models;
use CoreCommon\Entities\UsersEntity; use CodeIgniter\Model;
class UsersModel extends Model {
/** * table name */ protected $primaryKey = "id"; protected $table = "users";
/** * allowed Field */ protected $allowedFields = [ 'first_name', 'last_name', 'image', 'address', 'phone', 'email', 'password_hash', 'gender', 'country', 'city', 'reset_hash', 'reset_at', 'reset_expires', 'force_pass_reset', ];
protected $returnType = UsersEntity::class; protected $validationRules = [ 'first_name' => 'if_exist|required|max_length[255]', 'last_name' => 'if_exist|required|max_length[255]', 'image' => 'if_exist|required|max_length[255]', 'address' => 'if_exist|required|max_length[255]', 'phone' => 'if_exist|required|max_length[11]', 'email' => 'if_exist|required|valid_email|is_unique[users.email]', 'password_hash' => 'if_exist|required', 'gender' => 'if_exist|required', 'country' => 'if_exist|required|max_length[255]', 'city' => 'if_exist|required|max_length[255]', ]; protected $validationMessages = []; protected $skipValidation = false;
}
Enlightenment Is Freedom
-
najdanovicivan Not Newbie

-
Posts: 7
Threads: 1
Joined: Jan 2019
Reputation:
0
The issue here is that you have setPassword() which sets password_hash and then your rule in model is trying to match $attributes['password'] with $attributes['password-confirm'] the issue is that your entity contains $attributes['password_hash'] and not $attributes['password'] just note that validation in model class will be working with $attributes array which can be modified with setters so you should either hash the 'password-confirm' and match is with 'password_hash' or set the not hashed password in $attributes['password'] as well in the setter.
|