Lots of Login Code - cakephp-2.0

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

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');
}
}
}
}

cake php form validation is not working for me

I have a a form which adds first_name and last_name of user in cakephp.
here is the code
code for view (add.ctp)
<?php
echo $this->Form->create('User');
echo $this->Form->input('first_name',array('label'=>'First Name'));
echo $this->Form->input('last_name',array('label'=>'Last Name'));
echo $this->Form->end('Add User');
?>
code for UserController (UsersController.php)
<?php
public function add(){
if($this->request->is('post')){
$addData = $this->request->data;
$this->User->create();
if($this->User->save($addData)){
$this->Session->setFlash('User has been added successfully');
$this->redirect(array('action'=>'index'));
}
}
}
?>
view code for User Model (UserModel.php)
<?php
class UserModel extends AppModel{
public $validate = array(
'first_name' => array(
'rule' => 'notEmpty',
'message' => 'first name should not be empty.'
),
'last_name' => array(
'rule' => 'notEmpty',
'message' => 'last name should not be empty.'
)
);
}
?>
This is the code I am using, I have seen on cakebook as well and used various other rules, but no validation is working for my form. Can some please help me what could be the reason ?
Thanks in advance!
Your model filename is incorrect. It should be User.php not UserModel.php
please change your file name to user.php if your using table name in mysql as users instead of UserModel.php
and your classname must be like below
<?php
class User extends AppModel{
var $name = 'User';
public $validate = array(
'first_name' => array(
'rule' => 'notEmpty',
'message' => 'first name should not be empty.'
),
'last_name' => array(
'rule' => 'notEmpty',
'message' => 'last name should not be empty.'
)
);
}
?>
Your model name should be User (as your table name and controller name is users).
So try this in your model file(User.php)
<?php
App::uses('AppModel', 'Model');
class User extends AppModel{
public $validate = array(
'first_name' => array(
'rule' => 'notEmpty',
'message' => 'first name should not be empty.'
),
'last_name' => array(
'rule' => 'notEmpty',
'message' => 'last name should not be empty.'
)
);
}

Cakephp 2.0 Localization for Model Messages

I am trying to get i18n to extract the strings from my model in Cakephp 2.0
The documentation states that
"CakePHP will automatically assume that all model validation error messages in your $validate array are intended to be localized. When running the i18n shell these strings will also be extracted."
http://book.cakephp.org/2.0/en/core-libraries/internationalization-and-localization.html
But my messages in my model are not being extracted into my po file when I run cake i18n and extract the data.
Does anyone know how to get the message strings into the po file?
App::uses('AuthComponent', 'Controller/Component');
class User extends AppModel {
public $validate = array(
'username' => array(
'required' => array(
'rule' => array('notEmpty'),
'message' => 'A Username is required',
'rule' => 'isUnique',
'message' => 'This username has already been taken'
)
);
}
This is how you can solve the problem I came across.
App::uses('AuthComponent', 'Controller/Component');
class User extends AppModel {
function __construct() {
parent::__construct();
$this->validate = array(
'username' => array(
'required' => array(
'rule' => array('notEmpty'))
'message' => __('A Username is required', true)),
'unique' => array(
'rule' => 'isUnique',
'message' => _('This username has already been taken', true)
)
);}
}
The correct way of achieve this is:
class AppModel extends Model {
public $validationDomain = 'validation_errors';
.
.
.
}
internally cake will call:
__d('validation_errors', 'Username should be more fun bla bla');
http://book.cakephp.org/2.0/en/console-and-shells/i18n-shell.html#model-validation-messages
http://book.cakephp.org/2.0/en/core-libraries/internationalization-and-localization.html#translating-model-validation-errors
Your $validate structure is a little messed up, you have two identical array keys (rule,message) under the required key. It should be:
public $validate = array(
'username' => array(
'required' => array(
'rule' => array('notEmpty'),
'message' => __('A Username is required', true),
),
'unique'=>array(
'rule' => 'isUnique',
'message' => __('This username has already been taken', true)
)
)
);

cakephp login page doesn't go anywhere

I have tried to set up a login page, but when I try to log in, even with a wrong username/password, cake redirects to the login page (the logout function redirects correctly). Even if I plug in the wrong info, I get no error flashes at all, I don't get it. Here is my controller code:
class UsersController extends AppController {
public $name='Users';
public $layout='pagelayout';
public $uses=array('User');
public function beforeFilter() {
parent::beforeFilter();
$this->Auth->allow('add', 'logout', 'overview');
}
public function login() {
$this->set('title', 'Log in to your Gulf Shores 4 Less account');
if ($this->request->is('post')) {
if ($this->Auth->login()) {
return $this->redirect($this->Auth->redirect());
} else {
$this->Session->setFlash(__('Username or password is incorrect'), 'default', array(), 'auth');
}
}
}
and here is my model:
<?php
App::uses('AuthComponent', 'Controller/Component');
class User extends AppModel {
public $name='User';
public $hasMany=array('Unit', 'Complex', 'Coupon', 'Location', 'Image', 'Charter', 'Course', 'Nightclub', 'Store');
public function beforeSave() {
if (isset($this->data[$this->alias]['password'])) {
$this->data[$this->alias]['password'] = AuthComponent::password($this->data[$this->alias]['password']);
}
return true;
}
public $validate = array(
'username' => array(
'required' => array(
'rule' => array('notEmpty'),
'message' => 'A username is required'
)
),
'password' => array(
'required' => array(
'rule' => array('notEmpty'),
'message' => 'A password is required'
)
),
'role' => array(
'valid' => array(
'rule' => array('inList', array('admin', 'advertiser')),
'message' => 'Please enter a valid role',
'allowEmpty' => false
)
)
);
}
?>
Here is the code from AppController:
<?php
class AppController extends Controller {
public $components = array(
'Session',
'Auth' => array(
'loginRedirect' => array('controller' => 'users', 'action' => 'overview'),
'logoutRedirect' => array('controller' => 'pages', 'action' => 'index')
)
);
function beforeFilter() {
$this->Auth->allow('login','index', 'view', 'condos', 'houses', 'hotels_and_motels', 'print_all_coupons', 'print_coupon', 'search', 'golf', 'charters', 'events', 'nightlife', 'shopping', 'visitors_info', 'contact_us');
}
}
?>
and here is the view code:
<div class="users form">
<?php echo $this->Session->flash('auth'); ?>
<?php echo $this->Form->create('User');?>
<fieldset>
<legend><?php echo __('Please enter your username and password'); ?></legend>
<?php
echo $this->Form->input('username');
echo $this->Form->input('password');
?>
</fieldset>
<?php echo $this->Form->end(__('Login'));?>
</div>
As you can see, I pretty much copy and pasted what was in the Cakephp-2.0 manual for this. The only difference between my db table and the manual's is that my password is stored as an MD5 hash in my users table. i can't figure out where this has derailed.
Make sure that your passwords are stored using the Auth component hash. AFAIK, there is no support for 'plain' md5 passwords. The hashes Cake generates are more complex than md5.
See the documentation for info on how to hash your passwords. If you are migrating from an app that used md5 hashing, you'll have to reset all the passwords to something random for all your users.
You can try to use the following codes on your AppController.php file
AppController.php
$this->Auth->authenticate = array(
AuthComponent::ALL => array('userModel' => 'User'),
'Form' => array(
'fields' => array('username' => 'email')
)
);
$this->Auth->authorize =false;
$this->Auth->loginAction = array('controller' => 'users', 'action' => 'login');
$this->Auth->fields = array('username' => 'email', 'password' => 'password');
$this->Auth->loginRedirect = array('controller' => 'media', 'action' => 'index/');
$this->Auth->logoutRedirect = '/logout';
$this->Auth->loginError = 'Invalid e-mail / password combination. Please try again';

Cakephp Auth problem : Undefined property: User::$alias

I keep getting this error over a day right now.
I search over and over , but i couldnt get an answer.
Probably i am making sometihing stupid.
Here is my enviroment;
UserController :
class UsersController extends AppController {
var $name = 'Users';
var $components = array('Email');
function login() {
}
function home() {
pre('login oldunuz');
}
function logout() {
$this->Session->setFlash(__('Goodbye!', true));
$this->redirect($this->Auth->logout());
}
....
}
AppController :
class AppController extends Controller {
var $components = array('Session','Auth');
function beforeFilter() {
$this->Auth->loginError = 'You didnt supply valid identification.';
$this->Auth->authError = 'You are not validated to see this location.';
$this->Auth->allowedActions = array('register','confirm');
$this->Auth->userScope = array('User.active' => 1);
}
function beforeRender() {
$this->set('User', $this->Session->read('Auth.User'));
}
}
UserModel:
class User extends AppModel {
var $name = 'User';
var $displayField = 'username';
var $validate = array(
'username' => array(
'notempty' => array(
'rule' => array('notempty'),
'message' => 'Username field can not be empty..',
),
'u_unique' => array(
'rule'=>array('isUnique'),
'message' => 'The username you selected, is being used please choose another one.'
)
),
'email' => array(
'email' => array(
'rule' => array('email'),
'message' => 'Please provide a valid email.',
),
'e_unique' => array(
'rule' => array('isUnique'),
'message' => 'The email you selected, is being used please choose another one.'
)
),
----
/* if you want i send more of this code */
}
I dont how to fix this,
But for helping, cakephp says :
The error portion is :
if ($key == null)
{
$model =& $this->getModel();
return array($model->alias => $this->Session->read($this->sessionKey));
}
if i make $model->alias = "User" then it works but where ever another $model->alias is used, it explodes same as before,
I hope you have an answer, thanks all,

Resources