'Laravel Sanctum tokenCan method on User model returns false despite correct ability
I'm using Laravel Sanctum in my Laravel 8 project, I'm building a controller which will allow other Laravel projects to authenticate and check the abilities of a token, to do this I'm finding a token using the findToken method, grabbing the tokenable_id (this is the user id) and then looking up this user based on the User model.
I'm then storing this in a variable and checking the abilities with tokenCan but it's always returning false despite my token having the correct abilities, what am I missing from this method?
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use Laravel\Sanctum\PersonalAccessToken;
use App\Models\User;
class HubController extends Controller
{
/**
* Instantiate a new AccountController instance.
*
* @return void
*/
public function __construct()
{
$this->middleware('throttle:30,1');
}
/**
* Handle the incoming request.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function __invoke(Request $request)
{
$validator = Validator::make($request->all(), [
'token' => 'required|string',
'ability' => 'required|string'
]);
if ($validator->fails()) {
return response()->json([
'message' => "It looks like you've missed something.",
'errors' => $validator->messages()
], 400);
}
$token = PersonalAccessToken::findToken($request->input('token'));
if (!$token) {
return response()->json([
'message' => "Token not found or is invalid"
], 404);
}
$user = User::find($token->tokenable_id);
if (!$user) {
return response()->json([
'message' => "User not found or is invalid"
], 404);
}
// $user->tokenCan('reports:view') always returning false
return response()->json([
'token' => $user->tokenCan('reports:view'),
'message' => "You don't have the correct permissions to perform this action."
], 401);
return response()->json([
'user' => $user
], 200);
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
