CakePHP redirect to current page after login - cakephp

I am triying to redirect to the current page after sucessfull login, but it seems that I am facing too many redirects...
My UsersController is working under a prefix 'admin' and I think it's the root cause but I didn't manage to get this work.
Router::prefix('Admin', function(RouteBuilder $builder)
{
$builder->connect('/', ['controller' => 'Pages', 'action' => 'index']);
$builder->fallbacks(DashedRoute::class);
});
My function initialize in appController looks like this
public function initialize()
{
parent::initialize();
$this->loadComponent('RequestHandler');
$this->loadComponent('Flash');
$this->loadComponent('Auth', [
'loginAction' => [
'controller' => 'Users',
'action' => 'login',
'prefix' => 'admin'
],
'unauthorizedRedirect' => $this->referer(),
'logoutRedirect' => [
'controller' => 'Users',
'action' => 'login',
'prefix' => 'admin'
]
]);
}
and here if action login
public function login()
{
$this->request->allowMethod(['get', 'post']);
$result = $this->Authentication->getResult();
if ($result->isValid())
{
return $this->redirect($this->Auth->redirectUrl());
}
// display error if user submitted and authentication failed
if ($this->getRequest()->is("post") && !$result->isValid())
{
$this->Flash->error('Email ou mot de passe incorrect.');
}
$this->viewBuilder()->setLayout('AdminTheme.login');
}
Thanks for your help.

I think the problem is at the first if block:
if ($result->isValid())
{
//This is the problem
return $this->redirect($this->Auth->redirectUrl());
}
I believe you mean to pass $this->request->referer() to the redirect method instead of $this->Auth->redirectUrl(). The referer is the previous url.

I used the function getLoginRedirect(), which seems to be working.
if ($result->isValid())
{
$target = $this->Authentication->getLoginRedirect() ?? '/';
return $this->redirect($target);
}

Related

Login redirecting in cakePHP 3.4

I'm trying to redirect to current page after logged in, using cakephp 3.4 but I'm getting like this
localhost page isn't working, locahost page redirecting you too many
times. Try clearing your cookies
for 2 sec after that it's redirecting to home page. Please help me out here.
Here my code
In appController.php
public function initialize()
{
parent::initialize();
$this->loadComponent('RequestHandler');
$this->loadComponent('Flash');
$this->loadComponent('Auth', [
'authorize' => ['Controller'],
'authenticate' => [
'Form' => [
'fields' => [
'username' => 'email',
'password' => 'password'
],
'scope' => ['userStatus' => '1']
]
],
'loginAction' => [
'controller' => 'Users',
'action' => 'login'
],
'unauthorizedRedirect' => $this->referer(),
'logoutRedirect' => [
'controller' => 'Users',
'action' => 'login'
]
]);
}
In loginController.php
function login{
if ( $this->request->is( 'post' ) ) {
if ( $this->Auth->login() )
{
$this->redirect($this->referer());
}
else {
$this->Flash->error(__('Your username or password is incorrect.'));
}
}
}
Looks like you got some redirect loop here. You should use AuthComponent::redirectUrl().
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'));
}
}
}
See the Redirecting Users After Login in the Documentation.
After logging a user in, you’ll generally want to redirect them back
to where they came from. Pass a URL in to set the destination a user
should be redirected to after logging in.
If no parameter is passed, the returned URL will use the following
rules:
Returns the normalized URL from the redirect query string value if it
is present and for the same domain the current app is running on.
Before 3.4.0, the Auth.redirect session value was used.
If there is no query string/session value and there is a config loginRedirect, the loginRedirect value is returned.
If there is no redirect value and no loginRedirect, / is returned.
Use $this->Auth->redirectUrl() instead of $this->referer().
After logging a user in, you’ll generally want to redirect them back to where they came from. Pass a URL in to set the destination a user should be redirected to after logging in.
Returns the normalized URL from the redirect query string value if it is present and for the same domain the current app is running on. Before 3.4.0, the Auth.redirect session value was used.
If there is no query string/session value and there is a config loginRedirect, the loginRedirect value is returned.
If there is no redirect value and no loginRedirect, / is returned.
Add to your AuthComponent configuration options:
loginRedirect
The URL (defined as a string or array) to the controller action users
should be redirected to after logging in. This value will be ignored
if the user has an Auth.redirect value in their session.
Your code should be like that:
In appController.php
public function initialize()
{
parent::initialize();
$this->loadComponent('RequestHandler');
$this->loadComponent('Flash');
$this->loadComponent('Auth', [
'authorize' => ['Controller'],
'authenticate' => [
'Form' => [
'fields' => [
'username' => 'email',
'password' => 'password'
],
'scope' => ['userStatus' => '1']
]
],
'loginAction' => [
'controller' => 'Users',
'action' => 'login'
],
'unauthorizedRedirect' => $this->referer(),
'logoutRedirect' => [
'controller' => 'Users',
'action' => 'login'
],
'loginRedirect' => [
'controller' => 'Pages',
'action' => 'display'
]
]);
}
In loginController.php
function login{
if ( $this->request->is( 'post' ) ) {
if ( $this->Auth->login() )
{
$this->redirect($this->Auth->redirectUrl());
}
else {
$this->Flash->error(__('Your username or password is incorrect.'));
}
}
}
See also Redirecting Users After Login

cake php Auth login not working online but working locally

i am using cakephp Auth login it is not working online but on localhost it is working fine.
class AppController extends Controller {
public $components=array(
'Auth'=>array(
'authenticate'=>array(
'Form'=>array(
'userModel'=>'User',
'fields'=>array(
'username'=>'uid',
'password'=>'password',
),
)
),
'loginAction' => array('controller' => 'users', 'action' => 'login'),
'loginRedirect' => array('controller' => 'users', 'action' => 'dashboard'),
'logoutRedirect' => array('controller' => 'users', 'action' => 'login'),
'authError' => 'You don\'t have access here.',
),
'Session'
);
this login() method in UsersController this is working fine at localhost what changes should be done when we are uploading any file on server in cakephp
public function login(){
$this->layout='login';
if($this->request->is('Post'))
{
if($this->Auth->login())
{
$user=$this->Auth->user();
if($user['status']!=0 || $user['role']=='1')
{
if($user['role'])
{
$role="Admin";
$this->Session->write('admin',$user['uid']);
}
else
{
$role="User";
$this->Session->write('user',$user['uid']);
}
$this->Session->write('rolename',$role);
$this->Session->write('uid',$user['uid']);
$log['Log']['loginType']=$this->request->data['User']['loginType'];
$log['Log']['userId']=$user['id'];
$log['Log']['latitude']='0';//$data['User']['latitude'];
$log['Log']['longitude']='0';//$data['User']['longitude'];
$this->Log->save($log);
$this->Flash->set(_('Sucessfully login'));
$this->redirect(array('controller'=>'users','action'=>'dashboard'));
}
else
{
$this->Flash->set('You have no access to login...');
}
}
else
$this->Flash->set('Invalid Credentials');
}
}

Auth logout is not working in CakePHP 2.x

When I login from one user account session is set.Then opening the next tab on same browser and enter login url it takes me to the login page.But actually it should redirect to the "dashboard" page(in my case). It can't redirect to loginRedirect(dashboard) page as mentioned in my Auth.
When i logout, as per my code session,cookie and cache are deleted. but it's not redirect to logoutRedirect page.
My code :
App controller
public $components = array(
'Session', 'RequestHandler', 'Email', 'Cookie',
'Auth' => array(
'authenticate' => array(
'Form' => array(
'fields' => array(
'username' => 'email',
'password' => 'password')
)
),
'loginRedirect' => array(
'controller' => 'users',
'action' => 'login'
),
'logoutRedirect' => array(
'controller' => 'users',
'action' => 'login'
)
)
);
User controller
login action :
public function login() {
$this->layout = 'admin';
if ($this->Session->check('Auth.User')) {
$this->redirect(array('controller' => 'users', 'action' => 'dashboard'));
}
if (isset($this->data['User'])) {
if (!empty($this->data['User']['email']) && !empty($this->data['User']['password'])) {
if ($this->Auth->login()) {
$this->redirect(array('controller' => 'users', 'action' => 'dashboard'));
} else {
$this->set('error', "Email or Password mismatch.");
}
}
} else {
if ($this->Auth->loggedIn()) {
$this->redirect(array('controller' => 'users', 'action' => 'dashboard'));
}
}
}
logout action :
public function logout() {
header('pragma: no-cache');
header('Cache-Control: no-cache, must-revalidate');
$this->response->disableCache();
$this->Session->delete('Auth.User');
$this->Session->delete('User');
$this->Session->destroy();
$this->Cookie->destroy();
return $this->redirect($this->Auth->logout());
}
This code is working fine in "local server" but not working in production server.
Your redirect statements should have return in front of them so that code execution will stop there. For example:
return $this->redirect(array('controller' => 'users', 'action' => 'dashboard'));

Weird exception with authentication in cakephp

I want to redirect http://localhost/amrajegeachi14/admins/deshboard after successful login and http://localhost/amrajegeachi14/admins/login if login failed. My code inside adminsController:
class AdminsController extends AppController {
var $layout = 'admin';
public function beforeFilter() {
parent::beforeFilter();
// $this->Auth->allow('login');
}
function isAuthorized($user) {
if (isset($user['Admin'])) {
if ($user['Admin']['status'] == 'active') {
return TRUE;
}
}
return FALSE;
}
function login() {
$this->loadModel('Admin');
$this->layout = "admin-login";
// if already logged in check this step
if ($this->Session->check('Auth.User')) {
return $this->redirect(
array('controller' => 'admins', 'action' => 'deshboard'));
}
// after submit login form check this step
if ($this->request->is('post')) {
$password = Security::hash($this->request->data['Admin']['password'], NULL, true);
$admin = $this->Admin->find('first', array(
'conditions' => array('email' => $this->request->data['Admin']['email'], 'password' => $password)
));
if ($this->isAuthorized($admin)) {
$this->Auth->login($this->request->data['Admin']);
return $this->redirect('/admins/deshboard');
} else {
$this->Session->setFlash('Invalid username/password combination OR you are blocked, try again');
return $this->redirect('/admins/login');
;
}
}
}
public function logout() {
// $user = $this->Auth->user();
// $this->Session->destroy();
$this->Session->setFlash('you have successfully logged out');
$this->Auth->logout();
return $this->redirect(array('controller' => 'admins', 'action' => 'login'));
}
function deshboard() {
}
}
Code Inside AppController.php
class AppController extends Controller {
public $components = array(
'Session',
'Auth' => array(
'authenticate' => array(
'Form' => array(
'fields' => array(
'username' => 'email', //Default is 'username' in the userModel
'password' => 'password' //Default is 'password' in the userModel
),
'userModel' => 'Agent'
)
),
'loginAction' => array(
'controller' => 'admins',
'action' => 'login'
),
'loginRedirect' => array('controller' => 'admins', 'action' => 'deshboard'),
'logoutRedirect' => array('controller' => 'admins', 'action' => 'login'),
'authError' => "You can't acces that page",
'authorize' => 'Controller'
)
);
public function beforeFilter() {
//parent::beforeFilter();
$this->Auth->allow('index');
}
}
When I try to login it redirects to http://localhost/amrajegeachi14/admins/login if login failed. its fine. but when I provide valid email and password and login successful it redirects to http://localhost/amrajegeachi14/amrajegeachi14/admins/deshboard. its wrong it should be http://localhost/amrajegeachi14/admins/deshboard
I am surprised when I changed the isAuthorized() function as follows:
function isAuthorized($user) {
if (isset($user['Admin'])) {
if ($user['Admin']['status'] == 'active') {
return TRUE;
}
}
return true;
}
it redirects http://localhost/amrajegeachi14/admins/deshboard with successful login. But in this case login will be okay with incorrect username and password.
This problem kills my sleep, makes me crazy and I am so much disappointed. I searched google for two days but no appropriate solution. Please help me.
The problem is that your user is never logged in because you did not follow the CakePHP way of authenticating an user. Here is your code with comments:
// This should not be here... This should either be in a authentication
// component, or maybe not present at all if you use default authentication.
$password = Security::hash($this->request->data['Admin']['password'], NULL, true);
$admin = $this->Admin->find('first', array(
'conditions' => array(
'email' => $this->request->data['Admin']['email'],
'password' => $password
)
));
// This should not be called manually.
if ($this->isAuthorized($admin)) {
// Your problem is probably here, since you never check the return
// value of the login function.
$this->Auth->login($this->request->data['Admin']);
// You should use $this->Auth->redirectUrl()
return $this->redirect('/admins/deshboard');
} else {
$this->Session->setFlash('Invalid username/password combination OR you are blocked, try again');
return $this->redirect('/admins/login');
}
I am pretty sure that the $this->Auth->login () call always return false. The login method will try to authenticate an user, using the authentication component you specified (or the default one).
Your passwords are probably hashed in your DB, but you did not tell the component how to hash them, so it cannot authenticate your users...

login not redirecting in cakephp

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'));
}
}
}
this is my login script and
public $components = array('Acl', 'Session',
'Auth' => array('authorize' => array('Controller'),
'loginRedirect' => array('controller' => 'users', 'action' => 'dashboard'),
'logoutRedirect' => array('controller' => 'users', 'action' => 'login'),
'authenticate' => array('Form' => array('fields' => array('username' => 'email')))
)
);
this is auth compnents in appcontroller.php
it is logging in using email and password but it is not redirecting to user/dashboard
but instead of that if i put any external urls it redirects perfectly
eg: 'loginRedirect' => 'http://google.com',
it redirects to google
i am totally lost.kindly help
Make sure you are allowed to view the dashboard page using: AuthComponent::allow():
Add this method to your controller:
public function beforeFilter() {
$this->Auth->allow('dashboard');
}
Make sure there is a route set for the dashboard page

Resources