shortcut/usefull access roles methods RBAC

You are viewing revision #1 of this wiki article.
This is the latest version of this article.

These are functions that I used very often, may helps you!

Create a new SYii.php file in protected/componets folder

Class SYii {
  
    //check if a specific user id is the current user
    public static function checkifMe($userid) {
        return Yii::app()->user->id == $userid; 
    }

    //check if a member
    public static function checkifMember($userid) {
        return Yii::app()->authManager->isAssigned("member", $userid);
    }

    public static function checkifAdmin($userid) {
        return Yii::app()->authManager->isAssigned("admin", $userid);
    }

    public static function checkifSuperAdmin($userid) {
        return Yii::app()->authManager->isAssigned("superadmin", $userid);
    }
    
    //check if user is a specific user type like admin,member,supradmin,anotherrole etc
    public static function checkifitis($userid,$role) {
        return Yii::app()->authManager->isAssigned($role, $userid);
    }

    //returns all roles of RBAC as list
    public static function rolesList() {
        $roles = Yii::app()->authManager->getRoles();
        $list = array();
        foreach ($roles as $key => $val) {
            $list[] = $key;
        }
        return $list;
    }
    
    //returns all the roles of the current user as list
    public static function rolesListPermit() {
        $list = self::rolesList();
       
        $res = array();
        foreach ($list as $key => $val) {
            if (Yii::app()->user->checkAccess($val))
                $res[$key] = $val;
        }
        return $res;
    }
    
    //returns the lowest permission role of the RBAC
      public static function getAuthItemLower() {
            $roles = Yii::app()->authManager->getRoles();
            foreach ($roles as $key => $val) {
                $is_lower_role = true;
                $roles = Yii::app()->authManager->getItemChildren($key);
                if (is_array($roles)) {
                    foreach ($roles as $key2 => $val) {
                        if ($val->type == CAuthItem::TYPE_ROLE) {
                            $is_lower_role = false;
                            break;
                        }
                    }
                } else {
                    if ($roles->type == CAuthItem::TYPE_ROLE)
                        $is_lower_role = false;
                }

                if ($is_lower_role) {
                    return $key;
                }
            }
            return null;
    }
    
 }