【问题标题】:Sessions vs Configure at CakePHPCakePHP 的会话与配置
【发布时间】:2013-03-27 14:44:02
【问题描述】:

我在网上看到一些代码,为了检查访问具体操作的权限,他们以这种方式使用Configure::read函数:

public function action1(){
    if(!Configure::read('isAdmin')){
        $this->redirect(array('controller' => 'depots', 'action' => 'status'));
    }

    //whatever
}

我想知道,为此目的使用Configure::readConfigure:write 与使用$this->Session->read()$this->Session->write() 之间有什么区别?

哪种检查方法更好?

谢谢。

【问题讨论】:

    标签: php cakephp cakephp-2.0 cakephp-2.2 cakephp-2.3


    【解决方案1】:

    使用 AuthComponent

    如果您使用内置的AuthComponent,CakePHP 将在会话中存储当前登录用户的详细信息。

    获取当前登录用户的属性

    登录后,您可以通过AuthComponent访问Used的信息(例如role_id)。这可以在任何地方完成(如果需要,也可以在您的视图或模型中);

    例如;

    if (123 === AuthComponent::user('role_id')) {
        debug('hello admin user');
    }
    

    或者,在控制器内部:

    if (123 === $this->Auth->user('role_id')) {
        debug('hello admin user');
    }
    

    Accessing the logged in user

    但是,为了不必在任何地方重复 group-id,最好为此创建一个方法(例如在您的 AppController 中);

    /**
     * Checks if the currently logged in user is an admin
     *
     * @return bool  true if the current user is an admin
     */
    protected function isAdmin()
    {
        // probably best to make the id configurable (Configure::write())?
        return (123 === $this->Auth->user('role_id'));
    }
    

    访问控制

    要使用“简单”授权,您可以在 Controller 中创建自己的 isAuthorized() 操作,这将允许您根据当前登录用户的属性阻止对特定操作的访问;

    Using ControllerAuthorize

    【讨论】:

      【解决方案2】:

      我不明白为什么要将用户角色放在配置数组中,因为它旨在包含应用程序范围的设置。

      就我个人而言,我的数据库中有一个包含角色的表。虽然可能会添加一些角色,但有一些我从不修改(通常是管理员角色)。 这使我可以将其值作为应用程序参数存储在配置中并稍后检查:

      bootstrap.php

      Configure :: write('administrator.role_id', 1);
      

      测试控制器:

      if($this->Auth->user('role_id') == Configure :: read('administrator.role_id'))
      {
          //do things specific to admin role
      }
      

      也就是说,如果用户角色在 Configure 中以一种或另一种方式动态存储,它可能也可以正常工作,但这可能不是更优雅的解决方案。

      【讨论】:

      • 我动态获取数据,那我应该使用会话吗?
      猜你喜欢
      • 2011-03-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-11-19
      • 2013-10-01
      • 2016-04-18
      • 1970-01-01
      相关资源
      最近更新 更多