cakePHP isUnique is not working any more - cakephp

I had this validation rule for a long time and it always used to work correctly, but not any more.
public $validate = array(
'email'=>array(
'email'=>array(
'rule'=>array('email', true),
'message'=>'E-mail is not correct'
),
'isUnique'=>array(
'rule'=>'isUnique',
'message'=>'This email adddress is already in use'
),
'notEmpty'=>array(
'rule'=>'notEmpty',
'message'=>'Insert email address'
)
)
I have been testing many possible ways, but none of them seem to work. Any help is much appreciated.
Here is the add function from the controller:
public function add() {
if ($this->request->is('post')) {
if( $this->request->data[ 'User' ][ 'email' ] != $this->data[ 'User' ][ 'email_confirmation' ] ) {
$this->User->invalidate( 'email_confirmation', __('Emails dont match'));
}else{
//generate password
$generatedPassword = $this->getRandomString(6);
$this->request->data['User']['password'] = $generatedPassword;
if ($this->User->save($this->request->data)) {
$name = $this->request->data['User']['name'];
$email = $this->request->data['User']['email'];
$password = $generatedPassword;
$this->Session->setFlash(__('User has been saved'), 'positive_notification');
$this->redirect(array('action' => 'index'));
} else {
$this->Session->setFlash(__('User has not been saved'), 'negative_notification');
}
}}}
And here is the beforeSave()
public function beforeSave($options = Array()){
if(isset($this->data['User']['password'])){
$this->data['User']['password'] = AuthComponent::password($this->data['User']['password']);
}
if(isset($this->data[$this->alias]['password1'])){
$this->data[$this->alias]['password'] = AuthComponent::password($this->data[$this->alias]['password1']);
}
return true;
}
Here is the query that is being executed while saving:
INSERT INTO `schedule`.`users` (`employee_nr`, `name`, `surname`, `email`, `phone`, `address`, `post_nr`, `city`, `role`, `company_id`, `password`) VALUES ('1', 'Name', 'Surname', 'email#email.com', '11223344', '', '', '', 'employee', 54, '389be16c83bf2e65a64f727465ec0c37a77552a5')

Test isUnique by using in you controller to see why it is not working. isUnique validation rule uses isUnique model method.

try this
public $validate = array(
'email' => array(
'rule1' => array(
'rule' => 'email',
'message' => 'Please enter a valid email address.'
),
'rule2' => array(
'rule' => 'isUnique',
'message' => 'That email address exists.'
)
),

Related

Cake php modal validation error

I have a simple registration form and complete model validation.
public function add() {
// Has any form data been POSTed?
if ($this->request->is('post')) {
$this->User->set($this->request->data); //echo '<pre>'; print_r($this->data);exit;
if($this->User->validates()){
if ($this->User->save($this->request->data)) {
// Set a session flash message and redirect.
$this->Session->setFlash('User Saved!');
return $this->redirect('/users');
}
}
}
}
Modal validation code is below
class User extends AppModel {
public $validate = array(
'username' => array(
'alphaNumeric' => array(
'rule' => 'alphaNumeric',
'required' => true,
'message' => 'Alphabets and numbers only'
),
'between' => array(
'rule' => array('between', 5, 15),
'message' => 'Between 5 to 15 characters'
)
),
'password' => array(
'rule' => array('minLength', '8'),
'message' => 'Minimum 8 characters long'
),
'email' => 'email',
'born' => array(
'rule' => 'date',
'message' => 'Enter a valid date',
'allowEmpty' => true
)
);
}
The problem is that when i delete html fields using firebug and submit form it save data with blank entries . i think its a big problem i am facing because it not good practice to save blank entry and i want to stop it by the hacker or any one.
please help.
Add the validation rule 'notEmpty' for all fields which shouldn't be blank entries in the database.
Reference: cookbook
I am agree with semmelbroesel13
please use notEmpty rules as:
'rule' => array('notempty')
Updated:
Please try below code and check whats the query exactly
public function add() {
// Has any form data been POSTed?
if ($this->request->is('post')) {
$this->User->set($this->request->data); //echo '<pre>'; print_r($this->data);exit;
if($this->User->validates()){
if ($this->User->save($this->request->data)) {
$log=$this->User->getDataSource()->getLog(false, false);
echo "<pre>";print_r($log);exit;
// Set a session flash message and redirect.
$this->Session->setFlash('User Saved!');
return $this->redirect('/users');
}
}
}
}

linking tables cakephp

Hi all I finally got my validation for my invoices model working 100% but now its thrown off my validation in relationship model(which was working) because now it references everything in the wrong table.
The relationship model is supposed to make sure that a user exists in the users table before you can send them a request.
The invoice model is supposed to make sure that a user has a column with another user in the the relationship table.
how can I change it to make it work properly? At the moment the code completely throws off my entire relationship side of the website.
-relationship model
class Relationship extends AppModel
{
var $name = 'Relationship';
public $useTable = 'relationships_users';
public $primaryKey = 'id';
public $hasMany = array(
'Invoice' =>
array(
'className' => 'Invoice',
'joinTable' => 'invoice',
'foreignKey' => 'invoice_id'));
public $belongsTo = array(
'User' =>array(
'className' => 'User',
'foreignKey' =>'partyone','partytwo',
'associationForeignKey' => 'username',
));
var $validate = array(
'date' => array(
'rule' => array(
'datevalidation',
'systemDate'
),
'message' => 'Current Date and System Date is mismatched'
),
'partytwo' => array(
'userExists' => array(
'rule' => array(
'userExists',
),
'message' => 'That username doesnt exist.'
),
),
);
function datevalidation($field = array(), $compare_field = null)
{
if ($field['date'] > $compare_field)
return TRUE;
else
return FALSE;
}
function userExists($check)
{
$userExists = $this->User->find('count', array('conditions' => array('User.username'=>$check)));
if ($userExists == 1) {
return TRUE;
}
else
return FALSE;
}
-user model
<?php
App::uses('AuthComponent', 'Controller/Component');
class User extends AppModel{
public $name = 'User';
public $hasMany = array(
'Relationship' =>
array(
'className' => 'Relationship',
'joinTable' => 'relationships_users',
'foreignKey' => 'id',
'unique' => false,));
public $useTable = 'users';
public $primaryKey = 'id';
public $validate = array(
'username'=>array(
'The username must be between 5 and 15 characters.'=>array(
'rule'=>array('between', 5, 15),
'message'=>'The username must be between 5 and 15 characters.'
),
'That username has already been taken'=>array(
'rule'=>'isUnique',
'message'=>'That username has already been taken.'
)),
'email'=>array(
'Valid email'=>array(
'rule'=>array('email'),
'message'=>'Please enter a valid email address'
)
),
'password'=>array(
'Not Empty'=>array(
'rule'=>'notEmpty',
'message'=>'Please enter your password'
)
),
'Match passwords'=>array(
'rule'=>'matchPasswords',
'message'=>'Your passwords do not match'
)
,
'password_confirmation'=>array(
'Not Empty'=>array(
'rule'=>'notEmpty',
'message'=>'Please confirm your password'
)));
public function matchPasswords($data){
if ($data['password']==$this->data['User']['password_confirmation']){
return true;
}
$this->invalidate('password_confirmation','Your passwords do not match');
return false;
}
public function beforeSave(){
if(isset($this->data['User']['password'])){
$this->data['User']['password'] = AuthComponent::password($this->data['User']['password']);
}
return true;
}
}
?>
invoice model-
class Invoice extends AppModel{
var $name='Invoice';
//public $useTable = 'invoices';
//public $primaryKey = 'id';
public $belongsTo = array(
'Relationship' =>array(
'className' => 'Relationship',
'foreignKey' =>'relationship_id',
)
);
var $validate = array(
'to' => array(
'relationshipExists' => array(
'rule' => array(
'relationshipExists',
),
'message' => 'sorry you dont have a relationship with that user.'
),
),
);
var $validateTwo = array(
'datecreated'=>array(
'dateHasntExpired' => array(
'rule'=>array(
'dateHasntExpired',
),
'message'=> 'sorry but your relationship has expired.'
),
),
);
public function relationshipExists($check){
$relationshipExists=$this->Relationship->find('count', array(
'conditions' => array(
'Relationship.partyone <>' => current($check),
'Relationship.partytwo' => current($check),
// 'Relationship.active'==true,
// get the value from the passed var
)
));
if ($relationshipExists == true) {
return TRUE;
}
else
return FALSE;
}
public function dateHasntExpired($check){
$dateHasntExpired=$this->Relationship->find('count', array(
'conditions'=>array(
'DATE(Relationship.expirydate) > DATE(Invoice.datecreated)',
)));
if ($dateHasntExpired == true) {
return TRUE;
}
else
return FALSE;
}
}
here is the error that comes up when trying to view current relationship requests
Database Error
Error: SQLSTATE[42S22]: Column not found: 1054 Unknown column 'Invoice.invoice_id' in 'field list'
SQL Query: SELECT `Invoice`.`id`, `Invoice`.`to`, `Invoice`.`biller`, `Invoice`.`subject`, `Invoice`.`description`, `Invoice`.`amount`, `Invoice`.`datecreated`, `Invoice`.`duedate`, `Invoice`.`invoice_id` FROM `pra_cake`.`invoices` AS `Invoice` WHERE `Invoice`.`invoice_id` IN (97, 98, 99, 101, 104, 105)
Notice: If you want to customize this error message, create
app\View\Errors\pdo_error.ctp
and here is the error i get when trying to view the relationship requests ive sent
Database Error
Error: SQLSTATE[42S22]: Column not found: 1054 Unknown column 'Invoice.invoice_id' in 'field list'
SQL Query: SELECT `Invoice`.`id`, `Invoice`.`to`, `Invoice`.`biller`, `Invoice`.`subject`, `Invoice`.`description`, `Invoice`.`amount`, `Invoice`.`datecreated`, `Invoice`.`duedate`, `Invoice`.`invoice_id` FROM `pra_cake`.`invoices` AS `Invoice` WHERE `Invoice`.`invoice_id` IN (97, 98, 99, 101, 104, 105)
Notice: If you want to customize this error message, create app\View\Errors\pdo_error.ctp
needed to use the unbind method in my controllers, here is an example of the unbind method I used throughout my relationship controller.
public function approve($id=null){
$this->set('title_for_layout', 'Relationships');
$this->set('stylesheet_used', 'homestyle');
$this->set('image_used', 'eBOXLogoHome.jpg');
$this->layout='home_layout';
$this->Relationship->unbindModel(array('hasMany'=>array('Invoice')));
if ($this->request->is('get')) {
$this->request->data = $this->Relationship->read(NULL, $id);
} else {
//sets active to 1
$this->Relationship->read(null, $id);
$this->Relationship->set(array('active' => true,));
if ($this->Relationship->save($this->request->data)) {
$this->Session->setFlash('Your post has been updated.');
$this->redirect(array('action' => 'request'));
} else {
$this->Session->setFlash('Unable to update your post.');
}
}
and because this threw errors in my invoice controller I used unbind there as well and here is an example of the unbind I used in invoicescontroller
public function viewInvoice($id = NULL){
$this->set('title_for_layout', 'View invoice');
$this->set('stylesheet_used', 'homestyle');
$this->set('image_used', 'eBOXLogoHome.jpg');
$this->Invoice->unbindModel(array('belongsTo'=>array('Relationship')));
$this->set('invoice', $this->Invoice->read(NULL, $id));
}

Can Cake Php Validation clear input field value

Can Cake Php Validation clear input field value
var $validate = array(
'name' => array(
'isUnique' => array (
'rule' => 'isUnique',
'message' => 'This Person name already exists.'
)
)
);
If error persist in validation, I want to clear name field value. Is it possible to do so with cake php validation itself ?
You can do it with a custom validation rule if you wanted.
var $validate = array(
'name' => array(
'isUnique' => array (
'rule' => 'ifNotUniqueClear', // use custom rule defined below
'message' => 'This Person name already exists.'
)
)
);
function ifNotUniqueClear(&$data) {
$field = key($data);
// see if the record exists
$user = $this->find('first', array(
'conditions' => array(
$field => $data[$field]
),
'recursive' => -1
));
if ($user) {
// unset or empty it, your choice
unset($this->data[$this->alias][$field]);
return false;
}
return true;
}

Lots of Login Code

This is a fairly long question but I have know idea where it's going wrong. I am making an ajax login script using CakePHP 2.0 but it keeps failing. I will post all of my code, and i hope someone has the time to go through it.
This is my sql Database
AccountID AccountEmail AccountPassword AccountActive
1 chris#hotmail.co.uk pass 0
2 chris#gmail.com pass 1
This is my relevant Model Code
class Account extends AppModel {
public $name = 'Account';
public $validate = array(
'AccountEmail' => array(
'required' => array(
'rule' => array('notEmpty'),
'message' => 'Please Enter A Valid Email.'
),
'email' => array(
'rule' => array('email', true),
'message' => 'Please supply a valid email address.'
)
),
'AccountPassword' => array(
'required' => array(
'rule' => array('notEmpty'),
'message' => 'Please Enter A Valid Password.'
)
)
);
}
This is my relevant Controller Code
class AppController extends Controller {
/**
* Class Variables
*/
public $helpers = array('Js', 'Html', 'Session', 'Form');
public $components = array(
'Session',
'RequestHandler',
'Auth' => array(
'logoutRedirect' => array(
'controller' => 'Accounts',
'action' => 'login'
),
'authError' => 'You can\'t Access That Page',
'authorize' => array('Controller'),
'authenticate' => array(
'Form' => array(
'fields' => array(
'username' => 'AccountEmail',
'password' => 'AccountPassword'
),
'scope' => array('AccountActive' => '1')
)
)
)
);
}
class AccountsController extends AppController {
/**
* Class Variables
*/
public $name = 'Accounts';
public $layout = 'Accounts';
/**
* Class Functions
*/
public function login()
{
if ($this->request->is('ajax')) {
$this->Account->set($this->data);
if ($this->Account->validates()) {
if($this->Auth->login()) {
echo "logged In";
exit;
} else {
echo "Login Failed";
exit;
}
} else {
echo 'validation/' . json_encode($this->Account->invalidFields());
exit;
}
}
}
I don't think there is anything else. Again i'm sorry for the huge amount of code but i just don't know what you need.
The info is all passed via 'echo' to jquery which at the moment is just displaying the response via 'alert'.
I know the validation is working, but if i enter the info of someone who should be able to login it just shows "Login Failed". Thanks For Your Time.
Your passwords in the database need to be in their hashed form. Using Cake's default settings, 'pass' would be: 1c31af5bd9913ff511fe780f506e6fab68979b90

Cakephp registration problem

I followed tutorial on CakephpTV to make registration by AuthComponent. Yesterday everything worked good, but today it isn't.
When I'm trying to add new account it says that passwords do not match, and in password field there is hashed password and in password confirmation there is normal (not hashed) password.
My UserController class:
class UsersController extends AppController
{
function beforeFilter() {
parent::beforeFilter();
$this->Auth->allow('new_user');
if($this->action == 'add' || $this->action == 'edit') {
$this->Auth->authenticate = $this->User;
}
}
function new_user()
{
if (!empty($this->data)) {
if ($this->User->save($this->data)) {
$this->Session->setFlash('Rejestracja zakończona pomyślnie');
$this->redirect(array('action' => 'index'));
}
}
}
function login() {
}
function logout() {
$this->redirect($this->Auth->logout());
}
}
My User model:
class User extends AppModel {
var $name = 'User';
var $validate = array (
'email' => array(
'Please supply a valid email address.' => array(
'rule' => 'email',
'message' => 'Please supply a valid email address.'
),
'Already exists' => array(
'rule' => 'isUnique',
'message' => 'Must be unique'
)
),
'password' => array (
'aThis field must have between 6 and 40 alphanumeric characters.' => array(
'rule' => '/^[^\'"]{6,40}$/i',
'message' => 'aThis field must have between 6 and 40 alphanumeric characters.'
),
'Do not match' => array(
'rule' => 'matchPasswords',
'message' => 'Do not match'
)
)
);
function matchPasswords($data) {
if($data['password'] == $this->data['User']['password_confirmation']) {
return TRUE;
}
$this->invalidate('password_confirmation', 'DO not match');
return FALSE;
}
function hashPasswords($data) {
if(isset($this->data['User']['password'])) {
$this->data['User']['password'] = Security::hash($this->data['User']['password'], NULL, TRUE);
return $data;
}
return $data;
}
function beforeSave() {
$this->hashPasswords(NULL, TRUE);
$this->data['User']['registration_date'] = date("Y-m-d H:i:s");
return TRUE;
}
}
My new_user.ctp:
echo $this->Form->create('User', array('action' => 'new_user'));
echo $this->Form->input('email');
echo $this->Form->input('password');
echo $this->Form->input('password_confirmation',array('type' => 'password'));
echo $this->Form->end('Zarejestruj');
My AppController class:
class AppController extends Controller {
var $components = array('Auth','Session');
function beforeFilter() {
$this->Auth->fields = array('username' => 'email', 'password' => 'password');
$this->Auth->allow('index','view','display','new_user');
$this->Auth->authError = 'Zaloguj się aby zobaczyć tą stronę.';
$this->Auth->loginError = 'Wprowadzono niepoprawne dane.';
$this->Auth->loginRedirect = array('controller'=>'pages','action'=>'home');
$this->Auth->loginRedirect = array('controller'=>'pages','action'=>'home');
}
}
CakePHP automatically hashes fields named password in a User model. This is why you get an already hashed password back when the form fails. You might want to check if the hash you get back is the same hash as you'd expect to get back.
Apart from that, in your function matchPasswords your checking on $this->data['password'] whereas I think that should be $this->data['User']['password'].

Resources