3 months ago

Sanctum: Issue with user logout case + TDD!!

Posted 3 months ago by konarktriv7

I am writing a use case to logout a user, so on Logout request, I delete all the user tokens so that every token issued previously becomes invalid for further requests.

Following is the feature test case:

/** @test */
public function a_user_can_logout()

    // $this->withoutExceptionHandling();

    $user = factory('App\User')->create();

    $response = $this->json('POST', route('api.user.login'), [
        'email'=> $user->email,
        'password' => 'password'
    $this->jsonPost(route('api.user.logout'), [], $response->json()['access_token'])->assertStatus(200);
    $this->jsonPost(route('api.user.profile'), [], $response->json()['access_token'])->assertStatus(401);

Now on logout request following method runs:

public function logout()
    return response()->json(['message' => 'Successfully logged out']);

Now comes the bug part, in the last assertion i.e. $this->jsonPost(route('api.user.profile'), [], $response->json()['access_token'])->assertStatus(401); I am calling user profile API which should return the status as 401 but it always returns 200.

Screenshot 2020-04-14 at 8 12 47 PM

My profit method:

public function profile() { return response()->json(auth()->user()); } I tried to debug the issue and the following are my observations:

I am facing this issue when I run this feature test through the command line. If I test the same thing on POSTMAN Client the functionality is just working fine. So this issue is related to TDD.

There is a method in the class Illuminate/Auth/RequestGuard.php

public function user() { // If we've already retrieved the user for the current request we can just // return it back immediately. We do not want to fetch the user data on // every call to this method because that would be tremendously slow. if (! is_null($this->user)) { return $this->user; }

   return $this->user = call_user_func(
       $this->callback, $this->request, $this->getProvider()

} In this method Laravel is caching user object for performance optimization. And If we comment out the caching code i.e.

if (! is_null($this->user)) { return $this->user; } my feature test case runs perfectly.

Screenshot 2020-04-14 at 8 10 56 PM

Following is my route list:

Screenshot 2020-04-14 at 7 45 27 PM

Steps To Reproduce: Setup Laravel 7 and Sanctum Setup API routes for login, log out, and user profile or any sanctum token protected route. Create a feature test or use the above feature test code. Run the tests.

Update: My issue has been solved, thank you. https://nox.tips/ https://xender.vip/ https://testmyspeed.onl/

Please sign in or create an account to participate in this conversation.