I have the following code in my CakePHP app home controller:
public function index ()
{
if($this->referer(array('controller' => 'users', 'action' => 'logout')))
{
$this->layout = 'splash';
$this->set('title_for_layout', 'Goodbye');
$this->render('loggedout');
}
else
{
if (!$this->Auth->user())
{
$this->layout = 'splash';
$this->set('title_for_layout', 'Welcome to CreatHive');
$this->render('splash');
}
else
{
$this->layout = 'home';
$this->set('title_for_layout', 'CreatHive');
$this->render('index');
}
}
}
Basically it says if the user came from the logout action show the loggedout view but if not then check if they are logged in and either show the splash page or home page.
However it ALWAYS shows the logged out view regardless of being logged in or not or even coming from the logout action (even flushing sessions/cookies etc doesn't work)
Any ideas what the problem is as the code looks fine to me :/
Thanks
Change:
if($this->referer(array('controller' => 'users', 'action' => 'logout')))
To:
if($this->referer() == Router::url(array('controller' => 'users', 'action' => 'logout')))
Related
I'm using CakePHP 3 and trying to change the default route after user is logged in. I want to set default route different depends on user's role_id.
I found a solution but it's only for CakePHP 2.
I can't use it in CakePHP 3, I can't use Session component in bootstrap.
So I tried this in my AppController
public $redirects = [
'admin' => ['controller' => 'Clients', 'action' => 'statistics'],
'user' => ['controller' => 'Clients', 'action' => 'index'],
];
public function initialize()
{
parent::initialize();
...
if ($this->Auth->user())
Configure::write('Route.default', $this->redirects[$this->Auth->user('role_id')]);
else
Configure::write('Route.default', ['controller' => 'Users', 'action' => 'login']);
Router::scope('/', function($routes) {
$routes->connect('/', Configure::read('Route.default'));
$routes->fallbacks('InflectedRoute');
});
}
My default route is
$routes->connect('/', \Cake\Core\Configure::read('Route.default'));
And I defined Route.default in bootstrap.php as
Configure::write('Route.default', ['controller' => 'Users', 'action' => 'login']);
But when I open the / page I still see the users/login page even if I have already logged in
So I added the redirection before Router::scope
if (
$this->Auth->user()
&& $this->request->params['controller'] == 'Users'
&& $this->request->params['action'] == 'login'
) {
$this->redirect(Configure::read('Route.default'));
}
Could anyone help me with that?
We can check user role from session data and make redirect according the role.
We can edit in the users controllers login function as follows
public function login()
{
if ($this->request->is('post')) {
$user = $this->Auth->identify();
if ($user) {
$this->Auth->setUser($user);
$loggedUser = $this->request->session()->read('Auth.User');
if($loggedUser['role'] == 'customer'){
return $this->redirect('/');
}else if($loggedUser['role'] == 'admin'){
return $this->redirect('/admin');
}else{
return $this->redirect($this->Auth->redirectUrl());
}
}
}
}
My cakephp version is 3.3.8
hey i found a solution!
create an file in App\Routing\Filter like that:
<?php
namespace App\Routing\Filter;
use Cake\Event\Event;
use Cake\Routing\DispatcherFilter;
class HFilter extends DispatcherFilter {
public function beforeDispatch(Event $event) {
$request = $event->data['request'];
if (isset($request->url) && $request->url == '') {
if ($request->session()->read('Auth.User')){
$request->params['controller'] = 'Users';
$request->params['action'] = 'index';
} else {
$request->params['controller'] = 'Pages';
$request->params['action'] = 'home';
}
}
}
}
?>
after add it into the bootstrap.php file without the Filter in the name like that
DispatcherFactory::add('H');
DispatcherFactory::add('Asset');
DispatcherFactory::add('Routing');
DispatcherFactory::add('ControllerFactory');
I have a problem with the redirection with cakephp 2.x.
When I execute the function below the redirect it works perfectly:
public function test() {
$this->redirect(array('controller' => 'pages','action' => 'index'));
}
But when I execute a trasaction with the database (add, modify and delete), the function redirect me to a blank page:
public function delete($id = null) {
$this->Post->id = $id;
if (!$this->Post->exists()) {
throw new NotFoundException(__('Invalid post'));
}
if ($this->Post->deleteAll(array('Post.id' => $id), false)) {
$this->Session->setFlash(__(" success."), 'flash', array('class' => 'alert alert-success'));
} else {
$this->Session->setFlash(__("error."), 'flash', array('class' => 'alert alert-danger'));
}
$this->redirect(array('controller' => 'pages','action' => 'index'));
}
Redirection does not work.
Thank you for helping me
Have you check with the debug 1 or 2 , if it shows some type of error.Moreover why are you using deleteAll for deleting single record, use delete method instead of deleteAll.
$this->Post->delete($id);
Please, check if there is anything printed before redirect acting, even if it is a space which can prevent redirect.
This is what I did to reproduce my problem:
Login (redirection at page foo)
Click and go to page bar
Logout
Login again
The redirected page is bar (it should be foo)
This is what I did:
AppController.php
$this->loadComponent('Auth', [
'authorize' => ['Controller'],
'loginRedirect' => [
'controller' => 'Dashboard',
'action' => 'index'
]
]);
UsersController.php
public function login($reset = null) {
$this->layout = 'login';
$this->set('reset', $reset);
if ($this->request->is('post')) {
$user = $this->Auth->identify();
if ($user) {
// IMPORTANT!
// Here I'm setting a different redirect url. The book says
// that $this->Auth->redirectUrl() will read the Auth.redirect
// session. I wanted my admin to login into a different page
if($session->read('Auth.User.role_id') === 3) {
$session->write('Auth.redirect', '/users/system_administrator_index');
}
$this->Auth->setUser($user);
return $this->redirect($this->Auth->redirectUrl());
} else {
$this->Flash->error('Oops', ['key' => 'auth']);
}
}
}
public function logout() {
return $this->redirect($this->Auth->logout());
}
I tried to use $session->destroy(); in order to clear everything related to my session but I noticed anything.
Each time I retry to login, the server redirect me to the last page I visited the last time I was connected.
I found a workaround. Instead of using return $this->redirect($this->Auth->redirectUrl());, I do a manual redirection.
public function login($reset = null) {
$this->layout = 'login';
$this->set('reset', $reset);
if ($this->request->is('post')) {
$user = $this->Auth->identify();
if ($user) {
$this->Auth->setUser($user);
if($user['role_id'] === 3){
return $this->redirect('/users/system_administrator_index');
}
return $this->redirect('/dashboard');
} else {
$this->Flash->error('Oops', ['key' => 'auth']);
}
}
}
I am having a small problem and I am not sure if its a routing issue or something is wrong with my login function. I have this ACL Plugin that I bought and integrated into my application. That said the login function is built into the plugin, so I edited my routing like so
Router::connect('/', array('plugin' => 'AuthAcl', 'controller' => 'users', 'action' => 'login', 'home'));
Router::connect('/pages/*', array('controller' => 'pages', 'action' => 'display'));
Now the login will work but when I login it appears like this localhost/app/app
Instead of localhost/app.
I do not see anything wrong with the routing.
My login function is as follows
public function login() {
$this->layout = 'admin_login';
$this->Session->delete('auth_user');
App::uses('Setting', 'AuthAcl.Model');
$Setting = new Setting();
$error = null;
$general = $Setting->find('first',array('conditions' => array('setting_key' => sha1('general'))));
if (!empty($general)){
$general = unserialize($general['Setting']['setting_value']);
}
$this->set('general',$general);
$user = $this->Auth->user();
if(!empty($user)){
$this->redirect($this->Auth->redirect());
}
if ($this->request->is('post')) {
if ($this->Auth->login()) {
if ((int)$this->request->data['User']['remember_me'] == 0){
$this->Cookie->delete('AutoLoginUser');
}else{
$this->Cookie->write('AutoLoginUser', $this->Auth->user(), true, '+2 weeks');
}
$this->redirect($this->Auth->redirect());
} else {
$error = __('Your username or password was incorrect.');
}
}
$this->set('error',$error);
Why am I not redirected correctly when I login.
Ok so here is what I did to fix the problem. I pointed to the controller where I wanted the users to be redirected. Thanks user221931!
$this->redirect($this->Auth->redirectUrl('auth_acl'));
I want to display a different navigation bar to my users based on if they're logged in or not. I have handled the registration and logging in stage, but having trouble checking if the users are logged in and displaying the correct navigation bar.
This is what I have in AppController.php:
public $components = array('Session', 'Auth' => array(
'loginRedirect' => array('controller' => 'users', 'action' => 'account'),
'logoutRedirect' => array('controller' => 'pages', 'action' => 'home')
));
public $loggedIn = false;
public function beforeFilter() {
$this->Auth->allow('home', 'register', 'login');
if ($this->Auth->user('id')) {
$this->set('loggedIn', true);
}
}
and then in my layout (not view):
<?php if ($loggedIn): ?>
logged in
<?php else: ?>
<li class="right">Register</li>
<li class="right">Login</li>
<?php endif; ?>
However, $loggedIn is always false. If do $this->set('loggedIn', $this->loggedIn); from within my individual controllers it works fine, but in an attempt to keep my code DRY I only want it in the controller that all my other controllers inherit from (AppController).
Is there an easy way to do this that i'm missing?
I know this has already been answered but I will post my findings anyway..
The way I solved this issue and made $loggedIn globally available was adding it to the AppController.php file in beforeFilter()
public function beforeFilter() {
$this->set('loggedIn', $this->Auth->loggedIn());
}
Try using:
if ($this->Auth->loggedIn()) {
For cakephp3
Controller wide:
public function beforeFilter(Event $event) {
$this->set('login_status', $this->Auth->user('id'));
}
In Template you can the check session object
$user = $this->request->session()->read('Auth.User');
Just put this code after login() action:
if($this->Auth->loggedIn()){
$this->redirect(array('action' => 'index'));
}