Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CakePHP Auth how to allow specific controller and actions

I have a "Posts" and a "Users" controller. I use the Auth Component and I want that all users can visit "Post.index" but only logged in users can visit "User.index".

In my app_controller.php I have this

$this->Auth->allow('signup', 'confirm', 'index');

but with that all users can visit post.index and user.index. How can I specify a Controller in the allow-method?

This didn't work for me:

$this->Auth->allow('signup', 'confirm', 'Post.index');

update I removed 'index' from the app_controller.php and instead set it in the beforeFilter method in the post controller:

function beforeFilter() 
{
    parent::beforeFilter();
    $this->Auth->allow('index');
}

I also set a variable "loggedIn" in app_controller, without calling "parent::beforeFilter();" I got an "undefined variable" notice.

thx sibidiba

like image 845
Christian Strang Avatar asked May 08 '10 10:05

Christian Strang


4 Answers

The period will not work. You could try '/' instead. If that fails as well, you should set $this->Auth->allow('index') in PostController's and UserController's ::beforeFilter() individually. Don't forget to call parent::beforeFilter().

like image 169
sibidiba Avatar answered Nov 17 '22 04:11

sibidiba


Depends on the version you're working on. If it's cakephp 2.x, put this code into the controller that has the action you want give access without login. As your question, you should put this code to Posts controller:

function beforeFilter(){
     $this->Auth->allow(array('index','another action'));}

allow(array('acction you want to allow')) instead allow('acction you want to allow')

like image 2
hoai pham thanh Avatar answered Nov 17 '22 06:11

hoai pham thanh


I am using CakePHP 2.x. The slash trick doesn't work.

If you want to allow user access "myController.myAction" without login, you should add beforeFilter() into myController.php instead of AppController.php

Here is the code to add into myController.php:

function beforeFilter() {
    parent::beforeFilter();
    $this->Auth->allow('myAction');
}
like image 1
crab Avatar answered Nov 17 '22 04:11

crab


For Cakephp 2.x, there are several methods (depending on the cakephp version).

From the docs (http://book.cakephp.org/2.0/en/core-libraries/components/authentication.html):

// Allow all actions. CakePHP 2.0
$this->Auth->allow('*');

// Allow all actions. CakePHP 2.1
$this->Auth->allow();

// Allow only the view and index actions.
$this->Auth->allow('view', 'index');

// Allow only the view and index actions.
$this->Auth->allow(array('view', 'index'));
like image 1
Britc Avatar answered Nov 17 '22 04:11

Britc