允许静态页面通过cakePHP

时间:2016-03-11 06:22:16

标签: php authentication cakephp cakephp-3.x

我想要添加到现有cakePHP项目的静态页面。我设法通过在PagesController

上使用此代码来绕过Auth
public $allowedPages = array('main',); 


public function beforeFilter() {
$this->Auth->allow('display');
}
public function display()
{
    $path = func_get_args();

    $count = count($path);
    if (!$count) {
        return $this->redirect('/');
    }
    $page = $subpage = null;

    if (!empty($path[0])) {
        $page = $path[0];
    }
    if (!empty($path[1])) {
        $subpage = $path[1];
    }
    $this->set(compact('page', 'subpage'));

    /*add CHU
    if(in_array($page, $this->allowedPages) || $this->User->loggedin) {
    $this->render($page);
    } */

    if(in_array($page, $this->allowedPages) ) {
        $this->render($page); //here redirects to login page change the path if the path is different
    }


    try {
        $this->render(implode('/', $path));
    } catch (MissingTemplateException $e) {
        if (Configure::read('debug')) {
            throw $e;
        }
        throw new NotFoundException();
    }
}

并添加了这样的路线:

$routes->connect('/main', ['controller' => 'Pages', 'action' => 'display', 'main']);

但正在发生的事情是,当用户登录时,登录页面会再次显示。我认为应该添加验证以检查用户是否在此处登录:

if(in_array($page, $this->allowedPages) ) {
        $this->render($page); //here redirects to login page change the path if the path is different
    }

我该怎么做?

我试过这些答案: Auth for static page

Allowing a Specific Page in Cakephp

1 个答案:

答案 0 :(得分:1)

我认为没必要经历这么多麻烦。例如:如果您的操作名称是" privacyPolicy",您只需在AppController本身的$ this-> Auth-> allow()中指定它。

如果你想将它分开并在PagesController中编写,我建议你调用父函数。否则,PagesController中的beforeFilter将覆盖AppController的beforeFilter。

   //AppController.php

  /* Other code */

  public function beforeFilter() {

  ..........

  $this->Auth->allow(array(
     "action1",
     "action2",
     "display"
   ));
  }

_____________________或________________________________

  // PagesController.php

   public function beforeFilter() {
      parent::beforeFilter(); // Add this line
      $this->Auth->allow('display');
   }

希望这有帮助。

和平!的xD