I'm using Guzzle within my Laravel app to make a request to /oauth/token/ as a login request and see to be getting connection refused
My code in my custom controller is:
public function login(Request $request)
{
$http = new \GuzzleHttp\Client();
try {
$response = $http->post("https://mixapp.test/oauth/token/", [
'form_params' => [
'grant_type' => 'password',
'client_id' => config('services.passport.client_id'),
'client_secret' => config('services.passport.client_secret'),
'username' => $request->username,
'password' => $request->password,
]
]);
return $response->getBody();
} catch (\GuzzleHttp\Exception\BadResponseException $e) {
if ($e->getCode() === 400) {
return response()->json('Invalid Request. Please enter a username or a password.', $e->getCode());
} else if ($e->getCode() === 401) {
return response()->json('Your credentials are incorrect. Please try again', $e->getCode());
}
return response()->json('Something went wrong on the server.', $e->getCode());
}
}
And the error seems to be:
local.ERROR: cURL error 7: Failed to connect to mixapp.test port 443: Connection refused (see http://curl.haxx.se/libcurl/c/libcurl-errors.html) {"exception":"[object] (GuzzleHttp\Exception\ConnectException(code: 0): cURL error 7: Failed to connect to mixapp.test port 443: Connection refused
Both are be on https, and I am using laravel valet.
Actually ended up solving this. Thinking a bit harder about it, I was just calling the same server from the controller, so I changed my guzzle request to:
$response = $http->post("https://127.0.0.1/oauth/token/", [...
Thanks SO for being my rubber duck :)
Related
I want to create social login using Google and Facebook. In the first step, I want to create Google Login. When I select the Google ID and Callback it shows me this error.
Laravel\Socialite\Two\InvalidStateException
http://localhost:8000/customer/login/google/callback?authuser=1&code=4%2F0AX4XfWgtwfNmX20WgsbTWXCO0joa1BrfjX0Iif1jqoxTqvT-AqwRVRgwyJwR95EuFlBx9Q&prompt=consent&scope=email%20profile%20openid%20https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fuserinfo.profile%20https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fuserinfo.email&state=e7PCC5OnNvtkQ6e7GBquKsTtAjWYiIuMdFZ477Kt
URL :
Route::get('/customer/login/google/callback', 'handleGoogleCallback')->name('callback.to.google');
Controller :
public function handleGoogleCallback() {
try {
$user = Socialite::driver('google')->user();
dd($user);
} catch (\Throwable $th) {
throw $th;
}
}
'google' => [
'client_id' => env('GOOGLE_CLIENT_ID'),
'client_secret' => env('GOOGLE_CLIENT_SECRET'),
'redirect' => 'http://localhost:8000/customer/login/google/callback',
],
GOOGLE_CLIENT_ID="xxxxxxxxxxxxx-xxxxxxxxxxxxxx.apps.googleusercontent.com"
GOOGLE_CLIENT_SECRET="GOCSPX-qzx7jVkboSS_xxxxxxxxxxxxx"
How to solve this problem??
Your state is incorrect. state is a parameter that laravel-socialite added to auth request once you did /redirect. Seems like you trying complete auth operation two+ times from just only google.com request. Retry auth from /redirect request.
PS. sorry for my English
actually i want to validate given token .. the validate code written in another lumen package. i have got some issues when i send request to validate token. i dont know why it's not working. cant use another api inside lumen ?
if i use that check token api in postman https://i.stack.imgur.com/kSpJt.png. it works fine. it's thrown error when i call that api inside other lumen package
this is what i got when use this api in postman https://i.stack.imgur.com/hfFzk.png
error log https://i.stack.imgur.com/ds0oR.png
<?php
namespace App\Helpers;
use App\Helpers\ResponseBuilder;
class check_customer_token_verification
{
public static function check($token, $vendor_id)
{
$client = new \GuzzleHttp\Client();
$result = $client->post('dev.adiswar-crm.local/customer/crm/v-1-0-0/check-token', [
'form_params' => [
'token' => isset($token)?$token:'',
'vendor_id' => $vendor_id,
]
]);
$res_data = json_decode($result->getBody()->getContents()); dd($res_data);
if ($res_data->http_code == 401) {
return ResponseBuilder::responseResult(400, $res_data->message);
}
return $res_data;
}
} ```
dump this api in postman. i got issue which is below
^ {#120
+"http_code": 400
+"message": """
Server error: `POST dev.adiswar-crm.local/customer/crm/v-1-0-0/check-token` resulted in a `500 Internal Server Error` response:
<!DOCTYPE html>
<html>
<head>
<meta name="robots" content="noindex,nofollow" />
<style>
(truncated...)
"""
}```
You need to define your form_params, though your code can work but I would also suggest using try catch blocks and adding your 401 exception in catch block (& other 400 in there), see the changes I have made
public static function check($token, $vendor_id)
{
try{
$client = new \GuzzleHttp\Client();
define("form_params", \GuzzleHttp\RequestOptions::FORM_PARAMS );
$guzzleResponse = $client->post('dev.adiswar-crm.local/customer/crm/v-1-0-0/check-token', [
'form_params' => [
'token' => isset($token) && !empty($token) ? $token : '',
'vendor_id' => $vendor_id,
]
]);
if ($guzzleResponse->getStatusCode() == 200) {
$result = json_decode($guzzleResponse->getBody(),true);
// dd($result);
}
return $result;
}catch(\GuzzleHttp\Exception\RequestException $e){
// Catch all 4XX errors
dd($e->getMessage, $e->getTraceAsString());
// To catch exactly error 401 use
if ($e->hasResponse()){
if ($e->getResponse()->getStatusCode() == '401') {
return ResponseBuilder::responseResult(400, $e->getMessage());
}
}
}catch(Exception $e){
//other errors
}
}
I am developing a Web application. In my app, I need to login user to the AWS cognito system. I can log in to the system successfully. But the only problem is when the username and password provided by the user are not valid, my Laravel framework kills the application returning 500 internal server status code. But I want to do something else when the username and password are not valid. I tried using try catch block, but it is not overriding the error. Please, see my code below.
try{
$client = new CognitoIdentityProviderClient([
'version' => 'latest',
'region' => env('AWS_REGION', '')
'credentials' => [
'key' => env('AWS_IAM_KEY', ''),
'secret' => env('AWS_IAM_SECRET', '')
]
]);
$result = $client->adminInitiateAuth([
'AuthFlow' => 'ADMIN_NO_SRP_AUTH',
'ClientId' => COGNITO_APP_CLIENT_ID,
'UserPoolId' => COGNITO_USER_POOL_ID,
'AuthParameters' => [
'USERNAME' => $request->email,
'PASSWORD' => $request->password,
],
]);
//Error thrown here if the username and password are not valid.
//continue
}
catch(Exception $e)
{
//I want to do something here if the error is thrown because of the invalid credentials without killing the app by throwing 500 status code.
}
As you can see in the above code if the user credentials are not valid, the SDK will throw the error. It will kill the app by returning 500 status code. I do not want to stop there. So, I used the try catch block to catch the error and continue in the code. But the try catch block is not catching the error as well.
This is the screenshot.
So, how can I stop the AWS sdk from stopping the application throwing 500 status code?
Finally, I found the solution. Laravel works with namespaces. So, instead of using just Exception in the try catch block, I needed to put "\" as a prefix. So the try catch becomes like this.
try{
//code
}
catch(\Exception $e) //pay attention to the "\"
{
}
I am using Laravel 5.5 with the AWS SDK for laravel (https://github.com/aws/aws-sdk-php-laravel).
I'm trying to do a simple request to establish that I'm connecting correctly. I believe I have my credentials all set and nothing points to that as an error.
Here is the function in my laravel controller that is being called:
public function testData(Request $request) {
$sdk = new Sdk([
'endpoint' => 'http://localhost:80',
'region' => 'us-east-1',
'version' => 'latest'
]);
$dynamodb = $sdk->createDynamoDb();
$marshaler = new Marshaler();
$tableName = 'funTalkDataStorage';
$params = [
'TableName' => $tableName
];
try {
$result = $dynamodb->query($params);
} catch (DynamoDbException $e) {
echo "Unable to query:\n";
echo $e->getMessage() . "\n";
}
}
The table 'funTalkDataStorage' does exist out on AWS already where there are two records already.
The thing that I'm not understanding is why I'm getting the following error from Laravel:
Aws \ Api \ Parser \ Exception \ ParserException
Error parsing JSON: Syntax error
being thrown by :
aws\aws-sdk-php\src\Api\Parser\PayloadParserTrait.php
The error is originating from the line in my code:
$result = $dynamodb->query($params);
I've been digging through the sdk and searching the web and I'm just not getting where the issue is. Any help would be marvalous!
Ok. My issue was that i was using port 80. It should have been port 8000.
I want to send a mail to the company's office mail(other than email field for login) when a candidate appy for the job posting
Controller function
public function ImmediateApply(Request $request) {
try {
$request['resume'] = $this->image->uploadImage($request->resume, 'resumes');
if (ImmediateApply::where('job_post_id', '=', $request->job_post_id)->where('email', '=', $request->email)->count() == 0) {
$application = ImmediateApply::create($request->all());
$job = JobPost::find($request->job_post_id);
$company = Company::find($job->company_id);
$company->notify(new JobApplication($job));
return response()->json([
'message' => 'You have applied successfully',
'code' => '201']);
}
} catch (Exception $e) {
return response()->json([
'message' => $e->getMessage(),
'code' => 400,
], 400);
}
}
company model
public function routeNotificationForMail() {
return $this->office_mail;
}
Now I'am getting the error
1.Failed to authenticate on smtp server with username "x" using 2
possible authenticators
2.CredentialsException in InstanceProfileProvider.php line 79: Error
retrieving credentials from the instance profile metadata server.
(Error creating resource: [message]
fopen(http://169.254.169.254/latest/meta-data/iam/security-credentials/):
failed to open stream: Connection timed out [file]
/var/www/html/jobs-website/laravel5.4/vendor/guzzlehttp/guzzle/src/Handler/StreamHandler.php
[line] 312)
But when i check in smtp online test, I'am recieving the mail correctly
Actually i don't know the reason for the 1st error.It doesn't persist now.
Changing
MAIL_DRIVER = ses
from
MAIL_DRIVER = smtp
solved the 2nd error.
now everything working fine.