Im trying to use Employee model instead of User model in Auth component. My code is:
AppController
public $components = array('Session','Auth');
function beforeFilter(){
Security::setHash('md5');
$this->Auth->userModel = 'Employee';
$this->Auth->fields = array('username'=>'code','password'=>'password');
$this->Auth->loginAction = array('controller'=>'employees','action'=>'login');
$this->Auth->loginRedirect = array('controller'=>'pages','action'=>'home');
$this->Auth->loginError = 'Invalid employee code or password, please try again';
$this->Auth->logoutRedirect = array('controller'=>'employees','action'=>'login');
}
function beforeRender(){
$this->set('Employee',$this->Auth->user());
}
EmployeeController
function login(){
$this->layout = 'login';
}
function logout(){
$this->Redirect($this->Auth->logout());
}
function beforeFilter(){
parent::beforeFilter();
$this->Auth->allow('signup');
}
function beforeRender(){
parent::beforeRender();
}
login.ctp
<?php
echo $this->Form->create('Employee',array('/employees/login'));
echo $this->Form->input('code',array('label'=>'Employee code'));
echo $this->Form->input('password');
echo $this->Form->submit('Sign in',array('class'=>'b-button'));
echo $this->Form->end();
?>
The problem is, when i click the login button, page simply refreshes. No redirect, noerror messages, no nothing.
Is there any mistake in what im doing?
EDIT
function login(){
$this->layout = 'login';
if($this->request->is('post')){
if($this->Auth->login($this->request->data)){
$this->Redirect('/pages/home');
}else{
$this->Session->setFlash('incorrect');
}
}
}
function logout(){
$this->redirect($this->Auth->logout());
}
Now its allowing logging in irrespective of the the employee code or password entered. In fact its alloing logging in even if login fields are empty.
Try the following:
echo $this->Form->create('Employee', array('controller' => 'employees', 'action' => 'login'));
And also check the user authenticity in login method of your EmployeesController.php
public function login()
{
if ($this->request->is('post'))
{
if ($this->Auth->login($this->request->data))
{
/*... do what you want...*/
}
else
{
this->Session->setFlash('Your username or password was incorrect.');
}
}
}
echo $this->Form->create('Employee',array('/employees/login'));
Try:
echo $this->Form->create('Employee',array('action'=>'login'));
I had similar issue . Finally here is the solution.
a) Define the tablename and fileds inside $components. Dont use before filter
public $components = array('Session', 'Acl', 'Auth' => array('authenticate' => array('Form' => array('userModel' => 'Employee','fields' => array('username' => 'code'), 'password' => 'password'))), 'Cookie');
b)Never use
$this->Auth->login($this->request->data)
this creates session for whatever garbage u post.
Instead use
$this->Auth->login()
c) Also hashing method for cakephp is not md5. You may want to remove that line.
Related
Sorry to bring this topic up again, but I've searched all the answers I can on this topic, but have not found a solution(I'm very new to cakephp):
I use the password routine to hash my password
in my AppController I have:
class AppController extends Controller {
public $components = array('DebugKit.Toolbar','Session','Auth');
}
in my UsersController I have:
public function add() {
if ($this->request->is('post')) {
$this->User->create();
// hash the password coming in from the form using Authcomponent::password
$this->request->data['User']['password'] = AuthComponent::password($this->request->data['User']['password']);
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.'));
}
}
}
/** login method */
public function login() {
if ($this->request->is('post')) {
if ($this->Auth->login()) {
//redirect to page he was trying to access before login
return $this->redirect($this->Auth->redirectUrl());
} else {
$this->Session->setflash('Invalid username or password');
}
}
}
The issue is that I cannot log back in after adding a user: I get the setflash message. The password is being hashed correctly on the MySQL database.
Any help appreciated: I'm at a loss how to debug this.
EDIT
I've tried other solutions, from the cakephp site (no success) and 2 youtube sites (no success). I have also tried plain passwords and hashed passwords (using the default and blowfish) all with the same result.
I have added the debug statements to the code as follows:
public function login() {
pr($this->request->data); //debug
if ($this->request->is('post')) { //devbug
echo ('post request');} //debug
if ($this->request->is('post')) {
debug($this->Auth->login()); //debug
debug($this->request->data); //debug
if ($this->Auth->login()) {
return $this->redirect($this->Auth->redirectUrl());
}
$this->Session->setFlash(__('Invalid username or password, try again'));
}
}
The array displayed using pr($this->request->data); shows the correct data, however when I use debug($this->request->data); it shows only 5 characters in the password. Could t his be the issue (or a red herring?)
result as displayed follows:
Array
(
[User] => Array
(
[username] => user
[password] => password
)
)
post request
\app\Controller\UsersController.php (line 18)
false
\app\Controller\UsersController.php (line 19)
array(
'User' => array(
'password' => '*****',
'username' => 'user'
)
)
You should try this
AppController
class AppController extends Controller {
public $components = array(
'RequestHandler','Session',
'Auth' => array(
'Autoredirect'=>false,
'loginRedirect' => array('controller' => 'users', 'action' => 'user_dashboard'),
'logoutRedirect' => array('controller' => 'users', 'action' => 'login'),
'authError' => 'Did you really think you are allowed to see that?',
)
);
UsersController
public function login() {
if ($this->request->is('post')) {
if ($this->Auth->login()) {
return $this->redirect($this->Auth->redirect());
} else {
$this->Session->setflash('Invalid username or password');
}
}
}
Try adding this line in the login function:
public function login() {
pr($this->request->data);//LINE ADDED
if ($this->request->is('post')) {
if ($this->Auth->login()) {
return $this->redirect($this->Auth->redirect());
} else {
$this->Session->setflash('Invalid username or password');
}
}
you will see what data you are passing to the form login.
You are saving an encrypted password, but when you log in your software expects an unencrypted password.
Try to put a password unencrypted to your database and it should work.
Try this here in your app controller:
public $components = array('DebugKit.Toolbar','Session','Auth' => array(
'authenticate' => array(
'Form' => array(
'passwordHasher' => 'Blowfish',
),
)
));
If that is still not working, please post your login-form as well.
I'm using cakePHP building a website. The login function works fine in local, but after I post them onto the server, I cannot login with existing username and password. The page doesn't either let me log in, or give me an error message which is supposed to show up when there are issues. I tried almost every solution in stackoverflow but can't solve it. Here's my code.
Model:
class User extends AppModel {
public function beforeSave($options = array()) {
/* password hashing */
if (isset($this->data[$this->alias]['password'])) {
$this->data[$this->alias]['password'] = AuthComponent::password($this->data[$this->alias]['password']);
}
return true;
}
}
AppController:
class AppController extends Controller {
public function webroot() {
}
public $components = array('DebugKit.Toolbar','Session',
/* add Auth component and set the urls that will be loaded after the login and logout actions is performed */
'Auth' => array(
'loginRedirect' => array('controller' => 'Home', 'action' => 'index'),
'logoutRedirect' => array('controller' => 'users', 'action' => 'login')
)
);
public function beforeFilter() {
/* set actions that will not require login */
$this->Auth->allow('index','display', 'view');
}
}
UsersController:
class UsersController extends AppController {
public $components = array('Auth');
public function beforeFilter() {
parent::beforeFilter();
$this->Auth->allow('add', 'logout');
}
public function login() {
if ($this->request->is('post')) {
/* login and redirect to url set in app controller */
if ($this->Auth->login()) {
return $this->redirect($this->Auth->redirect('/Home'));
}
$this->Session->setFlash(__('Invalid username or password, try again'));
}
}
public function logout() {
/* logout and redirect to url set in app controller */
return $this->redirect($this->Auth->logout());
}
public function index() {
$this->User->recursive = 0;
$this->set('Users', $this->paginate());
}
public function add() {
if ($this->request->is('post')) {
$this->User->create();
if ($this->User->save($this->request->data)) {
$this->Session->setFlash;
return $this->redirect(array('controller' => 'Home','action' => 'index'));
}
$this->Session->setFlash(__('The user could not be saved. Please, try again.'));
}
}
}
View:
<?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')); ?>
Another glitch I think I should mention is, as the code shows, when I add a new username and pw, the page should redirect me to Home. This also works fine locally, but on server it doesn't redirect, HOWEVER, the username and password is successfully stored into database when I added it.
I'm really stuck and have no clue what the problem is, any help is appreciated, thanks.
Update
errors in error.log :
2014-05-14 05:16:21 Error: [MissingActionException] Action UsersController::js() could not be found.
Exception Attributes: array (
'controller' => 'UsersController',
'action' => 'js',
)
Request URL: /users/js/lightbox.min.js
2014-05-14 05:16:21 Error: [MissingActionException] Action UsersController::js() could not be found.
Exception Attributes: array (
'controller' => 'UsersController',
'action' => 'js',
)
Request URL: /users/js/jquery-1.11.0.min.js
This question already has answers here:
Login Script in 2.4.2 is not working
(2 answers)
Closed 8 years ago.
my problem is : 'when i enter wrong username-password combination, it still redirects me to index page, while it should be redirected to login page again '.. what is the problem ??Pl help me... i am atteching my code...
here is AppController:
class AppController extends Controller {
public $components=array('DebugKit.Toolbar',
'Session','Auth' => array(
'loginRedirect' => array('controller' => 'users', 'action' => 'login'),
'logoutRedirect' => array('controller' => 'users', 'action' => 'index')
));
public function beforeFilter(){
$this->Auth->allow('index','register');
}
}
here is UsersController:
class UsersController extends AppController
{
public $name='Users';
public $uses=array('user');
public $helpers = array('Html', 'Form','Session');
public function beforeFilter() {
parent::beforeFilter();
}
public function index()
{
}
public function login() {
if ($this->request->is('post')) {
/* login and redirect to url set in app controller */
if ($this->Auth->login($this->request->data)) {
$this->Session->setFlash(__('Successful!!!'));
$this->Session->write('user',$this->data['user']['username'],time()+3600);
return $this->redirect(array('action'=>'index'));
}
$this->Session->setFlash(__('Invalid username or password, try again'));
}
// else{ echo "fail";exit;}
}
public function logout() {
/* logout and redirect to url set in app controller */
$this->Session->destroy();
return $this->redirect($this->Auth->logout());
}
public function register() {
if ($this->request->is('post')) {
$this->user->create();
if ($this->user->save($this->request->data)) {
$this->Session->setFlash(__('The user has been saved'));
return $this->redirect(array('controller' => 'users','action' => 'index'));
}
$this->Session->setFlash(__('The user could not be saved. Please, try again.'));
}
}
}
here is User Model:
<?php
class User extends AppModel
{
var $name='User';
var $validate=array(
'username'=> array(
'rule'=>'notEmpty',
'message'=>'Enter Your USername'),
'password'=>array(
'rule'=>'notEmpty',
'message'=>'Enter your Password'
),
'Confirm_password'=>array(
'rule'=>'match',
'message'=>'password not match, try again'
)
);
public function match(){
if($this->data['user']['password']===$this->data['user']['Confirm_password'])
{
return true;
}
return false;
}
public function beforeSave($options = array()) {
/* password hashing */
if (isset($this->data[$this->alias]['password'])) {
$this->data[$this->alias]['password'] = AuthComponent::password($this->data[$this->alias]['password']);
}
return true;
}
}
?>
here is my login ctp:
<h2>LOGIN-MYSITE</h2>
<?php echo $this->Form->create('user',array('action'=>'login'));
echo $this->Form->input('username');
echo $this->Form->input('password');
echo $this->Form->end('LOGIN');
?>
Remove 'index' from
$this->Auth->allow('index','register');
Keep
$this->Auth->allow('register');
I have a simple login form, just like the Cake Blog Tutorial.
It works like a charm when I use 'UsersController' and 'User' model naming conventions, passing the rights queries in debug.
But when I change it to other name, Alunos in my case, it generates no QUERY and give me 'Incorrect username and/or password.'.
My login.ctp
<H1> Login </H1>
<?php
debug($this->data);
echo $this->Form->create('Aluno', array('action' => 'login'));
echo $this->Form->input('username');
echo $this->Form->input('password');
echo $this->Form->end('Login');
?>
My AppController
<?php
class AppController extends Controller {
public $components = array (
'Session',
'Auth' => array (
'loginAction' => array ('controller'=>'alunos', 'action'=>'login'),
'loginRedirect'=>array ('controller'=>'alunos', 'action'=>'inicio'),
'logoutRedirect'=>array ('controller'=>'alunos', 'action'=>'index'),
'authError'=>"Ops, você não está autorizado a fazer isso.",
'authorize'=>array('Controller'),
)
);
public function isAuthorized($user) {
return true;
}
public function beforeFilter() {
$this->Auth->allow('index', 'add');
$this->set('logged_in', $this->Auth->loggedIn());
$this->set('current_user', $this->Auth->user());
}
}
And my 'AlunosController.php' (see that its not USERSController, like common codes)
<?php
class AlunosController extends AppController {
public $name = 'Alunos';
public function beforeFilter(){
parent::beforeFilter();
}
public function index() {}
public function login(){
debug($this->Auth->login());
if ($this->request->is('post')) {
if ($this->Auth->login()){
$this->redirect($this->Auth->redirect());
} else {
$this->Session->setFlash('Incorrect username and/or password.');
}
}
}
public function logout() {
$this->redirect($this->Auth->logout());
}
public function add() {
debug($this->Auth->login());
if($this->request->is('post')) {
if ($this->Aluno->save($this->request->data)) {
$this->Session->setFlash('Cadastrado.');
}else {
$this->Session->setFlash('Falha no cadastro.');
}
}
}
public function inicio() {
debug($this->Auth->login());
}
}
?>
My debug($this->data) in login.ctp result:
array(
'Aluno' => array(
'password' => '*****',
'username' => 'anyuser'
)
)
What am I doing wrong?
Add this code to your app controller:
function beforeFilter() {
$this->Auth->userModel = 'Aluno'; <-- Should be singular. My mistake
parent::beforeFilter();
}
UPDATE FOR CAKE2
// Place in beforeFilter() of AppController.php
$this->Auth->authenticate = array(
'Form' => array(
'userModel' => 'Aluno'
)
);
Your problem is because you are not telling cake what to use for a user table. This is why your first instance works, and the second does not.
Change this:
echo $this->Form->create('Aluno', array('action' => 'login'));
to:
echo $this->Form->create('Alunos', array('url' => 'alunos/login'));
To call Alunos Controller's login() method.
I am trying to make the login work... but when i register (using the add) function i used to have a md5, then i changed it to $this->Auth->password, and then i tried without that line.. well it logins fine the first time.. but then for some reason it changes the hash again on login it never matches the database.. i dont know how to fix this.. here is my code
<?php
class UsersController extends AppController {
var $uses = array("User");
var $components = array('Auth', 'Session');
function index()
{
$this->set('users', $this->User->find('all'));
$this->layout = 'master_layout';
}
function beforeFilter() {
$this->Auth->allow('add');
}
function add() {
if (!empty($this->data)) {
//pass is hashed already
//->data['User']['password'] = $this->Auth->password($this->data['User']['password']);
if ($this->User->save($this->data)) {
$this->Session->setFlash('Your were registered!.');
$this->redirect(array('action' => 'index'));
}
}
$this->layout = 'master_layout';
}
//IF THE DATABASE IS SET UP CORRECTLY CAKE AUTHENTICATES AUTOMATICALLY NO
//LOGIC IS NEEDED FOR LOGIN http://book.cakephp.org/view/1250/Authentication
function login() {
$this->layout = 'master_layout';
}
function logout() {
$this->redirect($this->Auth->logout());
}
}
?>
VIEW
<?php
echo $this->Session->flash('auth');
echo $this->Form->create('User');
echo $this->Form->input('username');
echo $this->Form->input('password');
echo $this->Form->end('Login');
?>
you shouldnt use password as field name on forms.
this way even empty strings will be saved and will mess up already saved ones. depending on your beforeSave method the empty string might even be saved as hash (cloaking that its actually an empty password).
see
http://www.dereuromark.de/2011/08/25/working-with-passwords-in-cakephp/