arifkhn46

arifkhn46

Technology Lead at New Delhi

Member Since 2 Years Ago

New Delhi

Experience Points
44,720
Total
Experience

280 experience to go until the next level!

In case you were wondering, you earn Laracasts experience when you:

  • Complete a lesson — 100pts
  • Create a forum thread — 50pts
  • Reply to a thread — 10pts
  • Leave a reply that is liked — 50pts
  • Receive a "Best Reply" award — 500pts
Lessons Completed
411
Lessons
Completed
Best Reply Awards
5
Best Reply
Awards
  • start your engines Created with Sketch.

    Start Your Engines

    Earned once you have completed your first Laracasts lesson.

  • first-thousand Created with Sketch.

    First Thousand

    Earned once you have earned your first 1000 experience points.

  • 1-year Created with Sketch.

    One Year Member

    Earned when you have been with Laracasts for 1 year.

  • 2-years Created with Sketch.

    Two Year Member

    Earned when you have been with Laracasts for 2 years.

  • 3-years Created with Sketch.

    Three Year Member

    Earned when you have been with Laracasts for 3 years.

  • 4-years Created with Sketch.

    Four Year Member

    Earned when you have been with Laracasts for 4 years.

  • 5-years Created with Sketch.

    Five Year Member

    Earned when you have been with Laracasts for 5 years.

  • school-in-session Created with Sketch.

    School In Session

    Earned when at least one Laracasts series has been fully completed.

  • welcome-newcomer Created with Sketch.

    Welcome To The Community

    Earned after your first post on the Laracasts forum.

  • full-time-student Created with Sketch.

    Full Time Learner

    Earned once 100 Laracasts lessons have been completed.

  • pay-it-forward Created with Sketch.

    Pay It Forward

    Earned once you receive your first "Best Reply" award on the Laracasts forum.

  • subscriber Created with Sketch.

    Subscriber

    Earned if you are a paying Laracasts subscriber.

  • lifer Created with Sketch.

    Lifer

    Earned if you have a lifetime subscription to Laracasts.

  • evangelist Created with Sketch.

    Laracasts Evangelist

    Earned if you share a link to Laracasts on social media. Please email [email protected] with your username and post URL to be awarded this badge.

  • chatty-cathy Created with Sketch.

    Chatty Cathy

    Earned once you have achieved 500 forum replies.

  • lara-veteran Created with Sketch.

    Laracasts Veteran

    Earned once your experience points passes 100,000.

  • 10k-strong Created with Sketch.

    Ten Thousand Strong

    Earned once your experience points hits 10,000.

  • lara-master Created with Sketch.

    Laracasts Master

    Earned once 1000 Laracasts lessons have been completed.

  • laracasts-tutor Created with Sketch.

    Laracasts Tutor

    Earned once your "Best Reply" award count is 100 or more.

  • laracasts-sensei Created with Sketch.

    Laracasts Sensei

    Earned once your experience points passes 1 million.

  • top-50 Created with Sketch.

    Top 50

    Earned once your experience points ranks in the top 50 of all Laracasts users.

Level 9
44,720 XP
Apr
30
1 month ago
Activity icon

Replied to Laracasts Refresh

Laracasts looks awesome @jeffreyway we love it!

Apr
15
1 month ago
Activity icon

Replied to Testing API Without Middleware For Sanctum

@saurabh

Okay then try this

Add use statement on the top of your feature test class.

use Laravel\Sanctum\Http\Middleware\EnsureFrontendRequestsAreStateful;

Now in your test method add the following line:

$this->withoutMiddleware(EnsureFrontendRequestsAreStateful::class);

For example:

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

        $this->withoutMiddleware(EnsureFrontendRequestsAreStateful::class);

	// Your code
    }

Or you can add this to setUp(); method for all test cases;

I hope this would work, please check once.

Activity icon

Replied to Laravel Sanctum

@amshu

It depends on the implementation

For WEB

For web you don't need the token explicitly the sanctum/csrf-token handles everything for you. In case of web make sure you are allowing credentials for example:

In Axios axios.defaults.withCredentials = true;

In JavaScript: xhr.withCredentials = true;.

For Mobile authentication

For mobile authentication, you don't need to call sanctum/csrf-cookie API.

Please refer to the official doc section "Mobile Application Authentication".

https://laravel.com/docs/7.x/sanctum#mobile-application-authentication.

General flow will be as follows:

  1. Make a login API and make sure you are not using auth: sanctum middleware with this.
  2. Call the login API and validate user credentials and return a token on success. You can refer following code:
   /**
     * Get a Token via given credentials.
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function login()
    {
        $credentials = request()->validate([
            'email' => 'required|email',
            'password' => 'required',
        ]);
        
        $user = User::where('email', $credentials['email'])->first();
        
        if (! $user || ! Hash::check($credentials['password'], $user->password)) {
            return response()->json(['message' => 'Unauthorized'], 401);
        }
        
        return $this->respondWithToken($user->createAccessToken(), ["user" => $user]);
    }

The user object has createToken() method to issue a token.

  1. Now use this token with every request your making to the routes having auth:sanctum middleware attached to itself.

You need to add 'Authorization' => 'Bearer '. $access_token header in the request headers.

I hope you get the idea!

Activity icon

Replied to Sanctum Config For Mobile Authentication

@firmlab

I think this setting is used when your request is coming from web. For mobile authentication, you don't need to call sanctum/csrf-cookie API.

Please refer to the official doc section "Mobile Application Authentication".

https://laravel.com/docs/7.x/sanctum#mobile-application-authentication.

General flow will be as follows:

  1. Make a login API and make sure you are not using auth: sanctum middleware with this.
  2. Call the login API and validate user credentials and return a token on success. You can refer following code:
   /**
     * Get a Token via given credentials.
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function login()
    {
        $credentials = request()->validate([
            'email' => 'required|email',
            'password' => 'required',
        ]);
        
        $user = User::where('email', $credentials['email'])->first();
        
        if (! $user || ! Hash::check($credentials['password'], $user->password)) {
            return response()->json(['message' => 'Unauthorized'], 401);
        }
        
        return $this->respondWithToken($user->createAccessToken(), ["user" => $user]);
    }

The user object has createToken() method to issue a token.

  1. Now use this token with every request your making to the routes having auth:sanctum middleware attached to itself.

You need to add 'Authorization' => 'Bearer '. $access_token header in the request headers.

I hope you get the idea!

Activity icon

Replied to Laravel Valet Wordpress Redirect

I installed Wordpress and everything is just working fine, I am not facing any problem.

Activity icon

Replied to Sanctum SPA Auth

make sure you have performed the following step:

https://laravel.com/docs/7.x/sanctum#cors-and-cookies

and on your front end you are allowing credentials to be passed with the request:

axios.defaults.withCredentials = true;

Activity icon

Replied to Testing API Without Middleware For Sanctum

@saurabh

Please refer official documentation

https://laravel.com/docs/7.x/sanctum#testing

For example, you could make a helper method in TestCase.php class to log in a user

   /**
     * Sign in the given user or create new one if not provided.
     * 
     * @param $user \App\User
     * 
     * @return \App\User
     */
    protected function signIn($user = null)
    {
        $user = $user ?: factory('App\User')->create();
        Sanctum::actingAs($user, ['*']);
        return $user;
    }

also don't forget to add following on the top of your class:

use Laravel\Sanctum\Sanctum;

Apr
14
1 month ago
Activity icon

Started a new Conversation Sanctum: Issue With User Logout Case + TDD

Description:

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();
        $this->jsonPost(route('api.user.logout'))->assertStatus(401);

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

        $response = $this->json('POST', route('api.user.login'), [
            'email'=> $user->email,
            'password' => 'password'
        ])->assertStatus(200);
        
        $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()
    {
        auth()->user()->tokens()->delete();
        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:

  1. 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.

  2. 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:

  1. Setup Laravel 7 and Sanctum
  2. Setup API routes for login, log out, and user profile or any sanctum token protected route.
  3. Create a feature test or use the above feature test code.
  4. Run the tests.
Apr
05
1 month ago
Activity icon

Commented on Intro To Laravel Sanctum

Finally! I found a screencast on decouple architecture. Thanks for the awesome work @drehimself, Kudos!.