Some people might find this question silly . But i really hav done all the googling, reading the cakephp documentation but still not able to understand about the Authentication mechanism of cakephp. I have tried my bit of code but still not able to authenticate....
My error for every proper entry i am getting error as invalid username-password.
Here's my code
//login.tpl
<div class="users form">
<?php echo $this->Session->flash('auth'); ?>
<?php echo $this->Form->create('User'); ?>
<fieldset>
<legend><?php echo __('Please enter your username and password'); ?></legend>
<?php echo $this->Form->input('username');
echo $this->Form->input('password');
?>
</fieldset>
<?php echo $this->Form->end(__('Login')); ?>
</div>
//Controllers file
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'));
}
}
}
Can anyone please tell me how to authenticate, i am new to cakephp
Well cakephp handle authentication itself you don't need to write code inside login function.
app_controller.php
<?php
class AppController extends Controller
{
var $components = array
(
'Auth',
'Session',
'RequestHandler',
'Email'
);
var $helpers = array
(
'Javascript',
'Form',
'Html',
'Session'
);
function beforeFilter()
{
$this->Auth->autoRedirect = true;
$this->Auth->authError = 'Sorry, you are not authorized to view that page.';
$this->Auth->loginError = 'invalid username and password combination.';
$this->Auth->loginAction = array
(
'controller' => 'users',
'action' => 'login',
'admin' => true
);
$this->Auth->logoutRedirect = array
(
'controller' => 'users',
'action' => 'logout',
'admin' => true
);
$this->Auth->loginRedirect = array
(
'controller' => 'users',
'action' => 'dashboard',
'admin' => true
);
$this->Auth->fields = array('username' => 'email', 'password' => 'password');
}
?>
users_controller.php
<?php
class UsersController extends AppController
{
var $name = 'Users';
/*
do not forget to add beforeFilter function and inside this function call parent beforeFilter function.
*/
function beforeFilter()
{
parent::beforeFilter();
}
function admin_login()
{
}
function admin_logout()
{
$this->Session->destroy();
$this->Auth->logout();
$this->Session->setFlash(__('Yor are now Logged out Successfully', true), 'default',array('class'=>'alert alert-success'));
$this->redirect('/');
exit;
}
?>
And you are done.
Related
I have an app recently upgraded from cakephp 1.3 to cakephp 2. When trying to log in, it insists on checking the db for a 'Customer.username' field equal to the email, but I'm pretty sure I configured it to use email.
Heres my AppController:
class AppController extends Controller {
public $components = array('Auth' => array(
'authenticate' => array(
'Form' => array(
'fields' => array('username' => 'Email', 'password' => 'password')
)
)
), 'Security', 'AntiXss', 'Cookie');
public $helpers = array('Js', 'Html', 'Form', 'Number', 'DateFormat', 'Currency', 'Session', 'DebugKit.Toolbar');
public $uses = array('Language', 'Customer', 'Affiliate', 'Setting', 'Whitelabel');
public function beforeFilter() {
Debugger::dump($this);
//Configure AuthComponent
$this->Auth->userModel = 'Customer';
$this->Auth->fields = array('username' => 'Email', 'password' => 'password');
$this->Auth->loginAction = array('controller' => 'customers', 'action' => 'login');
$this->Auth->logoutRedirect = array('controller' => 'customers', 'action' => 'login');
$this->Auth->loginRedirect = '/';
$this->Auth->identifyMethod = 'login_identify';
$this->Auth->authError = __("Please log in to continue.");
$this->Auth->authenticate = array(
AuthComponent::ALL => array('userModel' => 'Customer'),
'Basic',
'Form' => array('fields' => array('username' => 'Email'))
);
And then the login code in the View:
<?php echo $this->Form->create('Customer', array('action' => 'login')); ?>
<fieldset class="Login">
<?php
echo $this->Form->input('Email', array("label"=>__('Email')));
echo $this->Form->input('password', array("label"=>__('Password')));
echo $this->whiteLabelElement('login_terms');
echo $this->Form->button(__('Log In'), array('type'=>'submit', 'class' => 'button loginButton'));
?>
</fieldset>
<?php echo $this->Form->end(); ?>
And the login code from the Customers Controller:
function login() {
if($this->loggedCustomerData) { $this->redirect("/"); } // If user is logged in, redirect to home
if ($this->request->is('post')) {
if ($this->Auth->login()) {
return $this->redirect($this->Auth->redirect('/accounts/'));
} else {
$this->Session->setFlash(__('Username or password is incorrect'), 'default', array(), 'auth');
}
}
}
// This is not an action. It's called by the login process, passing in email and password, for this method to return
// the customer that should be logged in (or null if invalid password). Here, we resolve to the right customer record
// in the right whitelabel
function login_identify($data, $conditions) {
if (isset($data['id'])) { // This means we got called by AutoLogin...
$this->LoginAudit->LogLogin($data['id'], "auto_login");
return array('Customer' => $data); // Somehow we get a Customer array, but not in a sub-array.
}
$whitelabel = $this->Whitelabel->GetWhitelabelFromHost();
$email = $data['Customer.Email'];
// First look for a *customer* (not a lead) in this whitelabel
$objCustomer = $this->Customer->findByWhitelabelAndEmail($whitelabel, $email, false, false);
// Then, a *customer* in another sharing whitelabel
if (!$objCustomer) { $objCustomer = $this->Customer->findByWhitelabelAndEmail($whitelabel, $email, true, false); }
// Finally, if there are no customers we can use, maybe we have a lead in this whitelabel
// We don't look for leads in other whitelabels, that makes no sense. The customer can register in this site at this point, but he can't login
if (!$objCustomer) { $objCustomer = $this->Customer->findByWhitelabelAndEmail($whitelabel, $email, false, true); }
// Finally, validate the password if we found a customer
if ($objCustomer) {
if ($data['Customer.password'] == $objCustomer['Customer']['password']) {
$this->LoginAudit->LogLogin($objCustomer['Customer']['id']);
return $objCustomer;
}
}
return null;
}
FROM: http://book.cakephp.org/2.0/en/core-libraries/components/authetication.html
To configure different fields for user in $components array:
// Pass settings in $components array
public $components = array(
'Auth' => array(
'authenticate' => array(
'Form' => array(
'fields' => array('username' => 'email')
)
)
)
);
I am working on a personal project and I have searched through multiple topics that are related to my issue and I cannot find a solution to my problem.
Whenever I enter an email and password on my login page it always give me an invalid username or password pop up. I debugged a part of code in my UserloginController and it just returns false. There is probably a problem here but i cannot see it.
Some solutions for other people were to change the VARCHAR length of the password field, my password field is already a VARCHAR(255) and it hashes properly so this is not the problem.
Here is my AppController
class AppController extends Controller
{
public function isAuthorized($user = null)
{
// Any registered user can access public functions
if (empty($this->request->params['prefix'])) {
return true;
}
// Only admins can access admin functions
if ($this->request->params['prefix'] === 'admin') {
return (bool)($user['role'] === 'admin');
}
// Default deny
return false;
}
public function initialize()
{
$this->loadComponent('Flash');
$this->loadComponent('Auth', [
'authenticate' => [
'Form' => [
'userModel' => 'userlogin',
'fields' => [
'username' => 'email',
'password' => 'password'
]
]
],
'loginAction' => [
'controller' => 'userlogin',
'action' => 'login'
],
'logoutRedirect' => [
'controller' => 'userlogin',
'action' => 'login'
],
]);
// Allow the display action so our pages controller
// continues to work.
$this->Auth->allow(['display']);
}
public function beforeRender(Event $event)
{
if (!array_key_exists('_serialize', $this->viewVars) &&
in_array($this->response->type(), ['application/json', 'application/xml'])
) {
$this->set('_serialize', true);
}
}
}
Here is my UserLoginController
class UserloginController extends AppController
{
public function initialize() {
parent::initialize();
$this->Auth->allow(['logout', 'add']);
}
//login
public function login(){
if ($this->request->is('post')) {
$user = $this->Auth->identify();
debug($this->Auth->identify()); // Returns False
if ($user) {
$this->Auth->setUser($user);
return $this->redirect($this->Auth->redirectUrl());
}
$this->Flash->error('Your username or password is incorrect.');
}
}
public function logout() {
$this->Flash->success('You are now logged out.');
return $this->redirect($this->Auth->logout());
}
public function beforeFilter(Event $event) {
parent::beforeFilter($event);
$this->Auth->allow('logout', 'login', 'index', 'add'); //you can add others here...
}
}
And Here is my Login.ctp
<br>
<div class="index large-4 medium-4 large-offset-4 medium-offset-4 columns">
<div class="panel">
<h1>Login</h1>
<?= $this->Form->create(); ?>
<?= $this->Form->input('email'); ?>
<?= $this->Form->input('password'); ?>
<?= $this->Form->button('Login'); ?>
<?= $this->Form->end(); ?>
Any sort of help will be greatly appreciated!
In cakephp have changed from simplePasswordHasher to BlowfishPasswordHasher . I add the following code and comment out all refernces to the old simplehasher method but I cant login. I can create a new user with BlowfishPasswordHasher but logins now dont work?
The link below didnt fix the problem as I just cant login but I can see the new user with correct salted password
CakePHP - How do I implement blowfish hashing for passwords?
http://book.cakephp.org/2.0/en/tutorials-and-examples/blog-auth-example/auth.html
//userscontroller
public function login() {
if ($this->request->is('post')) {
if ($this->Auth->login()) {
return $this->redirect($this->Auth->redirectUrl()); //for 2.3 and above versions, docs are old
}
$this->Session->setFlash(__('Invalid username or password, try again'));
}
}
//user
App::uses('BlowfishPasswordHasher', 'Controller/Component/Auth');
public function beforeSave($options = array()) {
if (isset($this->data[$this->alias]['password'])) {
$passwordHasher = new BlowfishPasswordHasher();
$this->data[$this->alias]['password'] = $passwordHasher->hash(
$this->data[$this->alias]['password']
);
}
return true;
}
//new user
<?php echo $this->Form->create('User'); ?>
<h2><?php echo __('Add User2'); ?></h2>
<?php
echo $this->Form->input('username');
echo $this->Form->input('password');
//in appcontroller
public $components = array( "Email", 'Session', 'Auth');
public function beforeFilter() {
$this->Auth->authError = 'You cant access this page';
$this->Auth->loginRedirect= array('controller' => 'users', 'action' => 'dashboard');
$this->Auth->logoutRedirect= array('controller' => 'users','action' => 'login' );
$this->Auth->authorize= array('Controller');
$this->Auth->unauthorizedRedirect= '/users/dashboard';
$this->set("logged_in", $this->Auth->loggedIn())
//user model
public $validate = array(
'username' => array(
'required' => array(
'rule' => array('notEmpty'),
'message' => 'A username is required'
)
),
'password' => array(
'required' => array(
'rule' => array('notEmpty'),
'message' => 'A password is required'
)
)
You haven't configured Auth to use BlowfishPasswordHasher so it's still uses the default hasher. Specify the passwordHasher key as shown in eg. here.
I just started trying to learn cakephp auth, i just copied and pasted the code, trying to understand it. I can't figure out what is directly the redirect
//app controller
//is empty i know in some cases you put it here, i'm just tested it in the user controller
//user controller
public $components = array('Paginator',
'Session',
'Auth' => array(
'loginAction' => array(
'controller' => 'users',
'action' => 'login',
'plugin' => 'users'
),
'authError' => 'Did you really think you are allowed to see that?',
'authenticate' => array(
'Form' => array(
'fields' => array('username' => 'email')
)
)
)
);
public function beforeFilter() {
$this->Auth->allow('index', 'view');
}
public function login() {
if ($this->request->is('post')) {
if ($this->Auth->login()) {
return $this->redirect($this->Auth->redirectUrl());
// Prior to 2.3 use
// `return $this->redirect($this->Auth->redirect());`
} else {
$this->Session->setFlash(
__('Username or password is incorrect'),
'default',
array(),
'auth'
);
}
}
}
I understand the before filter makes sense, it only allows index and view, i have another controller called admin which redirects to the login page if your not logged in
but for somme reason it keeps redirecting to users/users/login, i want it to go to users/login? How do i fix this?
you just have to put the controller wherever you go and the action
public function login() {
if ($this->request->is('post')) {
if ($this->Auth->login()) {
return $this->redirect(array('controller' => 'users', 'action' => 'login'));
}
} else {
$this->Session->setFlash(__('Invalido nombre de usuario o contraseña'));
}
}
I am sorry that I asking this question, I’ve googled the problem and it giving me a lot of answer but it turns out everything is not working for me. I try to do the login page for one of my website using cakephp 2.0 and what happen is, when I save the user data, the password is not hashing and I can't login using the data that has been saved.
Here are what I have have done so far:
Model/user.php
App::uses('SimplePasswordHasher', 'Controller/Component/Auth');
class User extends AppModel {
/* validate data enetered by user */
public $validate = array(
'username' => array(
'required' => array(
'rule' => array('notEmpty'),
'message' => 'A username is required'
)
),
'password' => array(
'required' => array(
'rule' => array('notEmpty'),
'message' => 'A password is required'
)
)
);
public function beforeSave($options = array()) {
if (!$this->id) {
$passwordHasher = new SimplePasswordHasher();
$this->data['User']['password'] = $passwordHasher->hash(
$this->data['User']['password']
);
}
return true;
}
}
Controller/AppController.php
class AppController extends Controller {
public $components = array(
'Session',
/* add Auth component and set the urls that will be loaded after the login and logout actions is performed */
'Auth' => array(
'authenticate' => array(
'Form' => array(
'passwordHasher' => array(
'className' => 'Simple',
'hashType' => 'sha256'
)
)
),
'loginRedirect' => array('controller' => 'Dashboard', 'action' => 'index'),
'logoutRedirect' => array('controller' => 'Users', 'action' => 'login')
)
);
public function beforeFilter() {
/* set actions that will not require login */
$this->Auth->allow('index','display', 'view');
}
}
Controller/UsersController.php`
class UsersController extends AppController {
public function beforeFilter() {
parent::beforeFilter();
$this->Auth->allow('add', 'login');
}
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());
}
$this->Session->setFlash(__('Invalid username or password, try again'));
echo $this->Auth->password('the-chosen-password');
}
}
public function logout() {
/* logout and redirect to url set in app controller */
return $this->redirect($this->Auth->logout());
}
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'));
return $this->redirect(array('controller' => 'Users','action' => 'login'));
}
$this->Session->setFlash(__('The user could not be saved. Please, try again.'));
}
}
}
View/Users/add.ctp
<div class="users form">
<?php echo $this->Form->create('User'); ?>
<fieldset>
<legend><?php echo __('Add User'); ?></legend>
<?php
echo $this->Form->input('username');
echo $this->Form->input('password');
?>
</fieldset>
<?php echo $this->Form->end(__('Submit')); ?>
View/Users/login.ctp
<?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')); ?>
I really hope that someone will look over it for me.
Thanks a lot.
Not sure why would you only hash passwords when the user model's id property exists (or only when you're doing an update essentially). I suggest you should always hash the password if the password exists in the $data array passed to save(). So change the beforeSave() in your User model to the following:
public function beforeSave($options = array()) {
if (!empty($this->data[$this->alias]['password'])) {
$passwordHasher = new SimplePasswordHasher();
$this->data[$this->alias]['password'] = $passwordHasher->hash(
$this->data[$this->alias]['password'],
);
}
return true;
}
Not sure but might work...
this public function beforeFilter() {
/* set actions that will not require login */
$this->Auth->allow('index','display', 'view');
}
should be in your UsersController. Because you add this to AppController its Allow all index, display and view action as public.
If not work then answer few question...
1. Are you able to register new user and are your password hasher is woring?
2. It there is any error message? If you are using DebugKit, you can easily find the error message.
3. It is looping for infinite?