Laravel/Lumen Tymon/JWT by Phone Number and Password - php

I'm creating an API login for my API application by using JWT. In the default code, JWT use email and password for authenticate.
public function login(Request $request){
$credentials = $request->only(['email', 'password']);
if (!$token = JWTAuth::attempt($credentials)) {
return 'Invalid login details';
}
return $token;
}
But now, i want to change for login by Phone/Email and Password, it mean, when a request coming, i will use Regular expression to recognize that an email or phone. And then, use that's credentials for attempt() function.
Is there any solution for this? Thanks in advance.

I found Request is Illuminate\Http\Request;
and Request->only() returns array.
You can get or set value using
$credentials["email"] or $credentials["password"]

You should easily be able to do this by sending either phone or email as credentials.
if($regexShowsItsAnEmail) {
$credentials = $request->only(['email', 'password']); // or simply $credentials = ['email' => $email, 'password' => $password]
} elseif($regexShowsItsAPhoneNumber) {
$credentials = $request->only(['phone', 'password']); // or simply $credentials = ['phone' => $phone, 'password' => $password]
} else {
return response()->json(['message' => 'Unauthorized'], 401);
}

Related

JWT Auth Error : The token could not be parsed from the request

Currently I'm developing Laravel 5.8 with using JWT Auth, everything running as well in Postman, but when I tried for testing on Browser, I got a lot of errors and one by one has been fixed. Now I'm get another error when I try to pass JSON Web Token by using Request. The token isn't provided correctly. After I do sign in process in :
public function signin(Request $request)
{
$this->validate($request, [
'username' => 'required',
'password' => 'required'
]);
// grab credentials from the request
$credentials = $request->only('username', 'password');
try {
// attempt to verify the credentials and create a token for the user
if (! $token = JWTAuth::attempt($credentials)) {
return response()->json([
'error' => 'Invalid Credentials, username and password dismatches. Or username may not registered.',
'status' => '401'
], 401);
}
} catch (JWTException $e) {
// something went wrong whilst attempting to encode the token
return response()->json(['error' => 'could_not_create_token'], 500);
}
return response()->json([
'token' => $token
]);
}
The token generated successfully. But when I need the token to another controller, the token generated unsuccessfully, one of example is in this method :
public function index(Request $request)
{
// this will set the token on the object
JWTAuth::parseToken();
// and you can continue to chain methods
$user = JWTAuth::parseToken()->authenticate();
$token = JWTAuth::getToken();
die($token);
try {
if (! $user = JWTAuth::parseToken()->authenticate()) {
return response()->json(['user_not_found'], 404);
}
} catch (Tymon\JWTAuth\Exceptions\TokenExpiredException $e) {
return response()->json(['token_expired'], $e->getStatusCode());
} catch (Tymon\JWTAuth\Exceptions\TokenInvalidException $e) {
return response()->json(['token_invalid'], $e->getStatusCode());
} catch (Tymon\JWTAuth\Exceptions\JWTException $e) {
return response()->json(['token_absent'], $e->getStatusCode());
}
Everytime I'd like to JWTAuth::parseToken(); I got this error :
The token could not be parsed from the request
So why this happen? And what should I do? Because In signin method, the token successfully generated, but in index I can't access the token. Thanks for your attention.
Token needs to be passed via Headers in each api request
Header Name: Authorization
Expected Value: Bearer --token--
(without the -- ofcourse)

how to do Auth Authentication in lumen api?

I have checked using Auth::attempt(['email' => $request->email_id, 'password' => $request->password]) which works in web side but gives false in api side .
if (Auth::attempt(['email' => $request->email_id, 'password' => $request->password]))
dd("Successfully Authenticated ");
else dd("false");
Use JWT authentication to authenticate your lumen api
composer require tymon/jwt-auth
after installation follow the configuration
https://github.com/tymondesigns/jwt-auth/wiki
Below authenticate function help to authenticate and return the API token
use JWTAuth;
use Tymon\JWTAuth\Exceptions\JWTException;
class AuthenticateController extends Controller
{
public function authenticate(Request $request)
{
// grab credentials from the request
$credentials = $request->only('email', 'password');
try {
// attempt to verify the credentials and create a token for the user
if (! $token = JWTAuth::attempt($credentials)) {
return response()->json(['error' => 'invalid_credentials'], 401);
}
} catch (JWTException $e) {
// something went wrong whilst attempting to encode the token
return response()->json(['error' => 'could_not_create_token'], 500);
}
// all good so return the token
return response()->json(compact('token'));
}
}

Laravel 5 login authenication issue

I have an issue with user authentication. I can create a new user and use laravel's Hash::make command to encrypt the password which all appears to be working correctly see database record below :
Now for the login script. I did a dump die on the $input and confirmed it has the post data from the login form inside it.
Code :
public function CheckLogin()
{
$input = Request::all();
// create our user data for the authentication
$userdata = array(
'Email' => $input['email'],
'Password' => $input['password']
);
// attempt to do the login
if (Auth::attempt($userdata)) {
// if(Auth::attempt(['Email' => $input['email'], 'Password' =>$input['password'], 'ArchivedOn' => null])){
//return redirect()->intended('devices');
return redirect()->intended('devices');
} else {
$err = 'Login Failed Please check credentials and try again.';
return view('welcome', compact('err'));
}
}
The Auth::attempt appears to always return false as it always re-directs to the welcome page with the error message I specified.
I expectect I am missing something obvious but I thought I would ask for a fresh pair of eyes on this as I can't see the problem.
Your userdata should be:-
$userdata = array(
'Email' => $input['email'],
'password' => $input['password']
);
Note: You need to write Password 's p character in small letter. You can change email with Email or Username whatever name you want but password must be 'password'.
Check this link for more detail.

Laravel /w Ionic JWT authentication

So I am developing Ionic app with Laravel back-end and using JWT authentication.
My question is...since im using 4 fields when registering a user, and only 2 when logging in (email and pass), I suppose that upon registration the token should be made of only those 2 fields...
This is the working sign up function:
public function signUp()
{
$credentials = Input::all();
if (User::whereEmail($credentials['email'])->first()) {
return Response::json([
'error' => 'User with given e-mail already exists',
], 409);
} elseif (User::wherePhone($credentials['phone'])->first()) {
return Response::json([
'error' => 'User with given phone number already exists',
], 409);
} else {
$user = User::create($credentials);
$token = JWTAuth::fromUser($user);
return Response::json(compact('token'));
}
}
However if I change $credentials = Input::only('email', 'password') the full user won't be created (since there are fields missing).
But even if I leave $credentials as-is, and make combinations like
$token = JWTAuth::fromUser(Input::only('email', 'password')) or parse e-mail and password to JSON, or something similar...I get a "Trying to get a property of non-object" error, or that array is given instead of an object to JWTAuth...
JWTAuth::fromUser(Input::only('email', 'password')) expects a User object.
If you wish to use credentials you can do something like this:
// grab credentials from the request
$credentials = Input::only('email', 'password');
try {
// attempt to verify the credentials and create a token for the user
if (! $token = JWTAuth::attempt($credentials)) {
return Response::json(['error' => 'invalid_credentials'], 401);
}
} catch (JWTException $e) {
// something went wrong whilst attempting to encode the token
return Response::json(['error' => 'could_not_create_token'], 500);
}
// all good so return the token
return Response::json(compact('token'));
https://github.com/tymondesigns/jwt-auth/wiki/Creating-Tokens

Laravel JWTAuth::attempt($credentials) not working in Ubuntu Server

PROBLEM: JWTAuth::attempt($credentials) is working in my windows local machine. When user calls /userLogin by providing credentials(username & password), it verifies the credentials and creates a token for the user. But same code: JWTAuth::attempt($credentials) is NOT working when I deploy the project on to Ubuntu Server.
DESCRIPTION:
I am using tymondesigns/jwt-auth for implementing JSON Web Tokens in my Laravel 5.1 project. I have built 2 REST APIs: /userRegister & /userLogin.
Here is code for /userRegister in UserController.php:
public function userRegister(Request $request)
{
$validator = Validator::make($request->all(), [
'email' => 'required',
'username' => 'required',
'password' => 'required',
'country' => 'required',
'zip_code' => 'required',
'date_time' => 'required',
'gender' => 'required',
]);
try
{
if ($validator->fails())
throw new Exception($validator->errors(), 409);
$name = $request->input('name');
$email = $request->input('email');
$username = $request->input('username');
$password = bcrypt($request->input('password'));
$country = $request->input('country');
$zip_code = $request->input('zip_code');
$fb_login = $request->input('fb_login');
$registration_date = $request->input('date_time');
$gender = $request->input('gender');
$user_email = UserProfile::where('email','=',$email)->first();
if($user_email!=null)
{
throw new Exception("User with this email is already registered");
}
$check_username = UserProfile::where('username','=', $username)->first();
if ($check_username != null)
{
throw new Exception("User with this username is already registered. Please use different username");
}
$saveUser = new UserProfile();
$saveUser->name=$name;
$saveUser->email=$email;
$saveUser->username=$username;
$saveUser->password=bcrypt($password);
$saveUser->country=$country;
$saveUser->zipcode=$zip_code;
$saveUser->gender=$gender;
$saveUser->fb_login=$fb_login;
$saveUser->registration_date=$registration_date;
$build_trial_date = new Carbon($registration_date);
$trial_end_date = $build_trial_date->addDays(30);
$saveUser->trial_end_date=$trial_end_date;
$result = $saveUser->save();
if (!$result)
throw new Exception("Error in registration. Please try again.");
$user_id = $saveUser->id;
$loginUser = UserProfile::find($user_id);
$loginUser->update(['logged_in' => 1]);
return ResponseService::buildSuccessResponse("User registered successfully");
}
catch(Exception $e)
{
$data = [
'error' => true,
'result' => [
'status_code' => $e->getCode(),
'message' => $e->getMessage(),
]
];
$result = ResponseService::buildFailureResponse($data);
return $result;
}
}
As you can notice I am using bcrypt() for before saving password.
Now, here is code for /userLogin in UserController:
public function userLogin(Request $request)
{
// grab credentials from the request
$credentials = $request->only('username', 'password');
Log::info("username and password obtained from Request: ".json_encode($credentials));
try
{
if(JWTAuth::attempt($credentials)) // For Logging
{
Log::info("$ token = JWTAuth::attempt $ credentials Result: TRUE");
}else{
Log::info("$ token = JWTAuth::attempt $ credentials Result: FALSE");
}
// attempt to verify the credentials and create a token for the user
if (! $token = JWTAuth::attempt($credentials))
{
return response()->json(['error' => 'invalid_credentials'], 401);
}
} catch (JWTException $e) {
// something went wrong whilst attempting to encode the token
return response()->json(['error' => 'could_not_create_token'], 500);
}
Log::info("Generated token is: ".json_encode(compact('token')));
// all good so return the token
return response()->json(compact('token'));
}
/userRegistration Api is working both in my windows local m/c as well
as in Ubuntu server. Also bcrypt() on password is working in
it.
BUT, /userLogin is working in my windows local m/c but not working in
Ubuntu Server.
Help me solve this silent-dead-hidden error. TIA.
FURTHER DETAILS:
I have also cross-checked jwt.php file both in my windows and ubuntu server. They are having same configuratons. Also I have used php artisan jwt:generate on ubuntu server.
I finally could solve the problem when I went through the code again. Luckily I could noice that! Here is the mistake I did. At some point in time I have added this code bcrypt() like this:
$password = bcrypt($request->input('password'));
But I was already using bcrypt() before saving $password into the database.
$saveUser = new UserProfile();
$saveUser->password=bcrypt($password);
Since it was encrypting twice before saving to database, when I called /userLogin api, JWTAuth::attempt($credentials) was checking for credintials and it was not able to validate. So I removed bcrypt() at one place and now its working fine. [Solved].

Categories