0

我正在为我的 UsersController 编写单元测试,以便用户只能编辑他们自己的个人资料。我正在使用 CakePHP 2.4.2 和带有控制器授权的 AuthComponent 来执行此操作。

授权配置:

public $components = array(
                      'Auth' => array(
                        'loginRedirect' => '/',
                        'logoutRedirect' => '/',
                        'authenticate' => array('Ldap'),
                        'authError' => 'You are not allowed to access this page',
                        'authorize' => 'Controller'));

用户控制器中的 isAuthorized():

public function isAuthorized($user = null) {
  if($this->Auth->loggedIn()) {
    return $this->request->params['pass'][0] == $user['id'];
  }
  return false;
}

编辑单元测试:

public function testEdit() {
  $result = $this->testAction('/users/view/1', array('return' => 'view'));
  $this->assertRegExp('/Adam C Hobaugh/', $result);
  $user = $this->generate('Users', array(
            'components' => array(
              'Session',
              'Auth' => array('user'))));
  $test = array('id' => 1);
  $user->Auth->expects($this->once())->method('loggedIn')
                                      ->with($this->returnValue(true));
  $user->Auth->expects($this->any())->method('user')
                                    ->with($this->returnValue($test));
  $user->Session->expects($this->any())->method('setFlash');
  $result = $this->testAction('/users/edit/1', array(
              'return' => 'headers',
              'data' => array('User' => array( {user array} ))));
  debug($result);
  $this->assertContains('/users', @$result['Location']);
  $result = $this->testAction('/users/view/1', array('return' => 'view'));
  $this->assertRegExp('/John Jacob Doe/', $result);
}

Expectation failed for method name is equal to <string:loggedIn> when invoked 1 time(s). Method was expected to be called 1 times, actually called 0 times.当我运行测试时,我得到了。此外,当我将 this->once() 更改为 $this->any() 并将 $test 数组中的 id 更改为 2 时,这种情况应该会失败并从浏览器执行,但它成功通过了测试。

结合这些,似乎 isAuthorized() 在单元测试期间没有被调用。我很茫然。感谢您提供的任何帮助。

4

1 回答 1

-2

第一:在您的测试代码中,您调用 view 方法而不是 edit 方法

第二: isAuthorized() 不适用于此。使用这种方法,您应该只定义谁可以访问哪些功能,不应该有任何应用程序业务逻辑。

第三:如果您想限制普通用户仅编辑他们自己的个人资料,您应该将 dit() 方法更改为类似的内容。

public function edit() {
  $this->request->data['User']['id'] = $this->Auth->User('id');
  if ($this->request->is('post') || $this->request->is('put')) {
    if ($this->User->save($this->request->data)) {
      $this->Session->setFlash(__('The user has been saved.'));
      return $this->redirect(array('action' => 'index'));
    } else {
      $this->Session->setFlash(__('The user could not be saved. Please, try again.'));
  }
  } else {
    $this->request->data = array('User' => $this->Auth->User());
  }
}

并删除 echo $this->Form->input('id'); 从您的编辑视图。

我正在写一本关于这个主题的书。它很快就会在这里可用:https ://leanpub.com/CakePHPUserAuthentication/

于 2013-11-16T17:10:26.717 回答