Mahaveer
1 week ago
137
3
Laravel

laravel passport Unauthorized postman

Posted 1 week ago by Mahaveer

Passport Token not working.

User login controller method

public function userlogin(Request $request)
    {
       $validator = Validator::make($request->only(['email', 'password']), [ 
            'email' => 'required|string|email',
            'password' => 'required|string'
        ]);

       if ($validator->fails()) { 
            $response = [
                'status' => false,
                'message' => $validator->errors()->first(),
            ];
            return response()->json($response, 401);            
        }

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

        if(!Auth::attempt($credentials))
        {
            $response = [
                'status' => false,
                'message' => trans('auth.failed'),
            ];

            return response()->json($response);
        }

        $user = $request->user();

        $objToken = $user->createToken('quechua');

        $strToken = $objToken->accessToken;

        $expiration = $objToken->token->expires_at->toDateTimeString();

        $response = [
            'status' => true,
            'message' => 'Login successfully.',
            'access_token' => $strToken,
            'token_type' => 'Bearer',
            'expires_at' => $expiration,
            'data' => [
                'first_name' => $user->first_name,
                'last_name' => $user->last_name,
                'email' => $user->email,
            ]
        ];

        return response()->json($response);
    }

Get user detail controller method

public function details() 
    { 
        //Check user login or not
        if (Auth::check()) {

            //Get Login user detail
            $user = Auth::user();
            
            $userarray = [
                'user_id' => $user->id,
                'first_name' => $user->first_name ?? '',
                'last_name' => $user->last_name ?? '',
                'email' => $user->email ?? '',
                'job_title' => $user->usermeta->job_title ?? '',
                'about_me' => $user->usermeta->about_me ?? '',
            ];

            $response = [
                'status' => true,
                'message' => 'User profile detail',
                'data' => $userarray,
            ];

            return response()->json($response, 200);

        }else{

            $response = [
                'status' => false,
                'message' => 'Unauthorized',
            ];
            
            return response()->json($response, 401);
                
        }

        exit();
    }

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