$this->auth->login() Not Working - cakephp

Hello Everyone i'm trying to login after i have successfully add user data into database, but login is not working,I'm new to cakephp.Please Help me out.
here is the code
appcontroller:
class AppController extends Controller {
public $components = array(
'DebugKit.Toolbar' ,'Session',
'Auth' => array(
'loginRedirect' => array('controller' => 'users', 'action' => 'index'),
'logoutRedirect' => array('controller' => 'users', 'action' => 'login')
)
);}
UsersController:
public function login(){
if ($this->request->is('Post')) {
if ($this->Auth->login()) {
return $this->redirect($this->Auth->redirectUrl());
}//$this->Flash->error(__('Invalid username or password, try again'));
}
}
login.ctp:
<?php
echo $this->Form->create('User');
echo $this->Form->input('username');
echo $this->Form->input('password');
echo $this->Form->end('login');
?>

Add password hashing to your User model
User.php
App::uses('AppModel', 'Model');
class User extends AppModel {
public function beforeSave($options = array()) {
if(isset($this->data['User']['password'])) {
$this->data['User']['password'] = AuthComponent::password($this->data['User']['password']);
}
}
}
after that truncate your user table and save fresh user and then check again the login.

Related

CakePHP - basic login functionality not working

I am wrestling with CakePHP trying to create a basic login functionality. So far CakePHP is winning. I followed the basic Blog tutorial and based on that I am try to create a similair login thingy.
The only difference I have is that I not using an Users model, but a custom Employers model and I use email/password instead of username/password.
Yet all I get is "Your username or password was incorrect."
AppController.php
App::uses('Controller', 'Controller');
class AppController extends Controller {
public $components = array(
'Session',
'Auth' => array(
'loginRedirect' => array(
'controller' => 'schedules',
'action' => 'index'
),
'logoutRedirect' => array(
'controller' => 'employers',
'action' => 'login',
'home'
),
'authenticate' => array(
'Form' => array(
'fields' => array(
'username' => 'email',
'password' => 'password'
),
'userModel' => 'Employer',
'passwordHasher' => 'Blowfish'
)
)
)
);
}
EmployersController.php
<?php
App::uses('AppController', 'Controller');
class EmployersController extends AppController {
public $helpers = array('Form');
public function beforeFilter()
{
parent::beforeFilter();
$this->Auth->allow('login');
}
public function login()
{
$layout = 'login';
$this->layout = $layout;
if($this->request->is('post'))
{
debug($this->Auth->login());
if($this->Auth->login())
{
return $this->redirect($this->Auth->redirect());
}
else
{
$this->Session->setFlash('Your username or password was incorrect.');
}
debug($this->request->data['Employers']['password']);
}
}
}
Login.ctp
<div id="login-container">
<h1>Login</h1>
<?php
echo $this->Form->create('Employers');
echo $this->Form->input('email', array('label' => false, 'placeholder' => 'Email'));
echo $this->Form->input('password', array('label' => false, 'placeholder' => 'Password'));
echo $this->Form->submit();
echo $this->Form->end();
?>
When I debug $this->request->data, the data is structered like data["Employers"]['email'] & data["Employers"]['password']. This is propably not right, since my model is called Employer.
Is this correct and does the login functionality break on this and if so, how can I fix that?
Or is there something else I am overlooking.
In your login.ctp,
It should be echo $this->Form->create('Employer'); not with s, so remove s and try it.
Hope it helps.

cakephp Auth Component: login fails everytime

I have developed authentication mechanism in cakePHP prior to this successfully however this time i don't know what is wrongand every time I will be prompted wrong user name/password. I have used Auth component and here are details:
Model names: User,License
sample user info: username: ahmad_agha password:e10adc3949ba59abbe56e057f20f883e which is md5 of 123456
I don't know if it is important in this case or not, but i have enabled admin routing for my controllers.
AppController.php:
class AppController extends Controller {
public $components = array('DebugKit.Toolbar',
'Auth' => array(
'authenticate' => array(
'Form' => array(
'passwordHasher' => array(
'className' => 'Simple',
'hashType' => 'sha256'
)
)
)),
'Cookie');
public function beforeFilter() {
Security::setHash('md5');
$this->Auth->loginRedirect = array('controller'
=> 'licenses', 'action' => 'index');
$this->Auth->logoutRedirect = array('controller'
=> 'owners', 'action' => 'login');
$this->Auth->allow('signup', 'confirm', 'login', 'logout', 'notauthorized', 'display');
$this->Auth->authorize = array('controller');
$this->set('loggedIn', $this->Auth->user('id'));
$this->Auth->userScope = array('User.activated' => '1');
parent::beforeFilter();
}
public function isAuthorized($user) {
// Here is where we should verify the role and give access based on role
return true;
}
}
Login.ctp for User's View
<div class="users form">
<?php echo $this->Session->flash('auth'); ?>
<?php echo md5('136112'); ?>
<?php echo $this->Form->create('User', array('action' => 'login')); ?>
<fieldset>
<legend>
<?php echo __('لطفا نام کاربری و کلمه عبور را وارد کنید'); ?>
</legend>
<?php
echo $this->Form->input('username',array('label'=>'نام کاربری'));
echo $this->Form->input('password',array('label'=>'کلمه عبور'));
echo $this->Form->input('remember_me',array('label'=>'مرا به خاطر بسپار','type'=>'checkbox'));
?>
</fieldset>
<?php echo $this->Form->end(__('ورود')); ?>
</div>
and here is the login() action of UsersController.php:
function login() {
if ($this->request->is('post')) {
if ($this->Auth->login()) {
/* if (!empty($this->data)) {
if (empty($this->data['User']['remember_me'])) {
$this->Cookie->delete('User');
} else {
$cookie = array();
$cookie['username'] = $this->data['User']
['username'];
$cookie['password'] = $this->data['User']
['password'];
$this->Cookie->write('User', $cookie, true, '+2 weeks');
}
unset($this->data['User']['remember_me']);
} */
$this->redirect($this->Auth->redirect());
} else {
$this->Session->setFlash(__('Invalid username or password, try again'));
}
}
}
You say your password is md5 hashed while in config for Auth you have set 'hashType' => 'sha256'. So the mismatch of hash types is quite obvious. Setting Security::setHash('md5') isn't going to do anything since the hashtype set in Auth config will take priority.
You need to change the hashType to md5. Also simply saving md5 hash of password in db won't work since password hasher appends a salt (Security.salt specified in your core.php) to the password before hashing. So do (new SimplePasswordHasher)->hash('123456') to get the hashed value which need to be stored in db. All this is explained in the CakePHP manual btw.

CakePHP2.4 Login and Redirect doesn't work on server

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

debug AuthComponent in cakephp 2.4

I baked a cakephp application with a users table, and I'm trying to get authentication to work using the Blowfish hash. My password field is a varchar(255), so it should be long enough to store the hash. Everything in the app is the default baked output, expect for what follows.
This issue is that I can't log in after creating a user; I always get "Access Denied". What's the best way of troubleshooting this?
AppController.php
App::uses('Controller', 'Controller');
class AppController extends Controller {
public function beforeFilter(){
$this->Auth->allow('index', 'view');
}
public $components = array(
'Session',
'Auth' => array(
'authenticate' => array(
'Form' => array(
'fields' => array('username' => 'email'),
'passwordHasher' => 'Blowfish'
)
),
'loginRedirect' => array('controller' => 'users', 'action' => 'index'),
'logoutRedirect' => array('controller' => 'users', 'action' => 'index'),
'authError' => "Access Denied",
'authorize' => array('Controller'),
)
);
public function isAuthorized($user){
return true;
}
}
User.php (model)
App::uses('AppModel', 'Model');
App::uses('BlowfishPasswordHasher', 'Controller/Component/Auth');
public function beforeSave($options = array()) {
if (!empty($this->data['User']['password'])) {
$passwordHasher = new BlowfishPasswordHasher();
$this->data['User']['password'] = $passwordHasher->hash($this->data['User']['password']);
}
return true;
}
UsersController.php
public function login(){
if ($this->request->is('post')) {
if($this->Auth->login()) {
$this->redirect($this->Auth->redirect());
}
else {
$this->Session->setFlash('Access Denied');
}
}
}
login.ctp
echo $this->Form->create('user');
echo $this->Form->input('email');
echo $this->Form->input('password');
echo $this->Form->button('Log In', array('type' => 'submit');
echo $this->Form->end();
'debug($this->request); die;' in login function gives the following output. should password be * or should it be the hashed version of the input?
data => array(
'user' => array(
'password' => '*****',
'email' => 'test#test.com'
)
)
1)listen to #waspinator echo $this->Form->create('User');
2)
App::uses('BlowfishPasswordHasher', 'Controller/Component/Auth');
remove it ad put it in AppController and it should be
App::uses('AuthComponent', 'Controller/Component');
3)comment this lines
//public function beforeFilter(){
// $this->Auth->allow('index', 'view');
//}
//public function isAuthorized($user){
// return true;
//}
4) for first time put this on top of user controller so you can save your password
public function beforeFilter() {
parent::beforeFilter();
$this->Auth->allow('edit', 'index', 'view);
}
echo $this->Form->create('user');
should be
echo $this->Form->create('User');

Auth login action not generating query in CakePHP

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.

Resources