I am new in CakePhp, I have a problem with logging in users,
I am using CakePhp 2.4, I hashed the password using blowfish here is the code for my User Model
App::uses('AppModel', 'Model');
App::uses('AuthComponent', 'Controller/Component');
App::uses('BlowfishPasswordHasher', 'Controller/Component/Auth');
/**
* User Model
*
*/
class User extends AppModel {
/**
* Validation rules
*
* #var array
*/
public $validate = array(
'username' => array(
'required' => array(
'rule' => array('notEmpty'),
'message' => 'A username is required'
)
),
'password' => array(
'alphanumeric' => array(
'rule' => array('alphanumeric'),
'message' => 'Password needs to be alphanumeric',
'allowEmpty' => false,
'required' => false,
//'last' => false, // Stop validation after this rule
//'on' => 'create', // Limit validation to 'create' or 'update' operations
),
/*'minlength' => array(
'rule' => array('minlength'),
//'message' => 'Your custom message here',
//'allowEmpty' => false,
//'required' => false,
//'last' => false, // Stop validation after this rule
//'on' => 'create', // Limit validation to 'create' or 'update' operations
),*/
),
'firstname' => array(
'notempty' => array(
'rule' => array('notempty'),
//'message' => 'Your custom message here',
//'allowEmpty' => false,
//'required' => false,
//'last' => false, // Stop validation after this rule
//'on' => 'create', // Limit validation to 'create' or 'update' operations
),
),
'middlename' => array(
'notempty' => array(
'rule' => array('notempty'),
//'message' => 'Your custom message here',
//'allowEmpty' => false,
//'required' => false,
//'last' => false, // Stop validation after this rule
//'on' => 'create', // Limit validation to 'create' or 'update' operations
),
),
'lastname' => array(
'notempty' => array(
'rule' => array('notempty'),
//'message' => 'Your custom message here',
//'allowEmpty' => false,
//'required' => false,
//'last' => false, // Stop validation after this rule
//'on' => 'create', // Limit validation to 'create' or 'update' operations
),
),
);
public function beforeSave($options = array()){
//Override beforeSave to set modified field to NULL
if(!empty($this->data[$this->alias]['modified']) || isset($this->data[$this->alias]['modified']))
unset($this->data[$this->alias]['modified']);
//Hash passwords before saving to database
if(!empty($this->data[$this->alias]['password']) || isset($this->data[$this->alias]['password'])){
$hashedPassword = Security::hash($this->data[$this->alias]['password'],"blowfish");
$this->data[$this->alias]['password'] = $hashedPassword;
}
return true;
}
}
now when i try to log in a user, thats where the problem arises,
even if I supply the wrong credentials
(a user that is not registered in the database),
the user would still be logged in. Here is my AppController
<?php
App::uses('Controller', 'Controller');
class AppController extends Controller {
public $components = array(
'DebugKit.Toolbar',
'Session',
'Auth' => array(
'authenticate' => array('Blowfish'),
'loginRedirect' => array('controller' => 'computers', 'action' => 'index'),
'logoutRedirect' => array('controller' => 'users', 'action' => 'index')
)
);
public function beforeFilter(){
$this->Auth->allow('index');
}
}
and here is my UsersController
<?php
App::uses('AppController', 'Controller');
/**
* Users Controller
*
* #property User $User
* #property PaginatorComponent $Paginator
* #property RequestHandlerComponent $RequestHandler
*/
class UsersController extends AppController {
/**
* Helpers
* #var array
*/
public $helpers = array('Session');
/**
* Components
* #var array
*/
public $components = array('Paginator', 'RequestHandler');
public function beforeFilter(){
parent::beforeFilter();
$this->Auth->allow(array('signup','check_user'));//Letting users register themselves
}
/**
* index method
* #return void
*/
public function index() {
$this->layout = 'custom_layouts/default';
$data = array(
'id' => 'myLayout',
'title_for_layout' => 'Reservation . Better Reservation'
);
$this->set($data);
/*
$this->User->recursive = 0;
$this->set('users', $this->Paginator->paginate());*/
}
public function login(){
if($this->request->is('post')){
if($this->Auth->login()){ return $this->redirect($this->Auth->redirectUrl()); }
$this->Session->setFlash(__('Invalid username or password, try again.'));
}
$this->layout = 'custom_layouts/default';
$data = array(
'id' => 'signin',
'title_for_layout' => 'Reservation . Sign in'
);
$this->set($data);
}
public function logout(){
return $this->redirect($this->Auth->logout());
}
/*
* signup method
* #return void
*/
public function signup(){
if($this->request->is('post')){
$this->User->create();
if($this->User->save($this->request->data)){
$this->Session->setFlash(__('Your Account has been successfully added.'));
return $this->redirect(array('action' => 'login'));
}
else{ $this->Session->setFlash(__('The user could not be saved. Please, try again.')); }
}
$this->layout = 'custom_layouts/default';
$data = array(
'id' => 'signup',
'title_for_layout' => 'Reservation . Sign up'
);
$this->set($data);
}
/*
* check_user method
* #return json
*/
public function check_user(){
$user = NULL;
if($this->request->is('get')){
$this->disableCache();
$ajax_query = $this->request->query('requested_user');
$isExisting = $this->User->find(
'first',
array(
'condition' => array(
'User.username' => $ajax_query
)
)
);
if($isExisting){
$user = $this->User->find(
'first',
array(
'fields' => array(
'User.username',
'User.firstname',
'User.lastname'
),
'conditions' => array('User.username' => $ajax_query)
)
);
}
$this->set('response', $user);
$this->set('_serialize','response');
}
}
//Baked methods
/**
* view method
*
* #throws NotFoundException
* #param string $id
* #return void
*/
/*
public function view($id = null) {
if (!$this->User->exists($id)) {
throw new NotFoundException(__('Invalid user'));
}
$options = array('conditions' => array('User.' . $this->User->primaryKey => $id));
$this->set('user', $this->User->find('first', $options));
}*/
/**
/*
* edit method
*
* #throws NotFoundException
* #param string $id
* #return void
*/
/*
public function edit($id = null) {
if (!$this->User->exists($id)) {
throw new NotFoundException(__('Invalid user'));
}
if ($this->request->is('post') || $this->request->is('put')) {
if ($this->User->save($this->request->data)) {
$this->Session->setFlash(__('The user has been saved.'));
return $this->redirect(array('action' => 'index'));
} else {
$this->Session->setFlash(__('The user could not be saved. Please, try again.'));
}
} else {
$options = array('conditions' => array('User.' . $this->User->primaryKey => $id));
$this->request->data = $this->User->find('first', $options);
}
}*/
/**
* delete method
*
* #throws NotFoundException
* #param string $id
* #return void
*/
/*
public function delete($id = null) {
$this->User->id = $id;
if (!$this->User->exists()) {
throw new NotFoundException(__('Invalid user'));
}
$this->request->onlyAllow('post', 'delete');
if ($this->User->delete()) {
$this->Session->setFlash(__('The user has been deleted.'));
} else {
$this->Session->setFlash(__('The user could not be deleted. Please, try again.'));
}
return $this->redirect(array('action' => 'index'));
}*/
}
I have done a lot of googling for a fix on this problem to no avail,
on the cakephp docs, I have read this note
In 2.x $this->Auth->login($this->request->data) will log the user in with whatever data is posted, whereas in 1.3 $this->Auth->login($this->data) would try to identify the user first and only log in when successful.
if this is the cause if why even if the user credentials supplied are not registered in the database, the user would still be authenticated, is there any kind of workaround for this one?
I think you should define userModel in appcontroller
'loginAction' => array('controller'=>'Admin', 'action'=>'login'),
'loginRedirect' => array('contoller'=>'Admin', 'action'=>'login'),
'logoutRedirect' => array('controller'=>'Admin', 'action'=>'logout'),
'authError' => '<div class="alert alert-error"><button type="button" class="close" data-dismiss="alert">×</button>
You are not authorized to access this location</div>',
'authenticate' => array(
'Form' => array(
'userModel' => 'User',
'fields' => array(
'username' => 'email',
'password'=>'password')
)
)
);
Related
I done a user system on a website.
In my UsersController.php I have this method:
public function login()
{
if($this->request->is('post')) {
if($this->Auth->login()) {
$this->Session->setFlash('Connexion établie', 'flash_success');
$this->redirect($this->Auth->redirectUrl());
} else {
$this->Session->setFlash("Nom d'user ou mot de passe invalide, réessayer", 'flash_error');
$this->redirect(array('controller' => 'indexes', 'action' => 'index'));
}
}
}
It works very well, but I need to change it. In my database I have a field "validate" which is a boolean.
On login I want to log user if the field is true but I don't want to log him if the field is on false.
Thanks for help
You need the scope field. You can either add it on the beforeFilter method For example:
public function beforeFilter() {
$this->Auth->authenticate = array(
'YourAuthComponent' => array(
'fields' => array(
'username' => 'username',
'password' => 'password'
),
'userModel' => 'Users.User',
//This is what you need
'scope' => array(
'User.active' => 1,
'User.verified' => 1)
)
);
}
Or you can add the option to your components array at your AppController or UsersController.
class AppController extends Controller {
/**
* Components used from the application
*
* #var array
*/
public $components = array(
'Auth'=> array(
'authenticate' => array(
'Form' => array(
'fields' => array('username' => 'email'),
'scope' => array(
'User.active' => 1,
'User.verified' => 1)
)
)
)
),
);
}
I am trying to get my login working but I seemed to run into a problem. Could someone please help? I am using the 'Employees' as the user of the database. Below is my code for AppController, EmployeeController, Employee and login.ctp:
App Controller:
class AppController extends Controller {
public $components = array(
'DebugKit.Toolbar',
'Session',
'Auth' => array(
'loginRedirect' => array('controller' => 'employees', 'action' => 'index'),
'logoutRedirect' => array('controller' => 'employees', 'action' => 'login'),
'authError' => 'You must be logged in to view this page.',
'loginError' => 'Invalid Username or Password entered, please try again.'
));
// only allow the login controllers only
public function beforeFilter() {
$this->Auth->allow('login');
}
}
Employees Controller:
class EmployeesController extends AppController {
//..other code
/**
* Components
*
* #var array
*/
//public $components = array('Paginator');
public $paginate = array(
'limit' => 25,
'conditions' => array('status' => '1'),
'order' => array('Employee.employee_username' => 'asc' )
);
public function beforeFilter() {
parent::beforeFilter();
$this->Auth->allow('login','add');
}
public function login() {
//if already logged-in, redirect
if($this->Session->check('Auth.Employee')){
$this->redirect(array('action' => 'index'));
}
// if we get the post information, try to authenticate
if ($this->request->is('post')) {
if ($this->Auth->login()) {
$this->Session->setFlash(__('Welcome, '. $this->Auth->user('username')));
$this->redirect($this->Auth->redirectUrl());
} else {
$this->Session->setFlash(__('Invalid username or password'));
}
}
}
public function logout() {
$this->redirect($this->Auth->logout());
}
/**
* index method
*
* #return void
*/
public function index() {
$this->paginate = array(
'limit' => 6,
'order' => array('Employee.employee_username' => 'asc' )
);
$employees = $this->paginate('Employee');
$this->set(compact('employees'));
}
Employee Model:
class Employee extends AppModel {
//..other code
function isUniqueUsername($check) {
$username = $this->find(
'first',
array(
'fields' => array(
'Employee.id',
'Employee.employee_username'
),
'conditions' => array(
'Employee.employee_username' => $check['username']
)
)
);
if(!empty($username)){
if($this->data[$this->alias]['id'] == $username['Employee']['id']){
return true;
}else{
return false;
}
}else{
return true;
}
}
/**
* Before isUniqueEmail
* #param array $options
* #return boolean
*/
function isUniqueEmail($check) {
$email = $this->find(
'first',
array(
'fields' => array(
'Employee.id'
),
'conditions' => array(
'Employee.employee_email' => $check['email']
)
)
);
if(!empty($email)){
if($this->data[$this->alias]['id'] == $email['Employee']['id']){
return true;
}else{
return false;
}
}else{
return true;
}
}
public function alphaNumericDashUnderscore($check) {
// $data array is passed using the form field name as the key
// have to extract the value to make the function generic
$value = array_values($check);
$value = $value[0];
return preg_match('/^[a-zA-Z0-9_ \-]*$/', $value);
}
public function equaltofield($check,$otherfield)
{
//get name of field
$fname = '';
foreach ($check as $key => $value){
$fname = $key;
break;
}
return $this->data[$this->name][$otherfield] === $this->data[$this->name][$fname];
}
/**
* Before Save
* #param array $options
* #return boolean
*/
public function beforeSave($options = array()) {
if (isset($this->data[$this->alias]['password'])) {
$this->data[$this->alias]['password'] = $passwordHasher->hash(
$this->data[$this->alias]['password']
);
}
// if we get a new password, hash it
if (isset($this->data[$this->alias]['password_update'])) {
$this->data[$this->alias]['password'] = AuthComponent::password($this->data[$this->alias]['password_update']);
}
// fallback to our parent
return parent::beforeSave($options);
//return true;
}
}
Login page:
<div class=“employees form">
<?php echo $this->Session->flash('auth'); ?>
<?php echo $this->Form->create('Employee'); ?>
<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>
1.Adapt the config of your Auth component regarding userModel, fields and passwordHasher:
public $components = array(
'DebugKit.Toolbar',
'Session',
'Auth' => array(
'loginRedirect' => array('controller' => 'Employee', 'action' => 'index'),
'logoutRedirect' => array('controller' => 'Employee', 'action' => 'login'),
'authError' => 'You must be logged in to view this page.',
'loginError' => 'Invalid Username or Password entered, please try again.',
'authenticate' => array(
'Form' => array(
'fields' => array('username' => 'username', 'password' => 'password'),
'userModel'=>'Employee',
'passwordHasher' => 'name of your password hasher'
))
));
2.Regarding CakePHP´s code convetion rename your controller to EmployeeController
3.In your Employee model instead your isUniqueUsername and isUniqueEmail you better use validation rule isUnique
4.Use same password hasher for creating password and update password
To use Employee table for Authentication:
public $components = array(
'Auth' => array(
'authenticate' => array(
'Form' => array(
'fields' => array('username' => 'username'),
'userModel'=>'Employee'
)
)
)
);
I'm trying to use the cakephp built in Auth for a user login. I've managed to validate a user registration (which is located on the same view as the login) but not get the login working.
All i get when trying to login is my 'Invalid username or password, try again' error. I've gone through the blog tutorial but I'm new to cake/php and have only worked on messy projects in 1.3 that sue their own crude authentication.
MarshallsController.php
class MarshalsController extends AppController {
public $helpers = array('Html', 'Form');
public $uses = array("Marshal", "User");
public $components = array("RequestHandler","Session", "Auth");
public function beforeFilter() {
parent::beforeFilter();
$this->Auth->allow('register', 'login');
}
public function index() {
$this->set('users', $this->User->find('all',
array(
'conditions'=>array(
'User.marshall_id'=>$Marshall['Marshall']['id']
)
)));
}
//Run when Marshal attempts to register for login page
public function register(){
if ($this->request->is('post')) {
$this->Marshal->create();
if ($this->Marshal->save($this->request->data)) {
//if new marshall has been saved fetch all their data
$marshal = $this->Marshal->find('first',
array(
'conditions'=>array(
"Marshal.email" => $this->data['Marshal']['email'],
)
)
);
if(!empty($marshal)){
//set marshal session data to track logged in users and their data
$this->Session->write("Marshal",$marshal);
}
$this->Session->setFlash(__('The Marshal has been saved'));
//redirect user to logged in page
$this->redirect(array('controller' => 'pages', 'action' => 'home'));
} else {
$this->Session->setFlash(__('The Marshal could not be saved. Please, try again.'));
echo $this->render('login');
exit();
}
}
else{
//if Marshal has not attempted to login redirect the back to the login/register page
echo $this->render('login');
exit();
}
}
public function login() {
//if user has atempted a login
if ($this->request->is('post')) {
if ($this->Auth->login()) {
//If login detials are correct get user data
$marshal = $this->Marshal->find('first',
array(
'conditions'=>array(
"Marshal.email" => $this->data['Marshal']['email'],
)
)
);
if(!empty($marshal)){
//set marshal session data to track logged in users and their data
$this->Session->write("Marshal",$marshal);
}
//redirect user to the logged in page
$this->redirect($this->Auth->redirect());
} else {
$this->Session->setFlash(__('Invalid username or password, try again'));
debug($this->Auth->request->data);
}
Marshal model
class Marshal extends AppModel {
public function beforeSave($options = array()) {
if (isset($this->data[$this->alias]['password'])) {
$this->data[$this->alias]['password'] = AuthComponent::password($this->data[$this->alias]['password']);
}
return true;
}
public $hasMany = array(
'User' => array(
'className' => 'User',
'foreignKey' => 'marshal_id',
'conditions' => array('User.status' => '1'),
)
);
public $validate = array(
'first_name' => array(
'required' => array(
'rule' => array('notEmpty'),
'message' => 'A first name is required'
)
),
'last_name' => array(
'required' => array(
'rule' => array('notempty'),
'message' => 'A last name is required'
)
),
'password' => array(
'required' => array(
'rule' => array('minLength', '8'),
'message' => 'Minimum 8 characters long'
)
),
'email' => 'email'
);
}
login.ctp
<div class="row">
<?php echo $this->Session->flash('auth'); ?>
<div class="sixcol">
<?php
echo $this->Form->create('Marshal', array('action' => 'login'));
echo $this->Form->inputs(array(
'legend' => __('Login'),
'email',
'password'
));
echo $this->Form->end('Login');
?>
</div>
<div class="sixcol last">
<?php
echo $this->Form->create('Marshal', array('action' => 'register'));
echo $this->Form->inputs(array(
'legend' => __('register'),
'first_name',
'last_name',
'email',
'password'
));
echo $this->Form->end('Register');
?>
</div>
By default, CakePHP uses username and password fields but you have email instead of username. You need to specify it:
public $components = array(
'Auth' => array('authenticate' => array('Form' => array( 'userModel' => 'User',
'fields' => array(
'username' => 'email',
'password' => 'password'
)
)
),
'authorize' => array('Controller'),
'loginAction' => array('controller' => 'users', 'action' => 'login'),
'loginRedirect' => array('controller' => 'home', 'action' => 'index'),
'logoutRedirect' => array('controller' => 'users', 'action' => 'login'),
'authError' => 'You don\'t have access here.',
),
);
This is my working example, feel free to change it for your needs.
You also could check the Security hash method and compare with the password in the database :
Security::setHash('sha1');
(sha1 or md5)
to compare passwords :
Security::hash($password,"sha1", true);
function login() {
//if already logged-in, redirect
// if($this->Session->check('email')){
// $this->redirect(array('action' => ''));
// }
// if we get the post information, try to authenticate
if ($this->request->is('post')) {
$data = $this->request->data;
print_r($data); die;
if ($this->Auth->login()) {
return $this->redirect($this->Auth->redirectUrl());
}
$this->Session->setFlash(__('Your username or password was incorrect.'));
}
}
only else codition is true
When I try to authenticate it says Your username or password was incorrect. even if I just created the user. When I try debug($this->Auth->login()) I get the message false. What is wrong with my code?
The model - UserModel.php:
<?php
App::uses('AppModel', 'Model', 'AuthComponent', 'Controller/Component');
/**
* User Model
*
* #property Group $Group
* #property WashMachine $WashMachine
*/
class User extends AppModel {
/**
* Validation rules
*
* #var array
*/
public function beforeSave($options = array()) {
$this->data['User']['password'] = AuthComponent::password($this->data['User']['password']);
return true;
}
public function bindNode($user) {
return array('model' => 'Group', 'foreign_key' => $user['User']['group_id']);
}
public $validate = array(
'username' => array(
'notempty' => array(
'rule' => array('notempty'),
//'message' => 'Your custom message here',
//'allowEmpty' => false,
//'required' => false,
//'last' => false, // Stop validation after this rule
//'on' => 'create', // Limit validation to 'create' or 'update' operations
),
),
'name' => array(
'notempty' => array(
'rule' => array('notempty'),
//'message' => 'Your custom message here',
//'allowEmpty' => false,
//'required' => false,
//'last' => false, // Stop validation after this rule
//'on' => 'create', // Limit validation to 'create' or 'update' operations
),
),
'email' => array(
'email' => array(
'rule' => array('email'),
//'message' => 'Your custom message here',
//'allowEmpty' => false,
//'required' => false,
//'last' => false, // Stop validation after this rule
//'on' => 'create', // Limit validation to 'create' or 'update' operations
),
),
'password' => array(
'notempty' => array(
'rule' => array('notempty'),
//'message' => 'Your custom message here',
//'allowEmpty' => false,
//'required' => false,
//'last' => false, // Stop validation after this rule
//'on' => 'create', // Limit validation to 'create' or 'update' operations
),
),
'group_id' => array(
'numeric' => array(
'rule' => array('numeric'),
//'message' => 'Your custom message here',
//'allowEmpty' => false,
//'required' => false,
//'last' => false, // Stop validation after this rule
//'on' => 'create', // Limit validation to 'create' or 'update' operations
),
),
);
//The Associations below have been created with all possible keys, those that are not needed can be removed
/**
* belongsTo associations
*
* #var array
*/
public $belongsTo = array(
'Group' => array(
'className' => 'Group',
'foreignKey' => 'group_id',
'conditions' => '',
'fields' => '',
'order' => ''
)
);
/**
* hasMany associations
*
* #var array
*/
public $hasMany = array(
'WashMachine' => array(
'className' => 'WashMachine',
'foreignKey' => 'user_id',
'dependent' => false,
'conditions' => '',
'fields' => '',
'order' => '',
'limit' => '',
'offset' => '',
'exclusive' => '',
'finderQuery' => '',
'counterQuery' => ''
)
);
}
The AppController.php
<?php
/**
* Application level Controller
*
* This file is application-wide controller file. You can put all
* application-wide controller-related methods here.
*
* PHP 5
*
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
* Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* Redistributions of files must retain the above copyright notice.
*
* #copyright Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
* #link http://cakephp.org CakePHP(tm) Project
* #package app.Controller
* #since CakePHP(tm) v 0.2.9
* #license MIT License (http://www.opensource.org/licenses/mit-license.php)
*/
App::uses('Controller', 'Controller');
/**
* Application Controller
*
* Add your application-wide methods in the class below, your controllers
* will inherit them.
*
* #package app.Controller
* #link http://book.cakephp.org/2.0/en/controllers.html#the-app-controller
*/
class AppController extends Controller {
public $components = array(
'Acl',
'Auth' => array(
'authorize' => array(
'Actions' => array('actionPath' => 'controllers')
)
),
'Session'
);
public $helpers = array('Html', 'Form', 'Session');
function beforeFilter() {
//Configure AuthComponent
$this->Auth->authorize = array(
'Controller',
'Actions' => array('actionPath' => 'controllers')
);
$this->Auth->authenticate = array('Form' => array('fields' => array('username' => 'login', 'password' => 'password')));
$this->Auth->loginAction = array('controller' => 'users', 'action' => 'login', 'admin' => false, 'plugin' => false);
$this->Auth->logoutRedirect = array('controller' => 'users', 'action' => 'login', 'admin' => false, 'plugin' => false);
$this->Auth->loginRedirect = array('controller' => 'products', 'action' => 'index', 'admin' => false, 'plugin' => false);
}
function isAuthorized($user) {
// return false;
return $this->Auth->loggedIn();
}
}
The UserController.php
<?php
App::uses('AppController', 'Controller');
/**
* Users Controller
*
* #property User $User
*/
class UsersController extends AppController {
function beforeFilter(){
parent::beforeFilter();
$this->Auth->allow('*');
}
public function login() {
if ($this->request->is('post')) {
if ($this->Auth->login()) {
$this->redirect($this->Auth->redirect());
} else {
$this->Session->setFlash('Your username or password was incorrect.');
}
}
if ($this->Session->read('Auth.User')) {
$this->Session->setFlash('You are logged in!');
$this->redirect('/', null, false);
}
}
public function logout() {
$this->Session->setFlash('Good-Bye');
$this->redirect($this->Auth->logout());
}
/**
* index method
*
* #return void
*/
public function index() {
$this->User->recursive = 0;
$this->set('users', $this->paginate());
}
/**
* view method
*
* #throws NotFoundException
* #param string $id
* #return void
*/
public function view($id = null) {
$this->User->id = $id;
if (!$this->User->exists()) {
throw new NotFoundException(__('Invalid user'));
}
$this->set('user', $this->User->read(null, $id));
}
/**
* add method
*
* #return void
*/
public function add() {
if ($this->request->is('post')) {
$this->User->create();
if ($this->User->save($this->request->data)) {
$this->Session->setFlash(__('The user has been saved'));
$this->redirect(array('action' => 'index'));
} else {
$this->Session->setFlash(__('The user could not be saved. Please, try again.'));
}
}
$groups = $this->User->Group->find('list');
$this->set(compact('groups'));
}
/**
* edit method
*
* #throws NotFoundException
* #param string $id
* #return void
*/
public function edit($id = null) {
$this->User->id = $id;
if (!$this->User->exists()) {
throw new NotFoundException(__('Invalid user'));
}
if ($this->request->is('post') || $this->request->is('put')) {
if ($this->User->save($this->request->data)) {
$this->Session->setFlash(__('The user has been saved'));
$this->redirect(array('action' => 'index'));
} else {
$this->Session->setFlash(__('The user could not be saved. Please, try again.'));
}
} else {
$this->request->data = $this->User->read(null, $id);
}
$groups = $this->User->Group->find('list');
$this->set(compact('groups'));
}
/**
* delete method
*
* #throws MethodNotAllowedException
* #throws NotFoundException
* #param string $id
* #return void
*/
public function delete($id = null) {
if (!$this->request->is('post')) {
throw new MethodNotAllowedException();
}
$this->User->id = $id;
if (!$this->User->exists()) {
throw new NotFoundException(__('Invalid user'));
}
if ($this->User->delete()) {
$this->Session->setFlash(__('User deleted'));
$this->redirect(array('action' => 'index'));
}
$this->Session->setFlash(__('User was not deleted'));
$this->redirect(array('action' => 'index'));
}
}
The Login.cp view:
<h2>Login</h2>
<?php
echo $this->Form->create('User', array('url' => array('controller' => 'users', 'action' => 'login')));
echo $this->Form->input('User.username');
echo $this->Form->input('User.password');
echo $this->Form->end('Login');
?>
why are you remapping "username" to login" in your Form settings
but your login form still contains "username" as field name?
drop the remapping OR change the field in your form to "User.login"
since you seem to have a database field username the first should be done:
'Form' => array('fields' => array('username' => 'username', 'password' => 'password')));
You have to change
from:-
$this->Auth->authenticate = array('Form' => array('fields' => array('username' => 'login', 'password' => 'password')));
to:-
$this->Auth->authenticate = array('Form' => array('fields' => array('username' => 'username', 'password' => 'password')));
or you can drop this line completely as it will take the default AuthComponent values defined
I have posted my routes, user model, user controller, app controller and pages controller. This is almost a complete copy of the Simple Authentication guide found for CakePHP 2 on their website.
I am using 2.2.2 and can not seem to get anything to work. The main issue I am been having is that a lot of guides / help assume that you are building this as a new 'base' site, by that I mean that Cake is installed to the root of the hosting. But in my case its not, I am building it as part of a showcase to show what I can do.
The problem with this is that it only reloads the main page (the page that the login form is on). It will not take a valid user + password and do anything with it, same goes for invalid details. So I am doing something basic wrong? Or becuase of the config of trying to have many different projects / sites hosted within the same domain do I need to change something some where?
I have not posted the code for the form I am using on take the users name + password but I have not changed this from what the guide posted.
If you need anything else that I might have not thought to post, then please let me know.
Please help me.
My Routes Config
$SiteBase = '/projects/cake/DrWho/';
Router::connect($SiteBase, array('controller' => 'pages', 'action' => 'display'));
Router::connect($SiteBase . 'login/', array('controller' => 'users', 'action' => 'LogIn'));
Router::connect($SiteBase . 'gallery/', array('controller' => 'galleries', 'action' => 'index'));
Router::connect($SiteBase . 'episodeguide/', array('controller' => 'episodes', 'action' => 'index'));
Router::connect($SiteBase . 'forum/', array('controller' => 'forumtopics', 'action' => 'index'));
//Router::connect('/pages/*', array('controller' => 'pages', 'action' => 'display'));
CakePlugin::routes();
require CAKE . 'Config' . DS. 'routes.php';
My UsersModel
App::uses('AppModel', 'Model');
App::uses('AuthComponent', 'Controller/Component');
class User extends AppModel {
public function beforeSave($options = array()) {
if (isset($this->data[$this->alias]['password'])) {
$this->data[$this->alias]['password'] = AuthComponent::password($this->data[$this->alias]['password']);
}
return true;
}
public $validate = array(
'id' => array(
'notempty' => array(
'rule' => array('notempty'),
//'message' => 'Your custom message here',
//'allowEmpty' => false,
//'required' => false,
//'last' => false, // Stop validation after this rule
//'on' => 'create', // Limit validation to 'create' or 'update' operations
),
),
'username' => array(
'notempty' => array(
'rule' => array('notempty'),
//'message' => 'Your custom message here',
//'allowEmpty' => false,
//'required' => false,
//'last' => false, // Stop validation after this rule
//'on' => 'create', // Limit validation to 'create' or 'update' operations
),
),
'password' => array(
'notempty' => array(
'rule' => array('notempty'),
//'message' => 'Your custom message here',
//'allowEmpty' => false,
//'required' => false,
//'last' => false, // Stop validation after this rule
//'on' => 'create', // Limit validation to 'create' or 'update' operations
),
),
'fristname' => array(
'notempty' => array(
'rule' => array('notempty'),
//'message' => 'Your custom message here',
//'allowEmpty' => false,
//'required' => false,
//'last' => false, // Stop validation after this rule
//'on' => 'create', // Limit validation to 'create' or 'update' operations
),
),
'surname' => array(
'notempty' => array(
'rule' => array('notempty'),
//'message' => 'Your custom message here',
//'allowEmpty' => false,
//'required' => false,
//'last' => false, // Stop validation after this rule
//'on' => 'create', // Limit validation to 'create' or 'update' operations
),
),
'email' => array(
'notempty' => array(
'rule' => array('notempty'),
//'message' => 'Your custom message here',
//'allowEmpty' => false,
//'required' => false,
//'last' => false, // Stop validation after this rule
//'on' => 'create', // Limit validation to 'create' or 'update' operations
),
),
'active' => array(
'boolean' => array(
'rule' => array('boolean'),
//'message' => 'Your custom message here',
//'allowEmpty' => false,
//'required' => false,
//'last' => false, // Stop validation after this rule
//'on' => 'create', // Limit validation to 'create' or 'update' operations
),
),
'role_id' => array(
'numeric' => array(
'rule' => array('numeric'),
//'message' => 'Your custom message here',
//'allowEmpty' => false,
//'required' => false,
//'last' => false, // Stop validation after this rule
//'on' => 'create', // Limit validation to 'create' or 'update' operations
),
),
);
public $belongsTo = array(
'Role' => array(
'className' => 'Role',
'foreignKey' => 'role_id',
'conditions' => '',
'fields' => '',
'order' => ''
)
);
}
My UsersController
App::uses('AppController', 'Controller');
class UsersController extends AppController {
public function login() {
if ($this->request->is('post')) {
if ($this->Auth->login()) {
$this->redirect($this->Auth->redirect());
} else {
$this->Session->setFlash(__('Invalid username or password, try again'));
}
}
}
public function logout() {
$this->redirect($this->Auth->logout());
}
public function beforeFilter() {
parent::beforeFilter();
$this->Auth->allow('add', 'logout');
}
public function index() {
$this->User->recursive = 0;
$this->set('users', $this->paginate());
}
public function view($id = null) {
$this->User->id = $id;
if (!$this->User->exists()) {
throw new NotFoundException(__('Invalid user'));
}
$this->set('user', $this->User->read(null, $id));
}
public function add() {
if ($this->request->is('post')) {
$this->User->create();
if ($this->User->save($this->request->data)) {
$this->Session->setFlash(__('The user has been saved'));
$this->redirect(array('action' => 'index'));
} else {
$this->Session->setFlash(__('The user could not be saved. Please, try again.'));
}
}
}
public function edit($id = null) {
$this->User->id = $id;
if (!$this->User->exists()) {
throw new NotFoundException(__('Invalid user'));
}
if ($this->request->is('post') || $this->request->is('put')) {
if ($this->User->save($this->request->data)) {
$this->Session->setFlash(__('The user has been saved'));
$this->redirect(array('action' => 'index'));
} else {
$this->Session->setFlash(__('The user could not be saved. Please, try again.'));
}
} else {
$this->request->data = $this->User->read(null, $id);
unset($this->request->data['User']['password']);
}
}
public function delete($id = null) {
if (!$this->request->is('post')) {
throw new MethodNotAllowedException();
}
$this->User->id = $id;
if (!$this->User->exists()) {
throw new NotFoundException(__('Invalid user'));
}
if ($this->User->delete()) {
$this->Session->setFlash(__('User deleted'));
$this->redirect(array('action' => 'index'));
}
$this->Session->setFlash(__('User was not deleted'));
$this->redirect(array('action' => 'index'));
}
}
My AppController
App::uses('Controller', 'Controller');
class AppController extends Controller {
public $components = array(
'Session',
'Auth' => array(
'loginRedirect' => array('controller' => 'pages', 'action' => 'index'),
'logoutRedirect' => array('controller' => 'pages', 'action' => 'display', 'home')
)
);
var $helpers = array('AssetCompress.AssetCompress');
function beforeFilter() {
if ($this->request->is('mobile')) {
$this->isMobile = true;
$this->set('isMobile', true );
$this->autoRender = false;
$this->layout = 'mobile';
}
$this->MenuSystem();
} //End of beforeFilter function
function MenuSystem() {
$this->loadModel('Menu');
$MenuSQL = $this->Menu->find('all', array('conditions' => array('active' => true)));
$this->set('Menu', $MenuSQL);
} //End of MenuSystem function
} //End of AppController Class
My PagesController
App::uses('AppController', 'Controller');
class PagesController extends AppController {
public $name = 'Pages';
public $uses = array();
function beforeFilter() {
parent::beforeFilter();
$this->Auth->allow('*');
}
function index() {
$this->render('pages_home');
}
public function display() {
if ($this->request->is('mobile')) {
$this->render('pages_mobile');
} else {
$this->render('pages_home');
}
} //End display() function
} // End of PagesController Class
I presume your cake project is inside folder DOCUMENT_ROOT/projects/cake/DrWho/ (where DOCUMENT_ROOT is your webserver's document root).
You don't have to do anything special to make a cake project work inside a subfolder in document root. Trying to prefix the $siteBase to your routes is actually whats causing problems. The base url is automatically handled by cake. In the rare occasion where the base url isn't guessed properly you can use the App.baseUrl config in your app/Config/core.php.