Authorizing administrators and regular users in a CakePHP application - php

I'm trying to write some simple functionality to distinguish between administrators and regular users in the CakePHP application I'm writing. I've changed my users table to have a field called admin which is either 0 or 1.
In AppController.php I've got a $components array set up like this:
public $components = array(
'Session',
'Auth' => array(
'authenticate' => array(
'Blowfish' => array(
'fields' => array('username' => 'email')
)
),
'loginRedirect' => array('controller' => 'pages', 'action' => 'home'),
'logoutRedirect' => array('controller' => 'pages', 'action' => 'home'),
'authorize' => array('Controller')
)
);
And also this method:
public function isAuthorized($user) {
// Check if admin
if(isset($this->params['admin']) && $this->Auth->user('admin') == 1) {
echo "admin";
return true;
}
// Default deny
return false;
}
When I load pages I get this error: (net::ERR_TOO_MANY_REDIRECTS): There were too many redirects.. For some reason the code above is causing infinite redirects and I can't work out why.
Also, I've set up a routing prefix for admin so administrators can access URLs like /admin/users/edit. When I go to that page, I don't get infinite redirects and admin is echo'd out like it should be.
I've read up on tutorials online and read the Cake docs but they all seem to end with the infinite redirects, how can I set this up so that I can distinguish administrators from regular users, and deny/allow access to certain actions for each role?

Sixthpoint has already pointed this out.
In absence of the Auth object, the Auth component is redirecting to the Pages Controller and I think you are missing
public function beforeFilter() {
parent::beforeFilter();
$this->Auth->allow("*"); // * or array("actions", "that", "are", "allowed")
}
So, this is essentially creating an infinite loop, First Auth object is missing, it gets directed to PagesController. The Auth component has been configured to authorize all Controllers, incl PagesController. And the loop reiterates redirecting again to PagesController.
Have you tried looking into ACL ? You can accomplish the same by use of Roles coupled with ACL.

Related

cakePHP Routers/ loginRedirect not working after logout

OK, another one for the cakephp ninjas today..
Here it is :
I have a login/logout system implemented..
I am using $components attr in the AppController, and using the Auth config key to set up loginRedirect and logoutRedirect.. The code looks like this :
public $components = array(
'DebugKit.Toolbar',
'Session',
'Auth' => array(
'loginRedirect' => array(
'controller' => 'posts',
'action' => 'index'
),
'logoutRedirect' => array(
'controller' => 'users',
'action' => 'login'
),
'authorize' => array('Controller')
)
);
The logout action looks like this :
public function logout() {
$this->Session->setFlash(__('You are now logged out.'));
return $this->redirect($this->Auth->logout());
}
Here's the deal.. Whenever I logout through the above logoutRedirect, and then log in, the user is not redirected to posts/index somehow.. and since I ve got DebugKit setup I tried to check whats going on an realised that within the cake Request Params, the controller is set to 'pages' and the action is 'display'.. This lead me to try and logout by manually entering the logout action URL in the address bar.. and guess what?! it works, and the user is redirected to the posts/index page..
So anyone knows how i can fix this issue im having? Or can point me towards a good source from which i can understand what and why is this happening exactly! thanks
Try this
$this->Auth->logout();
$this->redirect(some url);

Does Cakephp Auth can be use even in other controller?

Recently, I've been studying cake, I've seen the auth library which said to be will take care of the access control over your app, but, it seems like, you can't initialize or even use this auth library when you're not in the 'UsersController', i did not want that, what if it has some admin part wherein i want the URI to be admin/login, or just simply /login, i've been scratching my head over this one, please help.
Another question, why it seems like the functionality of the '$this->redirect' is not effective when i'm putting this one at any method that contains nothing but redirection, or even in the __construct()?
thanks guys, hoping someone could clearly explain to me those things.
you can use the Auth component inside any controller in the application. If you want it will only effect with the admin section then you can add condition in the beforeFilter funciton in you application AppController on Auth initialization like.
// for component initialization.
public $components = array(
'Auth' => array(
'authenticate' => array(
'userModel' => 'Customer', // you can also specify the differnt model instead of user
'Form' => array(
'fields' => array('username' => 'email')
)
)
)
}
and you can bind this on the admin routing like
function beforeFilter(){
// only works with admin routing.
if(isset($this->request->params['prefix']) && ($this->request->params['prefix'] == 'admin')){
$this->Auth->loginRedirect = array('admin' => true, 'controller' => 'pages', 'action' => 'index');
$this->Auth->logoutRedirect = array('controller' => 'users', 'action' => 'login', 'admin' => true);
$this->Auth->loginAction = array('admin' => true, 'controller' => 'customers', 'action' => 'login');
}
}
If you're using cake 2.3.x or later then make sure you have specified the redirect action in correct format like.
return $this->redirect('action_name'); // you can also specify the array of parameters.

CakePHP Auth loginRedirect error/always redirect to 'users/login' whereas i put different controller

CakePHP Auth loginRedirect error/always redirect to 'users/login' whereas i put different controller.
I mean, when i open the forbidden page(not allowed/require login)
$this->Auth->allow('index', 'profile', 'view', 'register');
it must redirect to "players/index". I put the loginRedirect to "players",
'loginRedirect' => array('controller' => 'Players', 'action' => 'index'),
but it doesn't work. It always redirect to "users/login" not "players/index" whereas i write "'loginRedirect' => array('controller' => 'Players', 'action' => 'index')".
this is my code:
class AppController extends Controller {
public $components = array(
'Session',
'Auth'=>array(
'loginRedirect' => array('controller' => 'Players', 'action' => 'index'),
'logoutRedirect' => array('controller' => 'Players', 'action' => 'index'),
'authError'=>"Anda tidak dapat mengakses halaman.",
'authorize'=>array('Controller')
)
);
public function isAuthorized($user) {
return true;
}
public function beforeFilter() {
$this->Auth->allow('index', 'profile', 'view', 'register');
$this->set('logged_in', $this->Auth->loggedIn());
$this->set('current_user', $this->Auth->user());
}}
My table's name : players
why the result's always redirect to "users/login" not "players/" or "players/index"?
please tell me why this happens and how i can solve it. Thank you!
I was stuck with the same issue for hours. Set the login action in the beforeFilter of your AppController as following:
$this->Auth->loginAction = array('controller'=>'yourcontollername', 'action'=>'login');
I followed the video youtube.com/watch?v=zvwQGZ1BxdM, see the first reply.
Have you tried to lowercase controller name ? Players => players
'loginRedirect' => array('controller' => 'players', 'action' => 'index'),
'logoutRedirect' => array('controller' => 'players', 'action' => 'index'),
very interesting, i come across a similar problem - after login redirect to the default home page.
I have tried all above methods, but none of them could solve the issue.
finally, i found out that login form did not build properly which action and controller were not set. therefore the html form pointed to '/', when posted.
However, the system still managed to login to right accounts, but none of redirect function worked in this situation.
It might be something you need to look into.
good luck.
The answer lies in the beforeFilter function in AppController.php. You must set allowances for the Auth object.
public function beforeFilter() {
// put in the functions that point to the views you want to be able to see
// without logging in. This works for all controllers so be careful for naming
// functions the same thing. (all index pages are viewable in this example)
$this->Auth->allow('index', 'thePageIWantToSee', 'userAdd', 'landingPage');
}
Simply use the login() function in your Users/Players Controller. With the if cause you can redirect to an diffrent page.
public function login()
{
if ($this->request->is('post')) {
$user = $this->Auth->identify();
if ($user) {
$this->Auth->setUser($user);
return $this->redirect('/account'); //$this->redirect($this->Auth->redirectUrl());
}
return $this->redirect( ['controller' =>'pages', 'action' => 'login-fail']);
}
}
Example used in CakePHP 3.2

cakePHP authentication problems

I am unable to wrap my head around how the Auth component works in cakePHP. I am using 2.1
My login works perfectly, and from my understanding I can set the default component in the appController, which I did as listed below.
// App controller:
public $components = array(
'Session',
'Auth' => array(
'loginAction' => array(
'controller' => 'users',
'action' => 'login',
),
'authError' => "Your username and password is incorrect, please try again.",
'authenticate' => array(
'Form' => array(
'scope' => array('User.user_status_id' => 1)
)
),
'redirect' => array("controller" => "users", "action" => "profile"),
'loginRedirect' => array("controller" => "users", "action" => "profile")
)
);
public function beforeFilter() {
$this->Auth->allow("home");
if($this->Auth->loggedIn() == true) {
$this->set("user_name",$this->Auth->user("first_name")." ".$this->Auth->user("last_name"));
$this->set("loggedIn",true);
if($this->Auth->user("user_type_id") == 5) {
$this->set("navigation","navigation_admin");
} else {
$this->set("navigation","navigation_loggedin");
}
} else {
$this->set("loggedIn",false);
$this->set("navigation","navigation_notloggedin");
}
}
home is located /app/view/home.ctp, however, I cannot access the page without being logged in. Next I have 2 different user levels, normal and administrator. I want to limit certain actions in controllers based if you're an admin or not.
In my UserController I have example:
public function beforeFilter() {
parent::beforeFilter();
$this->Auth->allow("login");
if($this->Auth->user("user_type_id") != 5) {
$this->Auth->allow("login","profile");
}
}
But irrespective of the user type, everyone can view the actions.
In my pages controller I also have the following:
public function beforeFilter() {
parent::beforeFilter();
$this->Auth->allow("*");
}
But I have to be logged in to view any pages.
I am convinced I am doing something wrong, but I cannot wrap my head around what, any help?
First, home is not an action on the controller, so $this->Auth->allow("home"); wouldn't have an effect. $this->Auth->allow("display"); would but would allow all pages to be seen (not sure if that's intended).
Secondly, you are using $this->Auth->allow("*"); after you call the parent's beforeFilter, which means that AppController::beforeFilter() would treat it as if the user wasn't logged in, since it doesn't know what you've allowed after the fact.

Changing the default login setup with CakePHP

I have something that I thought was a relatively common problem, but after researching the issue, it appears not to be as easy as thought.
I have a CakePHP application (using version 1.2.7) and I am trying to change the standard login procedure using the Auth Component. I would like to use a persistent login screen ( like this Jquery plugin : http://web-kreation.com/demos/Sliding_login_panel_jquery/ ) which my users would use to login.
In Cake terminology, I would like to be able to login to the Auth component from the /pages/home screen but Cakephp keeps redirecting to the /users/login.
In My App Controller :
function beforeFilter()
{
...
$this->Auth->loginAction = array( 'controller' => 'users', 'action' => 'login' );
$this->Auth->loginRedirect = array( 'controller' => 'pages', 'action' => 'home' );
$this->Auth->logoutRedirect = array( 'controller' => 'pages', 'action' => 'home' );
$this->Auth->autoRedirect = false;
...
}
If I change the loginAction to /pages/home. the login does not work, in fact it does not even post to the /users/login method. Not exactly sure what has happened.
My question is this :
How do I make a login form located at www.EXAMPLE.com/ which will return to the same location on successful and unsuccessful login?
I would prefer not to have it redirect to /users/login or have that show up in the URL at all.
To change default login URL set by 'Auth'
make Changes in lib/cake/Controller/component/AuthComponent.php
public $loginAction = array(
'controller' => 'users', //Change here
'action' => 'login',
'plugin' => null
);
If you set $this->Auth->autoRedirect to false then you must redirect manually in your login() method. Take a look at this also.
To change where the form submits just changed the submit url in your form, it's that simple.
$form->create('User', array('url'=>array('controller'=>'users','action'=>'login')))
Then you can load your page, and check the action attribute, and you should see your /users/login :)

Categories