spatie/laravel-permission

[Lumen] Call to undefined method App\Models\User::canAny()

aarisfauji opened this issue · 6 comments

Issue Description:

I am currently facing an issue with the following error message:

"Call to undefined method App\Models\User::canAny()"

Context:

I have a sample router set up as follows:

$router->group([
    'prefix' => 'test',
    'middleware' => ['auth']
], function () use ($router) {
    $router->group([
        'middleware' => ['permission:tag_read']
    ], function () use ($router) {
        $router->get('/', function () use ($router) {
            return response()->json(['hello' => "world"]);
        });
    });
});

The response I receive is:

{
    "status": "ERROR",
    "statusCode": 500,
    "message": "Call to undefined method App\Models\User::canAny()",
    "payload": null,
    "error": "BadMethodCallException"
}

User Model:

use Spatie\Permission\Traits\HasPermissions;
use Spatie\Permission\Traits\HasRoles;

class User extends Model implements AuthenticatableContract, AuthorizableContract, JWTSubject
{
    use HasRoles, HasPermissions;
    //.. other code parts
}

Middleware in the app.php file:

// app.php
$app->routeMiddleware([
    'auth' => App\Http\Middleware\Authenticate::class,
    'permission' => Spatie\Permission\Middleware\PermissionMiddleware::class,
    'role'       => Spatie\Permission\Middleware\RoleMiddleware::class,
]);

Question:

My question is, why is the hasAnyPermission method being checked in the code, but the canAny method is being executed? The relevant part of the code is in the PermissionMiddleware class:

// vendor\spatie\laravel-permission\src\Middleware\PermissionMiddleware.php
if (!method_exists($user, 'hasAnyPermission')) {
    throw UnauthorizedException::missingTraitHasRoles($user);
}

$permissions = is_array($permission)
    ? $permission
    : explode('|', $permission);

if (!$user->canAny($permissions)) {
    throw UnauthorizedException::forPermissions($permissions);
}

Environment:

  • Laravel/Lumen version: ^10.0
  • Spatie Laravel Permission version: ^6.1

I appreciate any guidance or insights into resolving this issue. Thank you.

The canAny() method comes from the Illuminate\Foundation\Auth\Access\Authorizable trait provided by Laravel.

The Permission middleware uses it so that its results are the same as if you had called canAny() directly.

Aside: You don't need to include the HasPermissions trait when you're already including the HasRoles trait, because HasRoles includes HasPermissions automatically.

class User extends Model implements AuthenticatableContract, AuthorizableContract, JWTSubject

You didn't post your complete User model.
Specifically: you didn't post the code that shows what namespace it is declared in, to be sure it matches the error message and therefore isn't hitting some other part of your code.
You also didn't post the imported use classes that show what the AuthorizableContract is an alias of.

class User extends Model implements AuthenticatableContract, AuthorizableContract, JWTSubject

You didn't post your complete User model. Specifically: you didn't post the code that shows what namespace it is declared in, to be sure it matches the error message and therefore isn't hitting some other part of your code. You also didn't post the imported use classes that show what the AuthorizableContract is an alias of.


The code for the User model is as follows:

<?php

namespace App\Models;

use Illuminate\Auth\Authenticatable;
use Illuminate\Contracts\Auth\Access\Authorizable as AuthorizableContract;
use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Laravel\Lumen\Auth\Authorizable;
use Spatie\Permission\Traits\HasRoles;
use Tymon\JWTAuth\Contracts\JWTSubject;

class User extends Model implements AuthenticatableContract, AuthorizableContract, JWTSubject
{
    use Authenticatable, Authorizable, HasFactory, HasRoles;

    /**
     * The attributes that are mass assignable.
     *
     * @var string[]
     */
    protected $fillable = [
        'name',
        'username',
        'password',
    ];

    /**
     * The attributes excluded from the model's JSON form.
     *
     * @var string[]
     */
    protected $hidden = [
        'password',
    ];


    /**
     * Get the identifier that will be stored in the subject claim of the JWT.
     *
     * @return mixed
     */
    public function getJWTIdentifier()
    {
        return $this->getKey();
    }

    /**
     * Return a key value array, containing any custom claims to be added to the JWT.
     *
     * @return array
     */
    public function getJWTCustomClaims()
    {
        return [];
    }
}

Note that in the above model, I have attempted to remove the HasPermissions trait, but the result remains the same (error: Call to undefined method App\Models\User::canAny()).

your code:
use Illuminate\Auth\Authenticatable;
use Illuminate\Contracts\Auth\Access\Authorizable as AuthorizableContract;
use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Laravel\Lumen\Auth\Authorizable;
use Spatie\Permission\Traits\HasRoles;
use Tymon\JWTAuth\Contracts\JWTSubject;

class User extends Model implements AuthenticatableContract, AuthorizableContract, JWTSubject
{
use Authenticatable, Authorizable, HasFactory, HasRoles;

Note that because of your imports at the top of the class, your use Authenticatable, Authorizable, HasFactory, HasRoles; line is using the Laravel\Lumen\Auth\Authorizable trait instead of Laravel's Illuminate\Foundation\Auth\Access\Authorizable.
Lumen doesn't implement canAny(), which is why your canAny() error is appearing.

You will either need to use Laravel's Authorizable trait, or re-implement the missing methods in your User model.

The docs have been updated to include a note about this.

your code:
use Illuminate\Auth\Authenticatable;
use Illuminate\Contracts\Auth\Access\Authorizable as AuthorizableContract;
use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Laravel\Lumen\Auth\Authorizable;
use Spatie\Permission\Traits\HasRoles;
use Tymon\JWTAuth\Contracts\JWTSubject;

class User extends Model implements AuthenticatableContract, AuthorizableContract, JWTSubject { use Authenticatable, Authorizable, HasFactory, HasRoles;

Note that because of your imports at the top of the class, your use Authenticatable, Authorizable, HasFactory, HasRoles; line is using the Laravel\Lumen\Auth\Authorizable trait instead of Laravel's Illuminate\Foundation\Auth\Access\Authorizable. Lumen doesn't implement canAny(), which is why your canAny() error is appearing.

You will either need to use Laravel's Authorizable trait, or re-implement the missing methods in your User model.

The docs have been updated to include a note about this.

I attempted to implement some missing methods from Illuminate\Foundation\Auth\Access\Authorizable, but it resulted in another issue, such as:

"Spatie\Permission\PermissionServiceProvider::Spatie\Permission{closure}(): Argument #2 ($app) must be of type Illuminate\Contracts\Foundation\Application, Laravel\Lumen\Application given, called in C:\laragon\www\api-blog\vendor\illuminate\container\Container.php on line 1302"

As an alternative, I tried creating or copying a new middleware from Spatie\Permission\Middleware\PermissionMiddleware::class with code modifications:

class PermissionMiddleware
{
    public function handle($request, Closure $next, $permission, $guard = null)
    {
        //.. other code parts

        if (!$user->canAny($permissions)) {
            throw UnauthorizedException::forPermissions($permissions);
        }

        return $next($request);
    }

   //.. other code parts
}

Changed to:

class PermissionMiddleware
{
    public function handle($request, Closure $next, $permission, $guard = null)
    {
        //.. other code parts

        if (!$user->hasAnyPermission($permissions)) {
            throw UnauthorizedException::forPermissions($permissions);
        }

        return $next($request);
    }

    //.. other code parts
}

The above code works well and meets my expectations for the time being.

Yes, that was going to be my next suggestion: clone the middleware from this package and replace canAny with hasAnyPermission.
Seems like the best solution.