1

如何使用 CakePHP 2.x 获取被 Auth 组件拒绝访问的页面?如果我使用 referer() 函数,它会给我链接到被拒绝操作的页面。这是我的代码:

public function login() {
    //get the current url of the login page (or current controller+action)
    $currentLoginUrl = "/login";

    if ($this->request->is('post')) {

        $this->User->recursive = -1;            
        $user = $this->User->find(
            'first', 
            array(
                'conditions' => array(
                    'User.username' => $this->request->data['User']['username'], 
                    'User.password' => AuthComponent::password($this->request->data['User']['password'])
                )
            )
        );

        if ($user && $this->Auth->login($user['User'])) {                   
            //if the referer page is not from login page, 
            if( $this->referer() != $currentLoginUrl  )                 
            //use $this->referer() right away
            $this->redirect($this->referer('/admin', true));  //if referer can't be read, or if its not from local server, use $this->Auth->rediret() instead                   
            else
            //if the user lands on login page first, rely on our session 
            $this->redirect( $this->Session->read('beforeLogin_referer') );
        }
        else 
            $this->Session->setFlash('Username or password is incorrect', 'default', array('class' => 'alert-danger'));         
    }

    if( $this->referer() != $currentLoginUrl  )             
    //store this value to use once user is succussfully logged in
    $this->Session->write('beforeLogin_referer', $this->referer('/admin', true) ) ;  //if referer can't be read, or if its not from local server, use $this->Auth->rediret() instead                
}

所以基本上发生的事情是我没有登录,我在这个网址:

'http://localhost/hotelguide/hotels/view/17/'

然后我点击一个链接,将我带到

'http://localhost/hotelguide/hotels/review/17/'

但这需要用户登录,因此它将我重定向到登录页面,当我调试referrer()时,它给了我这个:

'http://localhost/hotelguide/hotels/view/17/'

我究竟做错了什么?

4

2 回答 2

2

$this->referer() 不会为您提供正确的推荐人网址。如果您想获取推荐人网址,只需使用 $this->Session->read('Auth.redirect');

您可以通过 $this->Session->read('Auth.redirect'); 找到您正在寻找的确切网址

每次重新加载页面时,$this->referer() 值都会更新。

于 2013-10-09T09:04:20.440 回答
2

当您在 CakePHP 中使用 Auth 组件并尝试访问受限站点时,它会将您重定向到登录页面并将引用页面保存在会话中。会话密钥Auth.redirect保存您正在寻找的值 - 您尝试访问的页面。

查看 AuthComponent 的__unauthenticated()方法。它包括负责将会话值写入Auth.redirect的代码。如果你不想使用AuthComponent,你可以查看它在组件中是如何实现的,并根据我提到的方法编写自己的解决方案。

于 2013-10-04T17:53:24.693 回答