如果未经授权,我正在尝试暂停用户执行的操作。
所以我决定在AppController
中编写一个函数,并在beforeFilter()
函数中调用它,如This
public function beforeFilter(Event $event)
{
$this->requestData = $this->request->data;
if (isset($this->request->params['prefix']) && $this->request->params['prefix'] == 'api/v1') {
$this->checkAuthToken(); // My function to check authentication
}
parent::beforeFilter($event);
}
我检查身份验证的功能
public function checkAuthToken()
{
if (empty($this->request->header('AUTH-TOKEN')) || empty($this->requestData['employee_id'])) {
$this->DATA['error'] = 'Access Denied. Contact admin';
$this->DATA['error_code'] = 2;
} else {
$this->loadModel('Employees');
$employee = $this->Employees->get($this->requestData['employee_id']);
if ($employee->status == 'B') {
$this->DATA['error'] = 'Your account is blocked. Contact admin';
$this->DATA['error_code'] = 3;
} else if ($employee->status == 'I') {
$this->DATA['error'] = 'Your account is not active yet. Contact Admin';
$this->DATA['error_code'] = 4;
} else if ($employee->auth_token != $this->request->header('AUTH-TOKEN')) {
$this->DATA['error'] = 'Access Denied! Invalid Request';
$this->DATA['error_code'] = 5;
} else if ($employee['fail_attempts'] > 3) {
$this->DATA['error'] = 'Due to so many attempts you account is blocked! Contact admin';
$this->DATA['error_code'] = 6;
}
}
}
在beforeRender
public function beforeRender(Event $event)
{
$debugApi = true;
if (!$debugApi) {
if (isset($this->DATA['error_debug'])) {
$this->log($this->DATA['error_debug']);
$this->DATA['error'] = 'Something went wrong! Please try again';
}
}
$this->set('data', $this->DATA);
if (!array_key_exists('_serialize', $this->viewVars) &&
in_array($this->response->type(), ['application/json', 'application/xml'])
) {
$this->set('_serialize', true);
}
}
出现问题的是,如果用户请求API并且我的身份验证出错,那么我必须停止调用控制器操作并给他错误消息。或者,如果我可以将控制器更改为空白。
由于
答案 0 :(得分:0)
如果身份验证失败,您可以调用setAction方法。类似的东西:
if ($this->DATA['error']) {
return $this->setAction('error_method');
}
答案 1 :(得分:0)
if ($this->DATA['error']) {
$this->redirect(['controller'=>'test', 'action'=>'/']);
exit;
}