Laravel Sanctum的tokenCan函数总是返回false

mrphzbgm  于 2023-03-31  发布在  其他
关注(0)|答案(1)|浏览(109)

我不明白为什么tokenCan总是返回false,当我测试它应该返回true时:

public function login(UserLoginRequest $userLoginRequest)
    {
        $validated = $userLoginRequest->validated();

        if(!Auth::attempt($validated)){

            return \response()->json(
                ['status' => false,
                    'message' => 'email or password does not match'],
                500
            );

        }

        $user = auth()->user();

        try {

            //Check if current user has ability to update datas via api
            if ($user->tokenCan('server:update')) {
                $ability = ['server:update'];
            }else{
                //default ability
                $ability = ['server:read'];
            }

            $user->tokens()->delete();

            $newToken = $user->createToken($user->name,$ability)->plainTextToken;
        }catch(\Throwable $exception){

            return \response()->json(
                ['status' => 'error',
                    'error' => $exception->getMessage()],
                500
            );

        }

        return \response()->json(
            [
                'status' => 'login success',
                'newToken' => $newToken,
            ],
            200
        );

    }

用户登录请求:

<?php

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\Rules\Password;

class UserLoginRequest extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return true;
    }

    /**
     * Get the validation rules that apply to the request.
     * @return array<string, mixed>
     */
    public function rules(): array
    {
        return [
            'email' => 'required|email|max:50',
            'password' => [
                'required',
                Password::min(\env('MIN_PASSWORD_LENGTH'))
                    //->mixedCase()
                    ->letters()
                    ->numbers()
                    //->symbols()
                ,
            ]
        ];
    }
}

我无法通过请求传递给用户,我该如何处理?
我尝试使用具有server:update功能的用户登录,但在调试中总是返回false
我希望在这种情况下它返回true。

doinxwow

doinxwow1#

作为一种变通方法,我通过以下方式解决了这个问题:

$user = auth()->user();
$token =  $user->tokens()->first();
$abilities[] = $token->abilities[0];

$user->tokens()->delete();

$newToken = $user->createToken($user->name,$abilities)->plainTextToken;

相关问题