Cakephp 3.2 Users can't Log in - php

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!

Related

Unable to login in Cakephp 3 Application

I am working on login and registration module in Cakephp 3 but is not able to login and while registration the password is also not hashed it is saving as plain text. I am getting error : Invalid username or password, try again.
I have followed some tutorial but some thing is missing which causes application to not properly logging in. Please help to sort out my issue.
Below is the complete code:
Login.ctp
<h1> Login </h1>
<p>Enter your username & password: </p>
<?php echo $this->Form->create();
echo $this->Form->input('email');
echo $this->Form->input('password');
echo $this->Form->button('Login');
echo $this->Form->end()
?>
AppController.ctp
<?php
namespace PanelAdmin\Controller;
use Cake\Event\Event;
use Cake\View\Helper\FlashHelper;
use Cake\Controller\Component\FlashComponent;
use App\Controller\AppController as BaseController;
class AppController extends BaseController
{
public function initialize()
{
parent::initialize();
$this->loadComponent('RequestHandler');
$this->loadComponent('Flash');
$this->loadComponent('Auth', [
'authorize'=> 'Controller',
'authenticate' => [
'Form' => [
// fields used in login form
'fields' => [
'username' => 'email',
'password' => 'password'
]
]
],
// login Url
'loginAction' => [
'controller' => 'Users',
'action' => 'login'
],
// where to be redirected after logout
'logoutRedirect' => [
'controller' => 'Topics',
'action' => 'index'//,
//'home'
],
// if unauthorized user go to an unallowed action he will be redirected to this url
'unauthorizedRedirect' => [
'controller' => 'Topics',
'action' => 'index'//,
//'home'
],
'authError' => 'Did you really think you are allowed to see that?',
]);
// Allow the display action so our pages controller still works and user can visit index and view actions.
$this->Auth->allow(['index','display','view']);
}
public function isAuthorized($user)
{
$this->Flash->error('You aren\'t allowed');
return false;
}
public function beforeFilter(Event $event)
{
$this->Auth->allow(['index', 'view', '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);
}
}
}
?>
UsersController.ctp
<?php
namespace PanelAdmin\Controller;
use Cake\Controller\Controller;
use Cake\ORM\TableRegistry;
use Cake\Event\Event;
class UsersController extends AppController
{
public function initialize()
{
parent::initialize();
$this->loadComponent('Flash'); // Include the FlashComponent
// Auth component allow visitors to access add action to register and access logout action
$this->Auth->allow(['logout', 'add']);
}
public function login()
{
if ($this->request->is('post')) {
// Auth component identify if sent user data belongs to a user
$user = $this->Auth->identify();
if ($user) {
//
$this->Auth->setUser($user);
return $this->redirect($this->Auth->redirectUrl());
}
$this->Flash->error(__('Invalid username or password, try again.'));
}
}
public function logout(){
$this->Flash->success('You successfully have loged out');
return $this->redirect($this->Auth->logout());
}
public function index()
{
$this->set('users',$this->Users->find('all'));
}
public function view($id)
{
$user = $this->Users->get($id);
$this->set('user',$user);
}
public function add()
{
$user = $this->Users->newEntity();
if($this->request->is('post')) {
$this->Users->patchEntity($user,$this->request->data);
if($this->Users->save($user)){
$this->Flash->success(__('Your account has been registered .'));
return $this->redirect(['action' => 'index']);
}
$this->Flash->error(__('Unable to register your account.'));
}
$this->set('user',$user);
}
public function edit($id)
{
$user = $this->Users->get($id);
if ($this->request->is(['post', 'put'])) {
$this->Users->patchEntity($user, $this->request->data);
if ($this->Users->save($user)) {
$this->Flash->success(__('Your profile data has been updated.'));
return $this->redirect(['action' => 'index']);
}
$this->Flash->error(__('Unable to update your profile.'));
}
$this->set('user', $user);
}
public function delete($id)
{
$this->request->allowMethod(['post', 'delete']);
$user = $this->Users->get($id);
if ($this->Users->delete($user)) {
$this->Flash->success(__('The user with id: {0} has been deleted.', h($id)));
return $this->redirect(['action' => 'index']);
}
}
}
?>
UsersTable.ctp
<?php
namespace App\Model\Table;
use Cake\ORM\Table;
use Cake\Validation\Validator;
use Cake\Auth\DefaultPasswordHasher;
class UsersTable extends Table
{
public function validationDefault(Validator $validator)
{
return $validator
->notEmpty('email', 'A email is required')
->add('email', 'valid' , ['rule'=> 'email'])
->add('email', [
'unique' => ['rule' => 'validateUnique', 'provider' => 'table']
])
->requirePresence('email','create')
->notEmpty('password', 'A password is required')
->notEmpty('role', 'A role is required')
->add('role', 'inList', [
'rule' => ['inList', ['admin', 'author']],
'message' => 'Please enter a valid role'
]);
}
}
?>
Entity : User.php
<?php
namespace App\Model\Entity;
use Cake\ORM\Entity;
use Cake\Auth\DefaultPasswordHasher;
class User extends Entity
{
protected $accessible = [
'*' => true,
'id' => false,
];
protected function _setPassword($password) {
if (strlen($password) > 0) {
return (new DefaultPasswordHasher)->hash($password);
}
}
}
?>
add.ctp
<h1>Register new user </h1>
<?php
echo $this->Flash->render('auth');
echo $this->Form->create($user);
echo $this->Form->input('name');
echo $this->Form->input('username');
echo $this->Form->input('password');
echo $this->Form->input('password2',array('label'=>"confirm password",'type'=>'password'));
echo $this->Form->input('email');
echo $this->Form->input('phone');
echo $this->Form->input('birthdate',[
'minYear' => date('Y') - 80,
'maxYear' => date('Y') - 10
]);
echo $this->Form->button(__('Register'));
echo $this->Form->end();
?>

cakePHP registration don't work

I'm new to CakePHP and just starting with the CookBook Examples. Now I want to create a simple registration and Login form with my custome Table columns. But the system do not want to insert the data! Where is my mistake? Is it right to tell him in the AppController which fields to use?
add.ctp=
<div class="users_form">
<?= $this->Form->create($user) ?>
<fieldset>
<legend><?= __('Add') ?></legend>
<?= $this->Form->input('username') ?>
<?= $this->Form->input('password') ?>
</fieldset>
<?= $this->Form->button(__('Submit')); ?>
<?= $this->Form->end() ?>
UsersTable.php
class UsersTable extends Table{
public function initialize(array $config)
{
parent::initialize($config);
$this->table('ab_login');
}
public function validationDefault(Validator $validator)
{
return $validator
->notEmpty('username', 'insert name')
->notEmpty('password', 'pw insert');
}
}
AppController.php
parent::initialize();
$this->loadComponent('RequestHandler');
$this->loadComponent('Flash');
$this->loadComponent('Auth', [
'authenticate' => [
'Form' => [
'fields' => ['username' => 'ab_mail', 'password' => 'ab_pass']
]
]
]);
UsersController.php
public function add()
{
$user = $this->Users->newEntity();
if ($this->request->is('post'))
{
$user = $this->Users->patchEntity($user, $this->request->data);
if ($this->Users->save($user))
{
$this->Flash->success(__('inserted!'));
return $this->redirect(['action' => 'add']);
}
$this->Flash->error(__('Error!'));
}
$this->set('user', $user);
}
Change the form elements in your view to:
<?= $this->Form->input('ab_mail') ?>
<?= $this->Form->input('ab_pass') ?>
Need to Change in AppController.php
parent::initialize();
$this->loadComponent('RequestHandler');
$this->loadComponent('Flash');
$this->loadComponent('Auth', [
'authenticate' => [
'Form' => [
'fields' => ['username' => 'username', 'password' => 'password'] // Password and Username fields are pre-define in cakephp.
]
]
]);
It will definitely work.
thanks :)

Cakephp 2.0 login is not working

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?

Auth Component not logging in users

I am unable to get the Auth component to login once passed credentials in a post method.
I am using CakePHP2.*
I am trying to write a web service.
Please below the code i have written to configure the Auth component in the AppController and below that the UserController for the User model
class AppController extends Controller {
public $components = array(
'DebugKit.Toolbar',
'Session',
'Auth' => array(
'loginRedirect' => array('controller' => 'user', 'action' => 'view'),
'logoutRedirect' => array('controller' => 'user', 'action' => 'home'),
'authenticate' => array('Form' => array('fields' => array('username'=>'username','password'=>'password'))),
'userScope'=> array('User.active_yn' => 1),
'userModel'=>'User',
'loginAction'=>array('controller' => 'user', 'action' => 'login'),
'autoRedirect'=>true,
'authError'=>'You dont have access to that area. Please login first.',
'loginError'=>'Username or password entered is incorrect. Please try again.',
'authorize' => array('Controller') // Added this line
)
);
public function isAuthorized($user) {
// Admin can access every action
if (isset($user['active_yn']) && $user['active_yn'] === 1) { //admin
return true;
}
// Default deny
return false;
}
public function beforeFilter() { }
}
class UserController extends AppController {
public $helpers = array('Html', 'Form', 'Session');
public $components = array('Session');
public $validate = array(
'email' => array('rule' => 'notEmpty')
);
public function index() {
$this->set('User', $this->User->find('all'));
}
public function view($id = null) {
if (!$id) {
throw new NotFoundException(__('Invalid User'));
}
$User = $this->User->findById($id);
if (!$User) {
throw new NotFoundException(__('Invalid User'));
}
$this->set('User', $User);
}
public function login() {
if ($this->request->is('post')) {
if ($this->Auth->login()) {
return $this->redirect($this->Auth->redirect());
}
$this->Session->setFlash(__('Invalid username or password, try again'));
}
$this->set('request', $this->request->data);
}
public function logout() {
return $this->redirect($this->Auth->logout());
}
public function beforeFilter() {
parent::beforeFilter();
$this->Auth->allow('view','login','logout');
}
}
Your controller names in the Auth configuration need to be in plural

User authentication in cakephp

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.

Categories