In my view I have:
<?php
echo $this->Form->create('User', array("controller" => "Users", "action" => "login", "method" => "post"));
echo $this->Form->input('User.email', array("label" => false));
echo $this->Form->input('User.password', array("label" => false, 'class' => 'password-input'));
echo $this->Form->end(); ?>
In my AppController:
public $components = array(
'Session',
'Auth'
);
function beforeFilter(){
$this->Auth->fields = array(
'username' => 'email',
'password' => 'password'
);
}
In my UsersController:
function beforeFilter(){
$this->Auth->allow('sign_up', 'login', 'logout', 'forgot_password');
return parent::beforeFilter();
}
public function login() {
if ($this->Auth->login()) {
$this->Session->setFlash(__('Successfully logged in'), 'default', array('class' => 'success'));
$this->redirect($this->Auth->redirect());
} else {
if (!empty($this->request->data)) {
$this->Session->setFlash(__('Username or password is incorrect'), 'default', array('class' => 'notice'));
}
}
}
But the login is not working, what am I missing?
Thanks.
I believe the problem is:
function beforeFilter(){
$this->Auth->fields = array(
'username' => 'email',
'password' => 'password'
);
}
That was how custom login fields were specified in CakePHP 1.3. CakePHP 2.0 instead requires you to specify these fields in the public $components = array(...);. The 1.3 API shows that Auth has a $fields property, but the 2.0 API shows that there is no longer a $fields property. So you must:
public $components = array(
'Session',
'Auth' => array(
'authenticate' => array(
'Form' => array(
'fields' => array('username' => 'email')
)
)
)
);
More information can be found at: http://book.cakephp.org/2.0/en/core-libraries/components/authentication.html#configuring-authentication-handlers
Please tell me how it works out!
Final solution for my problem. Thank you.
I had a problem with userModel and I write this:
'Auth' => array(
'userModel' => 'Member'
)
instead of this:
'Auth' => array(
'authenticate' => array(
'Form' => array(
'userModel' => 'Member'
)
)
)
Related
Sorry - Hate to ask but I've spent hour's working this out and researching but havent had any luck.
CakePHP (running the latest version) seems to refuse to use the fields setting (So that I can use the email column in the database as the username). If I set it to 'email' which is the field I wish to use from the database it simply refuses to login stating incorrect details. Cant get any output from SQL in DebugKit for some reason. Although when it's set to username as per below it works fine just using a 'temp' column in the DB. I've tried putting it in the components var but had no luck with that either. What could I be doing wrong? Debug is on, cant see any errors in the log or browser.
The model does contain an email column.
Controller/AppController.php
class AppController extends Controller {
public $components = array(
'Session',
'DebugKit.Toolbar',
'Auth' => array(
'allow' => array('login','logout'),
'loginAction' => array('controller' => 'users', 'action' => 'login'),
'loginRedirect' => array('controller' => 'dashboard', 'action' => 'index'),
'authorize' => 'Controller'
)
);
function beforeFilter() {
Security::setHash('md5');
$this->Auth->authenticate = array(
'Form' => array(
'fields' => array(
'username' => 'username',
),
),
);
}
}
Controller/UserController.php
class UsersController extends AppController {
public $uses = array('User');
public function beforeFilter() {
parent::beforeFilter();
}
public function isAuthorized($user){
return true;
}
public function login() {
$this->layout = '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','flash_error');
}
}
}
public function logout() {
$this->layout = 'login';
$this->Session->setFlash('Successfully logged out!','flash_success');
$this->redirect($this->Auth->logout());
}
}
View/Users/login.ctp
<?php
$this->set('title_for_layout', 'Login');
echo $this->Session->flash();
echo $this->Session->flash('auth','flash_info');
echo $this->Form->create('User', array(
'action' => 'login'
));
echo $this->Form->input('username',array(
'between' => '<br/>',
'before' => '<p>',
'after' => '</p>',
'class' => 'text',
'label' => 'Email:'
));
echo $this->Form->input('password',array(
'between' => '<br/>',
'before' => '<p>',
'after' => '</p>',
'class' => 'text',
'label' => 'Password:'
));
echo $this->Form->submit('Login', array(
'class' => 'submit',
'before' => '<p>',
'after' => '</p>'
));
echo $this->Form->end();
?>
You need to change the name of the field on your form from username to email. Just setting the label to "email" is not enough.
echo $this->Form->input('email',array(
'between' => '<br/>',
'before' => '<p>',
'after' => '</p>',
'class' => 'text',
'label' => 'Email:'
Try updating the components code in your appController to add the authenticate values to the Auth array like this:
public $components = array(
'Session',
'DebugKit.Toolbar',
'Auth' => array(
'allow' => array('login','logout'),
'loginAction' => array('controller' => 'users', 'action' => 'login'),
'loginRedirect' => array('controller' => 'dashboard', 'action' => 'index'),
'authorize' => 'Controller',
'authenticate' => array(
'Form' => array(
'fields' => array('username' => 'email')
)
)
)
);
i am beginning with cakephp framework, i use auth to create a login form, at my appcontroller i add:
class AppController extends Controller {
public $components = array('Auth', 'Cookie');
public function beforeFilter(){
$this->Auth->authenticate = array(
'Form' => array(
'userModel' => 'User',
'fields' => array('name' => 'name', 'password' => 'password'),
)
);
$this->Auth->loginAction = array('controller' => 'TestOnlineSystem', 'action' => 'P001');
$this->Auth->loginRedirect = array('controller' => 'TestOnlineSystem', 'action' => 'index');
$this->Auth->loginError = 'Failed to login';
$this->Auth->authError = ' ';
}
}
but when i run TestOnlineSystem/P001 it auto redirect to users/login anh show message net controller usercontroller. How can i fix it, P001 is my login page
I agree with thaJeztah, try the standard config from http://book.cakephp.org/2.0/en/core-libraries/components/authentication.html :
public $components = array(
'Auth' => array(
'loginAction' => array(
'controller' => 'TestOnlineSystem',
'action' => 'P001',
'plugin' => 'users'
)
)
);
and get rid of your beforeFilter().
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
I'm having Player instead of default User model for my Auth.
I recently configured ACL for my app and while trying to do testing by return false in my isAuthorized($player) function, the following error occured:
AclNode::node() - Couldn't find Aro node identified by
Array ( [Aro0.model] => User [Aro0.foreign_key] => 1 )
Isn't the Aro0.model suppose to be Player? I can't find where to change for Auth->authorize. Auth-authenticate works fine as I manage to login since there is a userModel option allow me to specify a custom Model for user login.
Here's My AppController
class AppController extends Controller
{
public $components = array(
'Session',
'Acl',
'RequestHandler',
'Auth' => array(
'authorize' => array(
'controller',
'Actions' => array('actionPath' => 'controllers'),
),
'authenticate' => array(
'Form' => array(
'userModel' => 'Player',
'fields' => array('username' => 'email', 'password' => 'password'),
)
)
),
);
public $helpers = array('Html', 'Form', 'Session');
function isAuthorized($player)
{
//var_dump($player); die;
return false;
return $this->Auth->loggedIn();
}
}
Solved. it is to append userModel together with actionPath.
$this->Auth->authorize = array(
AuthComponent::ALL => array('actionPath' => 'controllers/', 'userModel' => 'Player'),
'Actions',
'Controller'
);
I've searched through many posts on stackoverflow for an answer, and prehaps I'm just overlooking something, but I can't seem to get $this->Auth->login() to work. I've tried many different suggestions from other posts. I will try to be as thorough as possible when describing other methods I've tried.
I do have adding a user working. The MD5 hashing is working correctly. I hashed a password and then checked it using miracle salad md5 http://www.miraclesalad.com/webtools/md5.php
I do not use a salt for hashing. I use MD5 without a salt.
The database I'm using is Postgresql 9.0. I know some of the CakePhp magic doesn't work for all databases (or so I've been told).
app/Config/core.php
Configure::write('Security.level', 'medium');
/**
* A random string used in security hashing methods.
*/
Configure::write('Security.salt', '');
I was using Auth->fields to map password to user_password and username to user_name in the DB. user_password and user_name are the columns in the core_users table. I also had in the beforeFilter() method.
$this->Auth->fields = array('username' => 'user_name', 'password' => 'user_password');
app/Controller/AppController.php
class AppController extends Controller {
public $components = array(
'Session',
'Auth' => array(
'loginRedirect' => array('controller' => 'pages', 'action' => 'index'),
'logoutRedirect' => array('controller' => 'pages', 'action' => 'display', 'home'),
'loginAction' => array('admin' => false, 'controller' => 'CoreUsers', 'action' => 'login'),
/*'fields' => array('password' => 'user_password', 'username' => 'user_name'),*/
'userModel' => 'CoreUser'
)
);
public function beforeFilter() {
Security::setHash('md5');
$this->Auth->allow('login');
//debug($this->Auth);
}
}
I left the debugs in so you can see the order that they are processed and I will show you how they are printed.
app/Controller/CoreUsersController.php
public function login() {
Security::setHash('md5');
//debug($this->Auth);
if ($this->request->is('post')) {
debug(Security::hash($this->Auth->request->data['CoreUser']['user_password']));
debug($this->Auth);
debug(Configure::version());
debug($this->Auth->request->data['CoreUser']['user_password']);
debug($this->Auth->request->data['CoreUser']['user_name']);
if ($this->Auth->login()) {
debug($this->Auth->request->data['CoreUser']['user_password']);
$this->redirect($this->Auth->redirect());
} else {
debug($this->Auth->request->data['CoreUser']['user_password']);
$this->Session->setFlash(__('Invalid username or password, try again'));
}
}
}
public function logout() {
$this->redirect($this->Auth->logout());
}
app/Model/CoreUser.php
App::uses('AuthComponent', 'Controller/Component');
class CoreUser extends AppModel{
public $primaryKey = 'user_id';
public $sequence = 'core_user_id_seq';
public $name = 'CoreUser';
public $validate = array(
'user_name' => array(
'required' => array(
'rule' => array('notEmpty'),
'message' => 'User name is required'
)
),
'user_password' => array(
'required' => array(
'rule' => array('notEmpty'),
'message' => 'Password is required'
)
),
'privilege_id' => array(
'required' => array(
'rule' => array('notEmpty'),
'message' => 'Privilege ID is required'
),
'legalValues' => array(
'rule' => array('between',1,4),
'message' => 'Privilege must be between 1 and 4'
)
),
'user_initial' => array(
'required' => array(
'rule' => array('notEmpty'),
'message' => 'User initials is required'
)
),
'email' => array(
'rule' => array('email',true),
'message' => 'Email must have an \'#\' symbol and a domain e.g. .com'
)
);
public function beforeSave() {
Security::setHash('md5');
if (isset($this->data[$this->alias]['user_password'])) {
$this->data[$this->alias]['user_password'] = AuthComponent::password($this->data[$this->alias]['user_password']);
}
return true;
}
}
app/View/CoreUsers/login.ctp
<h3>Login</h3>
<div class="users form">
<?php echo $this->Session->flash('auth'); ?>
<?php echo $this->Form->create('CoreUser');?>
<fieldset>
<legend><?php echo __('Please enter your username and password'); ?></legend>
<?php
echo $this->Form->input('user_name');
echo $this->Form->input('user_password');
?>
</fieldset>
<?php echo $this->Form->end(__('Login'));?>
</div>
Debug output
All of these are from the CoreUsersController and going in order in which they are processed.
Hashed password. This is the same as what is in the DB, when I added the user.
'098f6bcd4621d373cade4e832627b4f6'
The Auth object
object(AuthComponent) {
components => array(
(int) 0 => 'Session',
(int) 1 => 'RequestHandler'
)
authenticate => array(
(int) 0 => 'Form'
)
authorize => false
ajaxLogin => null
flash => array(
'element' => 'default',
'key' => 'auth',
'params' => array()
)
loginAction => array(
'admin' => false,
'controller' => 'CoreUsers',
'action' => 'login'
)
loginRedirect => array(
'controller' => 'pages',
'action' => 'index'
)
logoutRedirect => array(
'controller' => 'pages',
'action' => 'display',
(int) 0 => 'home'
)
authError => 'You are not authorized to access that location.'
allowedActions => array(
(int) 0 => 'login'
)
request => object(CakeRequest) {
params => array(
'plugin' => null,
'controller' => 'CoreUsers',
'action' => 'login',
'named' => array(),
'pass' => array()
)
data => array(
'CoreUser' => array(
'user_name' => 'testy5',
'user_password' => 'test'
)
)
query => array()
url => 'CoreUsers/login'
base => '/cpm_v2_dev'
webroot => '/cpm_v2_dev/'
here => '/cpm_v2_dev/CoreUsers/login'
}
response => object(CakeResponse) {
}
settings => array(
'loginRedirect' => array(
'controller' => 'pages',
'action' => 'index'
),
'logoutRedirect' => array(
'controller' => 'pages',
'action' => 'display',
(int) 0 => 'home'
),
'loginAction' => array(
'admin' => false,
'controller' => 'CoreUsers',
'action' => 'login'
),
'userModel' => 'CoreUser'
)
userModel => 'CoreUser'
}
Version of CakePHP
'2.1.0'
Password before login() is called
'test'
Username before login() is called
'testy5'
Password after login() is called
'test'
Here is a quick list of things that I've read in other stackoverflow post that I've tried. Let me know if you need to me to elaborate.
1) I mapped username and password to the fields in the DB. It's where the comments are for fields. I also tried doing it in the beforeFilter() method. Using:
$this->Auth->fields = array('username' => 'user_name', 'password' => 'user_password');
In the login view the form was created as such:
$this->Form->input('username');
$this->Form->input('password');
2) I tried hashing the password manually before login like so:
$this->Auth->request->data['CoreUser']['password'] = Security::hash($this->Auth->request->data['CoreUser']['password'])
if ($this->Auth->login()) {
$this->redirect($this->Auth->redirect());
}
EDIT0
3) I just tried doing this as recommended by CakePHP 2.0 Auth Login not working
My AuthComponent now looks like this:
public $components = array(
'Session',
'Auth' => array(
'authenticate' => array(
'Form' => array(
'userModel' => 'CoreUser',
'fields' => array(
'username' => 'user_name',
'password' => 'user_password'
)
)
),
'loginRedirect' => array('controller' => 'pages', 'action' => 'index'),
'logoutRedirect' => array('controller' => 'pages', 'action' => 'display', 'home'),
'loginAction' => array('admin' => false, 'controller' => 'CoreUsers', 'action' => 'login')
)
);
I apologize if I didn't elaborate enough, or I made a mistake. I've been working on this for a couple of days and it has really drained me. I appreciate any help I may receive. Thanks!
What I ended up doing to solve this issue was following the tutorial exactly as CakePHP has it. I also upgraded to 2.1.2. I was running 2.1.0.
http://book.cakephp.org/2.0/en/tutorials-and-examples/blog-auth-example/auth.html
Then I slowly added the configurations I needed. For information about the Auth component I referenced:
http://book.cakephp.org/2.0/en/core-libraries/components/authentication.html
Really what my problem was poor troubleshooting. I would make a bunch of changes rather than one at a time. I had my login.ctp view two different ways
$this->Form->input('username');
$this->Form->input('password');
and now it looks like this:
echo $this->Form->input('user_name');
echo $this->Form->Label('Password');
echo $this->Form->password('user_password');
The second version works.
EDIT0:
This is very important. Without a call to the AppController parent the login will not work.
class CoreUsersController extends AppController{
public $helpers = array('Html','Form');
public function beforeFilter() {
parent::beforeFilter();
}
The revision for the Auth component works:
public $components = array(
'Session',
'Auth' => array(
'authenticate' => array(
'Form' => array(
'userModel' => 'CoreUser',
'fields' => array(
'username' => 'user_name',
'password' => 'user_password'
)
)
),
'loginRedirect' => array('controller' => 'pages', 'action' => 'index'),
'logoutRedirect' => array('controller' => 'pages', 'action' => 'display', 'home'),
'loginAction' => array('admin' => false, 'controller' => 'CoreUsers', 'action' => 'login')
)
);
My salt is still an empty string:
Configure::write('Security.salt', '');
Setting the md5 hash is only needed in one place. It's not needed in beforeSave() in the model:
public function beforeFilter() {
Security::setHash('md5');
$this->Auth->allow('login','add');
}
beforeSave():
public function beforeSave() {
if (isset($this->data[$this->alias]['user_password'])) {
$this->data[$this->alias]['user_password'] = AuthComponent::password($this->data[$this->alias]['user_password']);
}
return true;
}
If you added the user directly in the db, the that's the problem. Even though you have an empty string in the config, it' using that in the salt algorithm rather than not using a salt. (This is probably a bad idea, but that's another issue).
Also, the Auth->password function is a wrapper for Security::hash() where the salt is always used. Use Security::hash($password, 'md5', false) instead. That will no salt the password when you save the user. However you will probably need to configure your Auth/login function to login without checking for a salt.
I'm positive that your problem is with the way you have configure Auth...the should work fine with your db.
I had the same error, I did a copy of a cakephp project and couldn't login on the new one. After weeks of searching for a correct answer I found that all I had to do was to change permissions on tmp folder. For an unknown reason when I copy folders some of them where copied with read only permissions.