Log in to a drupal 7 website with laravel - php

I've been trying to create a laravel login with users from a drupal 7 database. Since drupal 7 has his own encription method for passwords, the ones that come with laravel don't work, hence whenever there's a try to log in it always returns authentication failure.
{
$request->validate([
'mail' => 'required|string|email',
'pass' => 'required|string',
'remember_me' => 'boolean',
]);
//dd(hash('sha256',$request->pass));
$credentials = request(['mail', 'pass']);
if (!Auth::attempt(['mail' =>$request->mail, 'pass' => hash('sha256',$request->pass)])) {
return response()->json([
'message' => 'Unauthorized'], 401);
}
$user = $request->user();
$tokenResult = $user->createToken('Personal Access Token');
$token = $tokenResult->token;
if ($request->remember_me) {
$token->expires_at = Carbon::now()->addWeeks(1);
}
$token->save();
$user->api_token = $tokenResult->accessToken;
return response()->json($user);
}
This is my login method in the controller.
I don't have access at all to the drupal project.
I'm open for any idea.

If you navigate to includes/password.inc in your drupal directory, you will find a function named: user_check_password. This method can help you verify your plain text password against the hashed password.
So, the easiest way would be connecting laravel to the existing drupal database and make use of the password.inc file from drupal.

Related

Laravel Set Session or Token for External User Login Successfully - No User Database Only Api user

I am pulling User Information from an external site with external API. I have completed the user login route on the Laravel and I get the data from the controller file. There is no problem in terms of pulling and displaying data from an external user API link.
How to do token and session operation like regular Laravel user to the user logged in with external API without the database. Note that I can use the same token part of the user API token available
In addition, I don't want to transfer the information by assigning session between the controller each time the user was login. How do I assign tokens in all transactions after user login?
It comes to these controls via post method from login screen
public function loginData(Request $request)
{
$password = $request->password;
$email = $request->email;
$apiman = "Bearer {$this->accesstokenApi()}";
$client = new Client();
$response = $client->post('https://testapi.com/api/v3/Profile', [
'headers' =>
[
'cache-control' => 'no-cache',
'authorization' => $apiman,
'content-type' => 'application/json'
],
'json' =>
[
'Email' => $email,
'Password' => $password
],
]);
$data = json_decode((string) $response->getBody(), true);
if ($data['ResponseType']=="Ok") {
session()->put('token', $data);
return redirect('/user-detail');
} else {
return response()->json([
'success' => false,
'message' => 'Invalid Email or Password',
], 401);
}
}
User logged in OK . After that, what token should the machine give, or where can the session be given to that user in one place? Besides, if the user is logged in, how do I get him to see the home page instead of showing the login form again, just like in Laravel login processes ?
Maybe you can create new middleware that will check if there is a token in the session
Here is the example that you can use and adapt it based on your needs.
namespace App\Http\Middleware;
use Closure;
class Myauth
{
public function handle($request, Closure $next, $guard = null)
{
if(session()->has('token')) {
return $next($request);
} else {
return response('Unauthorized.', 401);
//OR return redirect()->guest('/');
}
}
}

ArgumentCountError in Laravel 5.8

I am trying to add social authentication to a Laravel 5.8 API project using socialite.
When trying to handle a social provide callback, the ArgumentCountError is thrown here
Too few arguments to function App\Http\Controllers\SocialAuthController::handleProviderCallback(), 0 passed and exactly 1 expected
The error is referring to the very first line of this code block
public function handleProviderCallback($provider)
{
// retrieve social user info
$socialUser = Socialite::driver($provider)->stateless()->user();
// check if social user provider record is stored
$userSocialAccount = SocialAccount::where('provider_id', $socialUser->id)->where('provider_name', $provider)->first();
if ($userSocialAccount) {
// retrieve the user from users store
$user = User::find($userSocialAccount->user_id);
// assign access token to user
$token = $user->createToken('Pramopro')->accessToken;
// return access token & user data
return response()->json([
'token' => $token,
'user' => (new UserResource($user))
]);
} else {
// store the new user record
$user = User::create([
'name' => $socialUser->name,
'username' => $socialUser->email,
'email_verified_at' => now()
]);
...
// assign passport token to user
$token = $user->createToken('******')->accessToken;
// return response
return response()->json(['token' => $token]);
}
}
Below is how I have set up other code. Frist in env I added
GOOGLE_CLIENT_ID=******
GOOGLE_CLIENT_SECRET=*******
GOOGLE_CALLBACK_URL=https://staging.appdomain.com/api/v1/user
Then modified web.php
Auth::routes(['verify' => true]);
Route::get('/auth/{provider}', 'SocialAuthController#redirectToProvider');
Route::get('/auth/{provider}/callback', 'SocialAuthController#handleProviderCallback');
Lastly in the google app, I added the uri path where users will be redirected to after successful authentication
https://staging.appdomain.com/api/v1/user
How do I fix this?
The callback uri that user should be redirected to after successful authentication was apparently not being cached. So running php artisan route:cache fixed it.

How to create own login method in laravel?

I am using passport package in my project. Everything is working fine. I need custom functionality in which I can login through provider_id instead of email and password.
The below code is working absolutely fine
$credentials = request(['email', 'password']);
if(!Auth::attempt($credentials))
return response()->json([
'status' => 'fail',
'message' => 'The given data was invalid.'
], 401);
$user = $request->user();
$tokenResult = $user->createToken('Personal Access Token');
$token = $tokenResult->token;
if ($request->remember_me)
$token->expires_at = Carbon::now()->addWeeks(1);
$token->save();
I want to have same functionality as like below
Auth::attempt($credentials)
But through provider_id, and I can use these input for login which are in same `users
name
provider
provider_id
can someone kindly guide me about that I would appreciate. Thank you.
Authenticate A User By ID
To log a user into the application by their ID, you may use the loginUsingId method. This method accepts the primary key of the user you wish to authenticate:
Auth::loginUsingId(1);
// Login and "remember" the given user...
Auth::loginUsingId(1, true);
Reference
You can make some changes in the same method or you can create your own custom login method as per your requirement.

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