Checking if user is logged in using CakePHP - php

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'));
}

Related

CakePHP 3: Different login redirection depending on user roles

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');

CakePHP 2.x first login with hash password no users in DB

I have already check and when I create users and passwords and then I try to login and is successful, however if for example I install on other device my project and set up my DB I enter to my system how can I access for first time if I dont have users created?
1) I tried to create user and password on my database but it cant recognize the password due to hashing methods.
How can i access for the first time and then create users as normal?
My login access controller:
public function login() {
//if already logged-in, redirect
if($this->Session->check('Auth.User')){
$this->redirect(array('action' => 'index'));
}
// if we get the post information, try to authenticate
if ($this->request->is('post')) {
if ($this->Auth->login()) {
$this->Session->setFlash(__('Bienvenido, '. $this->Auth->user('username')));
$this->redirect($this->Auth->redirectUrl());
} else {
$this->Session->setFlash(__('Usuario o password invalidos'));
}
}
$this->layout = 'login';
}
appcontroller:
class AppController extends Controller {
//public $components = array('DebugKit.Toolbar');
public $components = array(
//'DebugKit.Toolbar',
'Session',
'Auth' => array(
'authorize' => 'Controller',
'actionPath' => 'controllers/',
'loginRedirect' => array('controller' => 'users', 'action' => 'index'),
'logoutRedirect' => array('controller' => 'users', 'action' => 'login'),
'authError' => 'You must be logged in to view this page.',
'loginError' => 'Invalid Username or Password entered, please try again.'
),
);
// only allow the login controllers only
public function beforeFilter() {
$this->Auth->allow('login','view','index','logout','getData');
}
public function isAuthorized($user) {
// Here is where we should verify the role and give access based on role
if (isset($user['role']) && $user['role'] === 'adm') {
return true;
}
if (in_array($this->action, array('add','getData','getDataArticulos','addDetFac','descargar','getNit'))) {
if (isset($user['role']) && $user['role'] === 'vend')
return true;
else
return $this->Session->setFlash(__('Acceso denegado.'), 'error');
}
return $this->Session->setFlash(__('Acceso denegado.'), 'error');
}
}
At first allow add method.
public function beforeFilter() {
$this->Auth->allow('login','view','index','logout','getData','add');
}
Then create a user, write in your browser URL your_project_path/users/add
After add 1st user remove add from Auth allow.

App Name Showing Twice - Routing Issue or Login Function Issue?

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'));

CakePHP Check referer

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')))

CakePHP Validation Question with Plugin

In my CakePHP application, I have setup the PersistantValidation plugin to validate my forms on the model level thanks to a kind previous suggestion. The plugin essentially makes it so that you can use model validation on a partial without having it redirect to the underlying page (ie. the register.ctp view or the login.ctp view, for example).
The validation works great for the login form, but it's not working properly on the user registration form for some reason.
The controller looks like this:
function register() {
if(!empty($this->data)) {
$name = $this->data['User']['name'];
$email = $this->data['User']['email'];
$password = $this->Password->generatePassword();
$this->data['User']['password'] = $this->Auth->password($password);
$this->User->create();
if($this->User->save($this->data)) {
$this->Session->setFlash(__('Your account has been created!', true));
$this->redirect(array('controller' => 'users', 'action' => 'offers'));
} else {
$this->redirect($this->referer());
}
}
}
The PresistentValidation component is also properly setup and included, since it works just fine in the login() function in the same controller. When I run this code, nothing happens. There is no redirect away from the partial, which is good, but the errors don't show up. Also, the errors do show up going to the register.ctp view, which means it isn't a problem with the validations themselves.
Does anyone have any ideas?
function register() {
if(!empty($this->data)) {
$this->data['User']['password'] = $this->Auth->password($password);
if($this->User->save($this->data)) {
$this->Session->setFlash(__('Your account has been created!', true));
$this->redirect(array('controller' => 'users', 'action' => 'offers'));
} else {
$this->redirect($this->referer());
}
}
}

Categories