Search code examples
laravelphpunittokenlaravel-passportlaravel-sanctum

Verify Token is Token Laravel Passport


I was recently updating from laravel's sanctum to passport; and there is this one test that bothers me a lot. In sanctum there is this method under the PersonalAccessToken model that finds the token and returns the token if it exists. I don't seem to find anything like that in the docs or online. I'm validating the test by asserting that $user->tokens is not empty... yet I wish to validate that the token I'm returning from my login controller is indeed a token; not just the creation;

Thnx in advance...

Login Test

public function user_can_login()
{
    //$this->withoutExceptionHandling();

    $user = User::factory()->create();
    $url = route('api.v1.auth.login', [
        'email' => $user->email,
        'password' => 'password'
    ]);
    $res = $this->jsonApi()
        ->post($url)
        ->assertStatus(200);

    $token = $res->json(['access_token']);

    $this->assertNotEmpty($user->tokens);
}

Login method in authcontroller

public function login(Request $request)
{
    $request->validate([
        'email' => 'required|email',
        'password' => 'required',
    ]);

    $credentials = $request->only(['email', 'password']);

    if (Auth::attempt($credentials)) {
        $user = Auth::user();
        $access_token = $user->createToken('laravel-api.local')->accessToken;
        return response()->json(['access_token' => $access_token], 200);
    } else {
        return response()->json(['error' => 'Unauthorized'], 401);
    }
}

pues:dont know why im writing the code, but just for ref of what i'm doing


Solution

  • https://laracasts.com/discuss/channels/testing/how-do-i-create-a-route-while-testing

    solution is quite simple... you'll find it here... I had an issue when I tried that before hand and it seems to be with the use of the Route::name('name') method and the route('name') function threw a server error. but if you call the path directly it should work...

    any who... authController and login method stay the same but the test changes to...

    public function setUp(): void
    {
        parent::setUp();
    
        Route::middleware('auth:api')
            ->get('/test-route', function (Request $request) {
                return $request->user();
            });
    
        $clientRepository = new ClientRepository();
    
        $client = $clientRepository->createPersonalAccessClient(
            null,
            'Personal Access Client Test',
            '/'
        );
        DB::table('oauth_personal_access_clients')->insert([
            'client_id' => $client->id,
            'created_at' => date('Y-m-d'),
            'updated_at' => date('Y-m-d'),
        ]);
    }
    
    /** @test */
    public function user_can_login_with_correct_credentials()
    {
        //$this->withoutExceptionHandling();
    
        $user = User::factory()->create();
        $url = route('api.v1.auth.login', [
            'email' => $user->email,
            'password' => 'password',
            'device_name' => $user->name . ' test Device'
        ]);
        $res = $this->jsonApi()
            ->post($url)
            ->assertStatus(200);
    
        $token = $res->json(['access_token']);
    
        $this->jsonApi()
            ->withHeader('Authorization', 'Bearer ' . $token)
            ->get('/test-route')
            ->assertStatus(200);
    }