laravellaravel-facade

Getting 403 Forbidden while using gate facade


When writing privileges and rights of a user shows error: 403 Forbidden

Controller code

class IndexController extends AdminController
{
    public function __construct(){

        parent::__construct();

        if (Gate::denies('VIEW_ADMIN')) {
            abort(403);
        }

        $this->template = env('THEME').'.admin.index';
 }

AuthServiceProvider code

public function boot()
{
    $this->registerPolicies();

   Gate::define('VIEW_ADMIN', function($user){
        return $user->canDo('VIEW_ADMIN');
    });

    //
}

Model User code

The User model is associated with the Roles model, and the Roles model is associated with the Permission model.

public function canDo($permission, $require = FALSE){

    if (is_array($permission)) {
        dump($permission);
    }
    else{
        foreach ($this->roles as $role) {
           foreach ($this->permissions as $permission) {
               if (str_is($permission,$permission->name)) {
                   return true;
               }
           }
        }
    }        
}

Solution

  • Your Gate definition and registration appear to be fine, I suspect the error lies in your canDo function.

    Ignoring the if(is_array($permission)) check:

    // does the user have any roles?
    foreach ($this->roles as $role) {
        foreach ($this->permissions as $permission) {
            // what is str_is? It's not a PHP function
            if (str_is($permission, $permission->name)) { 
                return true;
            }
        }
    }
    

    Check if the user has any roles, if they do not then canDo will return empty and be considered false.

    Not sure what str_is is? It's not a PHP function, did you mean something like strcasecmp or maybe Str::is?

    I suspect there are no roles, as otherwise you wouldn't get a 403, instead you would likely get a Call to undefined function str_is() error.