Does Cakephp Auth can be use even in other controller? - php

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.

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

Authorizing administrators and regular users in a CakePHP application

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.

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

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

CakePHP Router::connect() aliases?

Is it possible in CakePHP to have URL aliases in routes.php? Or by what other means can achieve something equivalent:
Lets assume I have some paginated views. Among the possible orderings there are particular ones I want to bind to a simple URL. E.g.:
http://example.com/headlines => http://example.com/posts/listView/page:1/sort:Post.created/direction:desc
http://example.com/hottopics => http://example.com/posts/listView/page:1/sort:Post.view_count/direction:desc etc.
How do I add parameters to a Router::connect()? Pseudo code:
Router::connect('/'.__('headlines',true),
array(
'controller' => 'posts',
'action' => 'listView'
'params' => 'page:1/sort:Post.created/direction:desc',
)
);
Note that the Router "translates" a URL into Controllers, Actions and Params, it doesn't "forward" URLs to other URLs. As such, write it like this:
Router::connect('/headlines',
array(
'controller' => 'posts',
'action' => 'listView'
'page' => 1,
'sort' => 'Post.created',
'direction' => 'desc'
)
);
I don't think '/'.__('headlines', true) would work, since the app is not sufficiently set up at this point to translate anything, so you'd only always get the word in your default language back. Also, you couldn't switch the language anymore after this point, the first use of __() locks the language.
You would need to connect all URLs explictly. To save you some typing, you could do this:
$headlines = array('en' => 'headlines', 'de' => 'schlagzeilen', ...);
foreach ($headlines as $lang => $headline) {
Router::connect("/$headline", array('controller' => ..., 'lang' => $lang));
}
That will create a $this->param['named']['lang'] variable, which you should use in the URL anyway.
Yes, it is possible... Bootstrap.php loads before routes so if you set there something like:
session_start();
if(isset($_SESSION['lng'])){
Configure::write('Config.language', $_SESSION['lng']);
}
...and in your app controller in beforeFilter:
$language = 'xy';
Configure::write('Config.language', $language);
$_SESSION['lng'] = $language;
So initial page render you prompt for language, redirect to xy.site.com or www.site.com/xy whatever you prefer. Now second render will change $language and on page links and set $_SESSION['lang']...
All router links like:
Router::connect(__('/:gender/search/:looking_for/*'), array('controller' => 'users', 'action' => 'search'));
will become:
Router::connect(__('/:gender/trazi/:looking_for/*'), array('controller' => 'users', 'action' => 'search'));
or:
Router::connect(__('/:gender/suche/:looking_for/*'), array('controller' => 'users', 'action' => 'search'));
100% tested, works in CakePHP 2.2. Also further improvement is possible if you put subdomain/language url parser in the bootstrap itself...

Categories