Created
February 13, 2024 03:51
-
-
Save jack2jm/21b13f96ceec49694967477ecae61334 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Ref Link: | |
https://jwt-auth.readthedocs.io/en/docs/laravel-installation/ | |
https://medium.com/@online-web-tutor/laravel-10-restful-apis-with-jwt-authentication-tutorial-9f5345e3cce6 | |
Add JWT Auth | |
====================================================== | |
=> composer require tymon/jwt-auth | |
=> Add below in your app.php file from /config folder. | |
'providers' => [ | |
... | |
Tymon\JWTAuth\Providers\LaravelServiceProvider::class, | |
] | |
=> php artisan vendor:publish --provider="Tymon\JWTAuth\Providers\LaravelServiceProvider" | |
=> php artisan jwt:secret | |
Create Login Api Using both Mobile Or Email | |
====================================================== | |
1. Add route in api.php file | |
----------------------------- | |
Route::post('/user/v1/login', [APIController::class, 'userLogin'])->name('userLogin'); | |
2. Add below function in your controller | |
----------------------------------------- | |
public function userLogin(Request $request){ | |
$request->validate([ | |
'userName' => 'required', | |
'password' => 'required|string', | |
]); | |
try { | |
$pattern = '/^\+\d{1,3}\d{3,14}$/'; | |
$inputUserName = str_replace(' ','',$request->get('userName')); // pass email or mobile no | |
$inputType = $request->get('inputType'); // pass type for username is email or mobile no | |
//Check validation base on input type | |
if ($inputType == "email" && filter_var($inputUserName, FILTER_VALIDATE_EMAIL)) { | |
$credentials = ['email' => $inputUserName, 'password'=>$request->get('password')]; | |
} | |
else if($inputType == "mobile_no" && preg_match($pattern, $inputUserName)){ | |
$credentials = ['mobile_no'=>$inputUserName,'password'=>$request->get('password')]; | |
}else{ | |
return $this->sendError('Please Enter Valid ' . str_replace('_',' ',ucwords($inputType)), [], 422); | |
} | |
//Login Using | |
$token = Auth::guard('api')->attempt($credentials); | |
if (!$token) { | |
return response()->json([ | |
'status' => 'error', | |
'message' => 'These credentials do not match our records.', | |
], 401); | |
} | |
$user = Auth::guard('api')->user(); | |
$response = [ | |
'user' => $user, | |
'authorisation' => [ | |
'token' => $token, | |
'type' => 'bearer', | |
] | |
]; | |
return $this->sendResponse($response, "User login successfully."); | |
} catch (\Exception $e) { | |
//throw $e; | |
Functions::sendErrorMail($request,$e); | |
return $this->sendError('Something went wrong.', [], 422); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment