Home > Back-end >  Laravel - How can I get user info based on a bearer token passed through a URL parameter?
Laravel - How can I get user info based on a bearer token passed through a URL parameter?

Time:10-27

I'm using sanctum to authenticate the API calls.

I'm loading images and videos within an app, and as I want the user to be logged in and actually be able to identify which user is requesting the image or video, I'm adding the bearer token as a parameter within the video/image URL.

i.e. <img src="https://mysite.test/private/video?e=XXXXX&tk=my_bearer_token" />

On the backend I'm then doing something like:

public function getPrivateVideo (Request $request) {
    $validator = Validator::make($request->all(), [
        'e' => 'required|exists:employees,id',
        't' => 'required|exists:course_lesson_videos,code',
        'tk' => 'nullable'
    ]);

    if(auth()->check(){
        $user = auth()->user();
    }elseif($request->tk){
        $user = get user by access token or  fail
    }else{
        return abort('403');
    }
    Log::info([$user->id,$request->e,$request->t]);

    $video_code = $request->t;

    if($validator->fails() || $request->user()->client_employee->id !== $request->e || !CourseLessonVideo::join('course_lesson_questions as clq','clq.lesson_id','course_lesson_videos.lesson_id')->join('course_employee_assigned_questions as ceaq','ceaq.question_id','clq.id')->where('employee_id',$request->e)->where('code',$video_code)->first()) 
        return abort('403');

    return response()->file(storage_path('app/videos/'.$video_code));
}

I assume it must be possible somehow?

CodePudding user response:

You can retrieve the authenticated user using the facade Auth

// Retrieve the authenticated user
Auth::user();
// Retrieve the authenticated user ID
Auth::id();

See this link of documentation Retrieve the authenticated user

CodePudding user response:

To get a user by tokens

try this code

findToken()

use Laravel\Sanctum\PersonalAccessToken;

$token = PersonalAccessToken::findToken($request->get('tk'));

$user = $token->tokenable;

Or

$token = PersonalAccessToken::where('token', $token)->first();

$user = $token->tokenable;
  • Related