我的学生控制器中有以下isAuthorized()函数:
function isAuthorized() {
$studentId = $this->Auth->user('id');
$studentEmail = $this->Auth->user('email');
if ($this->Auth->user('active') == 1 && $this->Auth->user('level_complete') != 1) {
$this->Auth->loginRedirect = '/classrooms/view';
return true;
} elseif (!$this->Student->hasPayed($studentId)) {
$this->Session->write('Payment.student_id', $studentId);
$this->Session->write('Payment.student_email', $studentEmail);
$this->Session->write('Payment.examScore', $this->Student->getPlacementScore($studentId));
$this->Auth->logout();
$this->redirect(array('controller'=>'payments', 'action'=>'pay'));
} elseif ($this->Auth->user('level_complete') == 1) {
$this->Session->write('Payment.student_id', $studentId);
$this->Session->write('Payment.student_email', $studentEmail);
$this->Auth->logout();
$this->redirect(array('controller' => 'payments', 'action' => 'repay'));
} else {
$this->Auth->logout();
$this->redirect(array('controller' => 'students', 'action' => 'disabled'));
}
return false;
}
Run Code Online (Sandbox Code Playgroud)
基本上,此方法涵盖四种可能的状态:
我遇到的问题是我的标题中有一个登录表单,我可以从任何控制器登录.如果我从学生控制器以外的控制器登录,则不会调用isAuthorized()方法,即使用户无法登录,也可以登录.
有任何想法吗?
编辑:在检查API的isAuthorized()方法的定义后,我认为只有在请求学生控制器的操作时才调用该方法.那么我还能在哪里实现这个逻辑呢?谢谢
你搞砸了.只有在用户登录时才会调用isAuthorized()方法.
这意味着蛋糕将逻辑分为两部分:
1)用户必须登录以查看访问操作是否受该$this->Auth->allow()方法控制(在控制器的beforeFilter内).如果用户必须登录以查看操作,则告诉cake.
2)用户必须传递isAuthorized()方法.仅当$ this-> Auth-> authorize设置为"controller"时.
因此,如果您希望用户必须登录才能从Controller C访问操作"X",则必须在C语言控制器中输入以下代码:
function beforeFilter(){
$this->Auth->authorize = 'controller';
$this->Auth->allow('*');
}
Run Code Online (Sandbox Code Playgroud)
之后,如果您想要更多地控制它(例如,如果用户角色是"admin"),那么您必须在isAuthorized()方法中执行此操作.
希望能帮助到你.