【问题标题】:cakephp: How to set flash message in custom isAuthorized model method?cakephp:如何在自定义 isAuthorized 模型方法中设置 flash 消息?
【发布时间】:2010-08-13 13:30:12
【问题描述】:

嗨,我对 cakephp 比较陌生。我尝试创建一个简单的应用程序作为学习和实践。 我使用 Auth 组件实现了一个简单的用户处理系统。我在用户模型中创建了一个自定义 isAuthorized 方法。 注册后,用户需要激活自己才能登录。如果用户未激活,则授权返回 false,并且我想通知用户他未激活。 但是我不知道如何在这个方法里面设置 flash 消息(我试过没有成功)。

function isAuthorized($user, $controller, $action) { 
 // We have simply user-rights system. There are admins and non-admins.
 // This function makes a decision if the user have rights to do what requested.
  if($user['User']['active']==0) { // if the user has not been activated yet then gets no rights
   $authed=false;
   $this->Auth->authError = __("Please activate your user first!",true);
  } else {
   $this->Auth->authError = __("Sorry, you do not have access to this area.",true);
   if($user['User']['admin']==1) { //all admins has all rights
    $authed=true;
   } else {
    if($controller=='Areas' or $controller=='Rooms' or $controller=='Categories') {
     if($action=='read') {
      $authed=true;
     } else {
      $authed=false; //non-admin users are not authorized to add or edit rooms or areas
     }
    } else {
     $authed=true; // however they are allowed to do other tasks. the per task rights are controlled within the controllers
    }
   }
  }
  //debug($authed);
  return $authed;

如您所见,我尝试过,但失败了 :) 它不起作用。

我也试过了

$this->Auth->authError = __("Please activate your user first!",true);

在用户控制器 login() 中没有成功

【问题讨论】:

  • 不,它没有。基本 authError 消息显示在 app_controller 中设置的内容。

标签: cakephp


【解决方案1】:

我意识到 Auth 组件比控制器方法更早地被激活,并且如果用户未经授权就会采取行动,这意味着它在控制器有机会修改 authError 之前 重定向。这就是我得到“标准”authError 的原因。

当我使用自定义授权函数(在模型中)时,用户已经通过身份验证(如果有条目)并且会话变量的 Auth 部分已经设置。 因此,如果我检查会话身份验证数据,我可以在控制器中决定用户是否经过身份验证且未激活。然后我设置了一条 flash 消息,以便用户收到来自 auth 组件的 auth 错误消息(无权访问该区域)和另一条消息作为正常的 flash 消息来激活他/她自己。

function login() {
    if(empty($this->Auth->data) and $this->Session->read('Auth.User.active')===0){
        $this->Session->setFlash(__('Please activate your user first.',true));
    }
}

我想这不是解决这个问题的最优雅的方法;)但我是网络编程新手,也是 cakephp。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-10-31
    • 1970-01-01
    • 2019-11-19
    • 1970-01-01
    • 1970-01-01
    • 2018-09-26
    • 2016-01-02
    • 2017-02-21
    相关资源
    最近更新 更多