$this->Auth->User(); is null - cakephp

I am new in cake php.
I am using cakephp 3.6.2 in linux ubuntu.
I use cakephp auth component.
While i give correct credentials it redirect back to the login page otherwise says error message "invalid username and password".
I debug and check details while i give correct credentials. It Set " $this->Auth->setUser($user);" correctly.
But After redirect " return $this->redirect($this->Auth->redirectUrl());"
$this->Auth->User() is Null and it redirects back to login page.
My Code
AppController.php
public function initialize(){
$this->loadComponent('RequestHandler');
$this->loadComponent('Flash');
$this->loadComponent('Auth', [
'authenticate' => [
'Form' => [
'fields' => ['username' => 'email', 'password' => 'password']
]
],
'loginAction' => ['controller' => 'Users', 'action' => 'login']
]);}
UserCOntroller.php
public function login()
{
if ($this->request->is('post')) {
$user = $this->Auth->identify();
if ($user) {
$this->Auth->setUser($user);
debug($this->Auth->User()); //contain user details correctly
debug($this->redirect($this->Auth->redirectUrl())); // //contain userdetails correctly
return $this->redirect($this->Auth->redirectUrl());
}
$this->Flash->error(__('Invalid username or password, try again'));
}
}
public function logout()
{
return $this->redirect($this->Auth->logout());
}
User.php
protected function _setPassword($password)
{
if (strlen($password) > 0) {
return (new DefaultPasswordHasher)->hash($password);
}
}
I print phpinfo() session is enabled. other projects under the "var/www/html" working properly. But inside this project only session not working.

Related

CakePHP: Validate login form

I need to validate a login form but I get error on form: Notice (8): Undefined variable: user [APP/Template\Users\login.ctp, line 5]
What could be?
login.ctp:
<br>
<div class="index large-4 medium-5 large-offset-4 medium-offset-4 columns">
<div class="panel">
<h2 class="text-center">Login</h2>
<?= $this->Form->create($user); ?>
<?= $this->Form->input('email' ,array('id' =>'email')); ?>
<?= $this->Form->input('password', array('type' => 'password'), array('id' => 'password')); ?>
<?= $this->Form->submit('Login', array('class' => 'button')); ?>
<?= $this->Form->end(); ?>
</div>
</div>
login function on UsersController.php:
public function login()
{
if($this->request->is('post'))
{
$user = $this->Auth->identify();
if($user)
{
$this->Auth->setUser($user);
return $this->redirect(['controller' => 'comentario']);
}
// Erro no Login
$this->Flash->error('Erro de autenticação');
}
}
UPDATE login function located in UsersController.php
public function login()
{
$user = $this->Auth->identify();
if($this->request->is('post'))
{
if($user)
{
$this->Auth->setUser($user);
return $this->redirect(['controller' => 'comentario']);
}
// Erro no Login
$this->Flash->error('Erro de autenticação');
}
}
Auth Configuration:
public function initialize()
{
parent::initialize();
$this->loadComponent('RequestHandler');
$this->loadComponent('Flash');
$this->loadComponent('Auth', [
'authenticate' => [
'Form' => [
'fields' => [
'username' => 'email',
'password' => 'password'
]
]
],
'loginAction' => [
'controller' => 'Users',
'action' => 'login'
]
]);
}
$user is a reference to a variable and is undefined in your view. If you are creating a form for users, then the standard convention would be :
<?= $this->Form->create('User'); ?>
which will implicitly post to the same action that rendered the view.
Update:
You are calling auth for the $user before you check if the form is posted, so it will throw an undefined error before the form is submitted, when the view is rendered normally. I'm not overly familiar with 3.x, so you may or may not need to explicitly pass $this->request->data to the auth function. The method should be something like the following:
public function login()
{
if($this->request->is('post'))
{
$user = $this->Auth->identify();
if($user)
{
$this->Auth->setUser($user);
return $this->redirect(['controller' => 'comentario']);
}
// Erro no Login
$this->Flash->error('Erro de autenticação');
}
else{
//do something else here
}
}
From the 3.x documentation
Identifying Users and Logging Them In AuthComponent::identify() You
need to manually call $this->Auth->identify() to identify the user
using credentials provided in request. Then use $this->Auth->setUser()
to log the user in, i.e., save user info to session.
When authenticating users, attached authentication objects are checked
in the order they are attached. Once one of the objects can identify
the user, no other objects are checked. A sample login function for
working with a login form could look like:
public function login()
{
if ($this->request->is('post')) {
$user = $this->Auth->identify();
if ($user) {
$this->Auth->setUser($user);
return $this->redirect($this->Auth->redirectUrl());
} else {
$this->Flash->error(__('Username or password is incorrect'), [
'key' => 'auth'
]);
}
}
}

CakePHP 3 - Login Error - Call to a member function identify on boolean

Hello I'm using CakePHP 3 to simple setup a site which some pages of it need user to login first.
It was fine when I put the loadComponent('Auth', blablabla) code in initialize() of AppController.php.
src\Controller\AdminController.php
...
public function login() {
if ($this->request->is('post')) {
$admin = $this->Auth->identify();
if ($admin) {
$this->Auth->setUser($admin);
return $this->redirect($this->Auth->redirectUrl());
}
$this->Flash->error('Your username or password is incorrect.');
}
}
...
src\Controller\AppController.php
...
public function initialize() {
parent::initialize();
$this->loadComponent('RequestHandler');
$this->loadComponent('Flash');
$this->loadComponent('Auth', [
'Authenticate' => [
'Form' => [
'userModel' => 'Admin',
'Fields' => [
'username' => 'email',
'password' => 'password'
]
]
],
'loginAction' => [
'controller' => 'Admin',
'action' => 'login',
]
]);
$this->Auth->allow(['display']);
}
...
At this point, I needed to login in order to view all other pages of the site.
But I tried to put this same authentication setup in another controller called JustController, and after I logged in, a fetal error stated
Call to a member function identify() on boolean
has been shown.
It should be possible to setup authentication in other controllers so that the site can have more than 1 set of login system instead of covering whole site by setting up in AppController, doesn't it?
Thank you.

Auth Login not working in Cakephp

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.

CakePHP 1.3: getting authError message on successful login

I'm trying to implement a login feature where a user can use his username or email address. I've worked out the login with both, but when the user logs in successfully with his email address, the authError still flashes (user is logged in). I've put a comment "HERE" down in the login action, and I'm not sure what happens after that with the redirect.
Here are the relevant bits of my code:
App Controoler:
public $components = array(
'Auth' => array(
'authorize' => 'controller',
'loginRedirect' => array(
'controller' => 'users',
'action' => 'welcome_page'
),
'loginError' => 'Invalid user name/password',
'authError' => 'You don\'t have permission'
),
'Session',
);
User Controller:
public function beforeFilter() {
parent::beforeFilter();
$this->Auth->allow('add');
}
public function login() {
// At this point, the Auth Component is unable to log in user, so check with email.
if (!empty($this->data) &&
!empty($this->Auth->data['User']['username']) &&
!empty($this->Auth->data['User']['password'])) {
// Look for user with email address using the entered username
$user = $this->User->find('first', array(
'conditions' => array(
'User.email' => $this->Auth->data['User']['username'],
'User.password' => $this->Auth->data['User']['password']
),
'recursive' => -1
));
// Check if a matching user is found and that if login was succesfull
if (!empty($user) && $this->Auth->login($user)) {
if ($this->Auth->autoRedirect) {
// NOTE: user trying to log in with email reaches HERE
$this->redirect($this->Auth->redirect()); // this is the default authentication redirect defined in App Controller
}
} else {
$this->Session->setFlash($this->Auth->loginError, $this->Auth->flashElement, array(), 'auth');
}
}
}
I edited your original post to delete the messages from the session variables.
<?php
$this->Session->delete('Message.flash');
$this->Session->delete('Message.auth');
?>
Hope this helps!
-Andrew

CakePHP auth redirection not working

In order to learn cakephp i am trying to reproduce the simple authentication example of the cookbook ; http://book.cakephp.org/2.0/en/tutorials-and-examples/blog-auth-example/auth.html
My problem is that when i try to access a non authorized page i just got a blank page with the cake installation notice warning : please change the valie of secruity salt and cipherSeed
here is my code for the appcontroller
class AppController extends Controller {
public $components = array(
'Session',
'Auth' => array(
'loginRedirect' => array('controller' => 'posts', 'action' => 'index'),
'logoutRedirect' => array('controller' => 'pages', 'action' => 'display', 'home')
),
'RequestHandler'
);
public function beforeFilter() {
$this->Auth->allow('index', 'view', 'login');
$this->Auth->authorize = 'actions';
$this->Auth->autoRedirect = true;
}
}
and here is my code for the usercontroller
public function beforeFilter() {
parent::beforeFilter();
$this->Auth->allow('add');
}
public function login() {
echo "i am called";
if ($this->request->is('post')) {
if ($this->Auth->login()) {
$this->redirect($this->Auth->redirect());
} else {
$this->Session->setFlash(__('Invalid username or password, try again'));
}
}
}
public function logout() {
$this->redirect($this->Auth->logout());
}
s there any configuration that i don't do or any misunderstanding problem about auth implementation ?
i am using easyPhp for windows as my webserver , but i also have the issue on a linux installation with php5 , mysql and apache 2
Cipher and salt are found in app/Config/core.php, you must change them

Resources