Help Me Mon Jan 02 05:38:33 -0500 2012

Subject: [Solved] Validate repassword without saving into DB

Validate repassword without saving it.

Here is the code:

Controller:

 1 if($_POST)
 2 {
 3     $register = new User(array(
 4         'username' => $_POST['username'],
 5         'password' => $_POST['password'],
 6         'first_name' => $_POST['first_name'],
 7         'last_name' => $_POST['last_name'],
 8         'email' => $_POST['email']
 9     ));
10 
11     $register->re_password = $_POST['re_password'];
12 
13     if($register->is_valid())
14     {
15         $register->save();
16         redirect('users/login');
17     }
18     else
19     {
20         echo '<pre>';
21         print_r($register->errors->full_messages());
22         echo '</pre>';
23     }
24 }

Model:

 1 <?php
 2 
 3 class User extends ActiveRecord\Model
 4 {
 5     var $password = FALSE;
 6     var $re_password = FALSE;
 7 
 8     static $validates_presence_of = array(
 9         array('username'),
10         array('password'),
11         array('first_name'),
12         array('last_name'),
13         array('email')
14     );
15 
16     static $validates_size_of = array(
17         array('username', 'within' => array(3,15)),
18         array('password', 'minimum' => 6),
19         array('first_name', 'within' => array(2, 15)),
20         array('last_name', 'within' => array(2, 15)),
21     );
22 
23     static $validates_uniqueness_of = array(
24         array('username', 'message' => 'is already used.')
25     );
26 
27     static $validates_format_of = array(
28          array('email', 'with' => '/^[^0-9][A-z0-9_]+([.][A-z0-9_]+)*[@][A-z0-9_]+([.][A-z0-9_]+)*[.][A-z]{2,4}$/')
29     );
30 
31     public function validate()
32     {
33         if($this->password != $this->re_password || $this->re_password != $this->password)
34         {
35             $this->errors->add('Password', "and retype password must me be the same.");
36         }
37     }
38 
39     function before_save()
40     {
41         if($this->password)
42         {
43             $this->hashed_password = $this->hash_password($this->password);
44         }
45     }
46 
47     private function hash_password($password)
48     {
49         $salt = bin2hex(mcrypt_create_iv(32, MCRYPT_DEV_URANDOM));
50         $hash = hash('sha256', $salt . $password);
51 
52         return $salt . $hash;
53     }

View:

 1 <?=form_open()?>
 2 
 3 <?$this->load->view('layouts/_flash')?>
 4 
 5 <p>
 6     Username: <?=form_input('username', set_value('username'))?>
 7 </p>
 8 <p>
 9     Password: <?=form_password('password')?>
10 </p>
11 <p>
12     Retype password: <?=form_password('re_password')?>
13 </p>
14 <p>
15     First name: <?=form_input('first_name', set_value('first_name'))?>
16 </p>
17 <p>
18     Last name: <?=form_input('last_name', set_value('last_name'))?>
19 </p>
20 <p>
21     Email: <?=form_input('email', set_value('email'))?>
22 </p>
23 
24 <?=form_submit('submit', 'Register')?>
25 <?=form_close()?>


Mr. Carl Thu Jan 26 22:51:26 -0500 2012

Take look at associations maybe? http://www.phpactiverecord.org/projects/main/wiki/Associations

Need more details.

What are the two form simple details will work.
How do each form relate to each other in the database?
Etc..

Help Me Fri Jan 27 20:08:40 -0500 2012

Hey ty for reply,, finaly! :)

I want password and re_password field. for this i want to use the validation function of activerecord.

Mr. Carl Fri Jan 27 23:08:18 -0500 2012

You want two input not two forum, also in Model–View–Controller (MVC) what you want would be done in C. For more information in Model–View–Controller.

See Form Validation and Input Class . These will make BIG DIFFERENT in security and coding.

In example on how to use the forum validation code clip from Ion Auth 2 is example controller 'auth' method create user. The methods in this code clip is using built-in class/method in CodeIgniter. Also use "$this->input->post()" to get the data from $_POST

 1 //create a new user
 2 function create_user()
 3 {
 4     //validate form input
 5     $this->form_validation->set_rules('first_name', 'First Name', 'required|xss_clean');
 6     // more input for the forum
 7     $this->form_validation->set_rules
 8     (
 9         'password', 'Password',
10          'required|min_length[8]|max_length[30]|matches[password_confirm]'
11     ); //Must be in length limit AND match password_confirm
12     $this->form_validation->set_rules
13     (
14         'password_confirm', 'Password Confirmation', 'required'
15     );
16 
17     if ($this->form_validation->run() == true)
18     {
19         //save into database
20     }
21     else
22     {
23         //deal with error
24     }
25 
26     //etc
27 }

What you want is more of a fat model which I'm not saying its wrong or right.

If you also want it in the model you need to create two function both which are public: set_password_confirm($password_confirm) and validate(), and private variable called $_password_confirm.

For reason why "set_password_confirm($password_confirm)" code clip from php.activerecored::Model.php:

 1      * Define customer setters methods for the model.
 2      *
 3      * You can also use this to define custom setters for attributes as well.
 4      *
 5      * class User extends ActiveRecord\Model {
 6      *   static $setters = array('password','more','even_more');
 7      *
 8      *   # now to define the setter methods. Note you must
 9      *   # prepend set_ to your method name:
10      *   function set_password($plaintext) {
11      *     $this->encrypted_password = md5($plaintext);
12      *   }
13      * }
14      *
15      * $user = new User();
16      * $user->password = 'plaintext';  # will call $user->set_password('plaintext')

For reason why "validate()" see validate custom
WARNING: You place this logic in a public method named validate. (This feature is available since v1.1
or nightly builds.)

Help Me Sun Jan 29 11:31:54 -0500 2012

Again thanks for the reply...

You are right its input instead of form's...

So i made a simpel code to test if it's working....

Error massage I get:
Fatal error: Call to undefined method Users::_validate() in /home/test/domains/test.nl/public_html/sparks/php-activerecord/0.0.2/vendor/php-activerecord/lib/Model.php on line 1077

Controller:

 1 public function register()
 2 {
 3     if($_POST)
 4     {
 5         $register = User::is_valid(array(
 6             'username' => $_POST['username'],
 7             'password' => $_POST['password']
 8         ));
 9 
10         if($register)
11         {
12             redirect('users/login');
13         }
14         else
15         {
16             print_r ($register->errors->full_messages());
17         }
18     }
19 }

Model:

 1 class User extends ActiveRecord\Model
 2 {
 3     var $password = FALSE;
 4 
 5     static $validates_size_of = array(
 6         array('username', 'within' => array(3,15)),
 7         array('password', 'minimum' => 6)
 8     );
 9 
10     function before_save()
11     {
12         if($this->password)
13         {
14             $this->hashed_password = $this->hash_password($this->password);
15         }
16     }
17 
18     private function hash_password($password)
19     {
20         $salt = bin2hex(mcrypt_create_iv(32, MCRYPT_DEV_URANDOM));
21         $hash = hash('sha256', $salt . $password);
22 
23         return $salt . $hash;
24     }

Mr. Carl Sun Jan 29 14:14:11 -0500 2012

Baycan Aydin wrote:

Error massage I get: Fatal error: Call to undefined method Users::_validate() in /home/test/domains/test.nl/public_html/sparks/php-activerecord/0.0.2/vendor/php-activerecord/lib/Model.php on line 1077

From what I can tell you using sparks version 0.0.2 of PHP.active-record (PHP AR) which the stable version non-sparks is version 1.0.0. So from what I can tell you using very out-date version of PHP AR. I don't know the different between spark and non-spark. I also don't see the method in Model::is_valid taking argument (unless it using PHP function magic or on the website docs.

You may also want to look at using the latest nightly build vs using the stable build because the stable is out-of-date and missing some of the fix/new feature the nightly build has. However, nightly build maybe unstable.

For user class and form validation may want to place upper limit on the password of 100 character or so.
Some SOB may try dump library full of texts in the password that cause slow down when hashing the password

Using your user class this is what my function user::register would look like:

List of topic in the code below
Validation Rules
Prepping Data
Re-populating the form

Custom code from Ion Auth 2 (WTF - I can't get coloring in the code for some reason...)

  1 //create a new user
  2 public function create_user()
  3 {
  4     $this->data['title'] = "Create User";
  5 
  6     // If user login and NOT a admin then redirect to home page
  7 
  8     //validate form input
  9     // See Setting Validation Rules
 10     // I place 'trim' which is PHP function to remove space from the input 
 11     // BEFORE validating it. See Prepping Data
 12     $this->form_validation->set_rules('first_name', 'First Name', 'trim|required|xss_clean');
 13     $this->form_validation->set_rules('last_name', 'Last Name', 'trim|required|xss_clean');
 14     $this->form_validation->set_rules('email', 'Email Address', 'trim|required|valid_email');
 15     // Etc
 16     $this->form_validation->set_rules
 17     (
 18         'password', 'Password', 
 19         'trim|required|min_length[5]|max_length[30]|matches[password_confirm]'
 20     );
 21     $this->form_validation->set_rules
 22     (
 23         'password_confirm', 
 24         'Password Confirmation', 'required'
 25     );
 26 
 27     // Check if the form is validate and generate error.
 28     // NOTE! It will NOT generate if NONE of the form_validation->set_rules
 29     // variable are there
 30     // So no checking if submit, VERY nice feature
 31     if ($this->form_validation->run() == true)    
 32     { // Check if user submiting data
 33 
 34         // Pass all data to model. Model whitelist will deal with mass-assignment calls
 35         $user = new User( $this->input->post() );
 36 
 37         try
 38         {
 39             // Class validate the data before saving and then save to database
 40             // If validation or save to database fails the class return false
 41             // Class user WILL throw if there duplicate primary key 
 42             // or index (I think on index)
 43             if($user->save() === True)
 44             {                
 45                 // Redict the user's browser to view the new created customer/client
 46                 redirect('user/view/'.$user->id, 'location');
 47             }
 48 
 49             // create the index for the first time
 50             $this->data['message'] = '';
 51 
 52             // Get the list/reason why the User model rejected the save
 53             foreach($customer->errors as $errorMsg)
 54             {
 55                 $this->data['message'] .= '<p>'.$errorMsg.'</p>';
 56             }
 57         }
 58         catch(ActiveRecord\ActiveRecordException $ex) // This is php.activerecored
 59         {
 60             //Log problem on server side
 61             $message = "Trying to creat client: -".print_r($user, true)
 62             ."- caused ActiveRecord\ActiveRecordException because: " 
 63                 .$ex->getMessage();
 64 
 65             // CodeIgniter class that log the error which 
 66             // I extend to log it save the error in the database
 67             log_message('error', $message);
 68 
 69             // CodeIgniter: Send message to user and exit the php
 70             show_error('Unable to create client');
 71         }
 72         // May want to add Exception if worest case.. MAYBE???
 73     }
 74     else
 75     {     //display the create user form
 76         //Get the error from the form_validation or NULL if there none
 77         //See Re-populating the form
 78         $this->data['message'] = validation_errors();
 79 
 80         // Building the input data and get user data on failed submit
 81         // 
 82         $this->data['first_name'] = array('name' => 'first_name',
 83             'id' => 'first_name',
 84             'type' => 'text',
 85             'value' => $this->form_validation->set_value('first_name'),
 86         );
 87         // etc
 88         $this->data['password'] = array('name' => 'password',
 89             'id' => 'password',
 90             'type' => 'password',
 91             'value' => $this->form_validation->set_value('password'),
 92         );
 93         $this->data['password_confirm'] = array('name' => 'password_confirm',
 94             'id' => 'password_confirm',
 95             'type' => 'password',
 96             'value' => $this->form_validation->set_value('password_confirm'),
 97         );
 98 
 99         // Load the file that has the html and php..
100         $this->load->view('auth/create_user', $this->data);
101     }
102 }

Help Me Sun Jan 29 16:44:42 -0500 2012

ty for showing example from ion_aut2 but he is using the validation of codeigniter not phpactiverecord....

sparks/activerecord/0.0.2 is the nightlybuild

Mr. Carl Sun Jan 29 21:46:14 -0500 2012

Baycan Aydin wrote:

ty for showing example from ion_aut2 but he is using the validation of codeigniter not phpactiverecord....

In my controller all CodeIgniter Form Rules are base off PHP AC models rules. I building a function that converts PHP AC model rules to CodeIgniter Form Rules. However, so far the convert lack CodeIgniter Form Rule for PHP AC rules: 'allow_blank', 'allow_null', (however I don't need because input form form is never value of null), validates_inclusion_of, validates_exclusion_of, validates_format_of, even/odd number, and validates_uniqueness_of.

I use CodeIgniter Form Rules for layer protection and it keep my code looking clean. Plus I still use PHP AC rules to catch any rules CodeIgniter Form Rules missed. Also later I move copy of those rules to javascipt.

The layer of protection is the same idea be hide layer of security for server/network/etc. For example why should Sony Pictures + PlayStation

(1-7/7)