如何使用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/'
我做错了什么?
答案 0 :(得分:2)
在CakePHP中使用Auth组件并尝试访问受限制的站点时,它会将您重定向到登录页面并将引用页面保存在会话中。会话密钥 Auth.redirect 包含您要查找的值 - 您尝试访问的页面。
查看AuthComponent的__unauthenticated()方法。它包括负责将会话值写入 Auth.redirect 的代码。如果您不想使用AuthComponent,您可以检查它在组件中的实现方式,并根据我提到的方法编写您自己的解决方案。
答案 1 :(得分:2)
$ this-> referer()不会为您提供正确的推荐人网址。如果你想获得推荐人网址只需使用$ this->会话 - >读取('Auth.redirect');
您可以通过$ this-> Session-> read('Auth.redirect');
找到您要查找的确切网址 每次重新加载页面时,$ this-> referer()值都会更新。