Check if an user has access to a Controller/Action

Hello. I write this little code to check if an user has access to a determinated Controller/Action.




class Dummy1{

    public $_id='';

    public function getId()

    {

        return $this->_id;

    }

    public function setId($id)

    {

        $this->_id=$id;

    }

}


class User{

    static public function hasAccess($arr)

    {

        $str_controlador=$arr['c'];

        $str_accion=$arr['a'];

        

        $app=Yii::app();

        $request=$app->getRequest();

        $user=$app->getUser();

        $verb=$request->getRequestType();

        $ip=$request->getUserHostAddress();


        $filter = new CAccessControlFilter;

        $cont=Yii::app()->controller;

        $filter->rules = $cont->accessRules();        

        $reglas=$filter->getRules();


        $c=new Dummy1();

        $c->setId($str_controlador);

        $a=new Dummy1();

        $a->setId($str_accion);


        foreach($reglas as $rule)

        {

          if($rule->allow=='1')

          {

              if($rule->isUserAllowed($user,$c,$a,$ip,$verb))

              {

                  return true;

              }

          }

        }

        return false;

      }

}




//Test:


if(User::hasAccess(array('c'=>'HereYourControllerName','a'=>'HereYourActionName')))

{

    //Here if the user has access to the controller/action pair.

    .....

    .....

}



I recognize that doesn’t be the best manner to do it, but since I’ve not found another way, this is the moment you can improve this method.

Best regards.

Why dont you use RIGHTS o others RBAC extensions of yii? All is managed and work. Is all already tested. RIGHTS if very powerfoul!!!

because he needed just one (missing) function to be implemented to his work, not 100 kilobytes of modules/UI and other stuffs.

Great job Nacesprin!

Yes, but yii do not load a class if do not need. RBAC is light, and use database standard of yii.