symfony 4 app on heroku with remote database - heroku

I really need some help here hehe
Ok i got a symfony 4 application that is working perfectly in local environement.
I installed the app on heroku, but i want to access my Mysql database on my web hosting.
To be able to do that i had to install the Fixie app on heroku to have two ip adress and be able to whitelist those address for the remote access of my database.
The app is running good, but if i go to any links that have a call to do at the database i got a timeout.
I think the problem is in my index.php file, when installing Fixie you have to add code to the trust proxy
Heres what i have right now in my index.php file
<?php
use App\Kernel;
use Symfony\Component\Debug\Debug;
use Symfony\Component\HttpFoundation\Request;
require dirname(__DIR__).'/config/bootstrap.php';
if ($_SERVER['APP_DEBUG']) {
umask(0000);
Debug::enable();
}
$trustedProxies = $_SERVER['TRUSTED_PROXIES'] ?? $_ENV['TRUSTED_PROXIES'] ?? false;
$trustedProxies = $trustedProxies ? explode(',', $trustedProxies) : [];
if($_SERVER['APP_ENV'] == 'prod') $trustedProxies[] = $_SERVER['REMOTE_ADDR'];
if($trustedProxies) {
Request::setTrustedProxies($trustedProxies, Request::HEADER_X_FORWARDED_AWS_ELB);
}
if ($trustedHosts = $_SERVER['TRUSTED_HOSTS'] ?? $_ENV['TRUSTED_HOSTS'] ?? false) {
Request::setTrustedHosts([$trustedHosts]);
}
$kernel = new Kernel($_SERVER['APP_ENV'], (bool) $_SERVER['APP_DEBUG']);
$request = Request::createFromGlobals();
$response = $kernel->handle($request);
$response->send();
$kernel->terminate($request, $response);
Thats the log message i get when i try to access a page that have a call to the database
2019-11-28T22:13:12.218311+00:00 app[web.1]: [2019-11-28 22:12:42] request.INFO: Matched route "publicResultat". {"route":"publicResultat","route_parameters":{"_route":"publicResultat","_controller":"App\\Controller\\PublicController::index"},"request_uri":"https://jugement.herokuapp.com/public","method":"GET"} []
2019-11-28T22:13:12.218435+00:00 app[web.1]: [2019-11-28 22:12:42] security.INFO: Populated the TokenStorage with an anonymous Token. [] []
2019-11-28T22:13:12.220033+00:00 app[web.1]: [2019-11-28 22:13:12] request.CRITICAL: Uncaught PHP Exception Doctrine\DBAL\Exception\ConnectionException: "An exception occurred in driver: SQLSTATE[HY000] [2002] Connection timed out" at /app/vendor/doctrine/dbal/lib/Doctrine/DBAL/Driver/AbstractMySQLDriver.php line 93 {"exception":"[object] (Doctrine\\DBAL\\Exception\\ConnectionException(code: 0): An exception occurred in driver: SQLSTATE[HY000] [2002] Connection timed out at /app/vendor/doctrine/dbal/lib/Doctrine/DBAL/Driver/AbstractMySQLDriver.php:93, Doctrine\\DBAL\\Driver\\PDOException(code: 2002): SQLSTATE[HY000] [2002] Connection timed out at /app/vendor/doctrine/dbal/lib/Doctrine/DBAL/Driver/PDOConnection.php:31, PDOException(code: 2002): SQLSTATE[HY000] [2002] Connection timed out at /app/vendor/doctrine/dbal/lib/Doctrine/DBAL/Driver/PDOConnection.php:27)"} []
When you install fixie in heroku you have to add something this is the example they give for php but i don't understand how to do that in my symfony app
PHP cURL is the easiest way to get your PHP application working correctly with Fixie. Here’s how:
<?php
function proxyRequest() {
$fixieUrl = getenv("FIXIE_URL");
$parsedFixieUrl = parse_url($fixieUrl);
$proxy = $parsedFixieUrl['host'].":".$parsedFixieUrl['port'];
$proxyAuth = $parsedFixieUrl['user'].":".$parsedFixieUrl['pass'];
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_PROXY, $proxy);
curl_setopt($ch, CURLOPT_PROXYUSERPWD, $proxyAuth);
curl_close($ch);
}
$response = proxyRequest();
print_r($response);
?>
Hope that i am clear on my problem
any help would be very useful
I also found strange that i have no header present when the call is done
Request URL: https://jugement.herokuapp.com/public
Referrer Policy: no-referrer-when-downgrade
Thats all i have in the header

Related

Issue with PEM file while building a query using Laravel and Goutte

I'm building a website using Laravel 8 and Goutte 4. I'm trying to send a request to a website that requires authentication with a .pem file. In order to do so, I include the 'local_cert' param when creating the instance of http-client like this:
use Goutte\Client;
use Symfony\Component\HttpClient\HttpClient;
class Query
{
protected $client;
public function __construct() {
$this->client = (new Client(
HttpClient::create([
'timeout' => 30,
'local_cert' => //absolute path to the .pem file,
])
));
}
public function query() {
$this->client->request('GET', "https://palena.sii.cl/cvc_cgi/dte/of_solicita_folios");
}
}
This works perfectly well on my local server, but when I try it on the production server, I get an Exception: "Problem with the local SSL certificate". The .pem file being used is the same in development and production, and the php can read the file in the production server.
The full error in the laravel Log is:
[2020-12-02 21:32:30] production.ERROR: Problem with the local SSL certificate for "https://palena.sii.cl/cvc_cgi/dte/of_solicita_folios". {"userId":1,"exception":"[object] (Symfony\Component\HttpClient\Exception\TransportException(code: 0): Problem with the local SSL certificate for "https://palena.sii.cl/cvc_cgi/dte/of_solicita_folios". at /my/path/vendor/symfony/http-client/Chunk/ErrorChunk.php:65)
did you fixed? i only make this work with GuzzleHttp
$requestAuthentication = $clientAuth->request('GET', $urlAuthentication, [
'cert' => [$rutaPem, 'clave'],
'cookies' => $cookiesAuth,
]);

AWS S3 error when trying to upload file in Laravel app

I'm trying to get S3 set up with my Laravel app (which is running on my local machine) but I'm getting the following error when trying to upload an image.
$my_file = 'file.txt';
$handle = fopen($my_file, 'w') or die('Cannot open file: '.$my_file);
$data = 'Test data to see if this works!';
fwrite($handle, $data);
$storagePath = Storage::disk('s3')->put("uploads", $my_file, 'public');
This is the error I'm getting:
Error executing "PutObject" on "https://landlord-files.s3.eu-west-2.amazonaws.com/uploads"; AWS HTTP error: cURL error 60: SSL certificate problem: unable to get local issuer certificate (see http://curl.haxx.se/libcurl/c/libcurl-errors.html)

file_get_contents(): SSL operation failed with code 1. OpenSSL Error messages

In my Laravel project, I am using the laravelgooglemaps api by farhanwazir on my "contact us" page to display a fixed location.
Route for contactus page:
Route::get('/contactus', function () {
$config['center'] = 'California State University, Fullerton';
$config['zoom']='15';
$config['map_height'] = "300px";
$config['map_width'] = "300px";
$config['scrollwheel']= false;
GMaps::initialize($config);
$marker['position'] = 'California State University, Fullerton';
$marker['infowindow_content'] = 'Easywash Centre';
GMaps::add_marker($marker);
$map = GMaps::create_map();
return view('contactus')->with('map', $map); });
In my contactus.blade.php file:
{!! $map['html'] !!}
But sometimes when I load the "contact us" page I get the error:
ErrorException (E_WARNING)
file_get_contents(): SSL operation failed with code 1. OpenSSL Error messages: error:14090086:SSL routines:ssl3_get_server_certificate:certificate verify failed
Can anyone help me understand why I am getting such error and how it can be solved?
Try this:
$arrContextOptions=array(
"ssl"=>array(
"verify_peer"=>false,
"verify_peer_name"=>false,
),
);
file_get_contents($link, false, stream_context_create($arrContextOptions));
Just in case anyone wondering I solved this error by changing https:// to http:// .

Enable Debug Component in Symfony 2.3

Before opening a ticket in the symfony repository, I just wanted to check if I have missed something obvious.
I want to enable the debug component (for having these nice exception screens, etc..).
I just installed symfony using
composer create-project symfony/framework-standard-edition symfony 2.3.1
For testing purposes I added an exception to the WelcomeController:
class WelcomeController extends Controller
{
public function indexAction()
{
throw new \Exception("test");
/*
* The action's view can be rendered using render() method
* or #Template annotation as demonstrated in DemoController.
*
*/
return $this->render('AcmeDemoBundle:Welcome:index.html.twig');
}
}
Instead of showing me the (old) exception screen, I am just getting a 502 Bad Gateway from nginx.
app_dev.php:
//$loader = require_once __DIR__.'/../app/bootstrap.php.cache';
$loader = require_once __DIR__.'/../app/autoload.php';
Debug::enable(-1);
require_once __DIR__.'/../app/AppKernel.php';
$kernel = new AppKernel('dev', true);
//$kernel->loadClassCache();
Request::enableHttpMethodParameterOverride();
$request = Request::createFromGlobals();
$response = $kernel->handle($request);
$response->send();
$kernel->terminate($request, $response);
Update:
Handling PHP errors does work however:
IDoNotExist();
produces the gray symfony error screen.
Ok, the problem was an error in the nginx config.
The error log of nginx revealed the following:
2013/07/03 14:33:05 [error] 22792#0: *15 upstream sent too big header while reading response header from upstream, client: 127.0.0.1, server: localhost, request: "GET /test/symfony_2.3.1/web/app_dev.php HTTP/1.1", upstream: "fastcgi://127.0.0.1:9111", host: "localhost"
I fixed it with adding
fastcgi_buffers 16 16k;
fastcgi_buffer_size 32k;
for the server {} in the nginx config (for reference http://forum.nginx.org/read.php?2,188352).
This first occured with 2.3.0, 2.2.3 works without this fix.
Ticket related to this issue: https://github.com/symfony/symfony/issues/8413

Google URL Shortening API using PHP

Now I know this is a common topic that has been over the Internet especially StackOverflow. But what I do not have (or haven't yet seen) is a straight solution for the token being maintained over a session.
I'm using the Google APIs Client Library for PHP .
My Query:
I have one index.php where I fetch the user data (such as name) using the Google_Oauth2Service from the PHP client lib. The user is authenticated successfully and all goes well. Now I'd like to use the URL Shortening service and therefore I have a shorten.php where I have the code to try fetch the short URL. Some how this doesn't work.
index.php
//include google api files
require_once 'src/Google_Client.php';
require_once 'src/contrib/Google_Oauth2Service.php';
require_once 'src/contrib/Google_UrlshortenerService.php';
//start session
session_start();
$gClient = new Google_Client();
$gClient->setApplicationName('Test App');
$gClient->setClientId($google_client_id);
$gClient->setClientSecret($google_client_secret);
$gClient->setRedirectUri($google_redirect_url);
$gClient->setDeveloperKey($google_developer_key);
$google_oauthV2 = new Google_Oauth2Service($gClient);
....
....
Here I have started the session and made an object of the Google_Client. I have declared the client id, secret and all other details.
Then I get the access token on successful authentication and store it in the Session variable so that when I try to fetch the short url (using jQuery ajax) from shorten.php, I can use the existing token.
$_SESSION['token'] = $gClient->getAccessToken();
....
Now in shorten.php
session_start();
require_once 'src/Google_Client.php';
require_once 'src/contrib/Google_Oauth2Service.php';
require_once 'src/contrib/Google_UrlshortenerService.php';
$gClient = new Google_Client();
$gClient->setApplicationName('Test App');
$gClient->setClientId($google_client_id);
$gClient->setClientSecret($google_client_secret);
$gClient->setRedirectUri($google_redirect_url);
$gClient->setDeveloperKey($google_developer_key);
....
if (isset($_SESSION['token']) && $_SESSION['token']) {
// Set the access token from the session
$gClient->setAccessToken($_SESSION['token']);
$url_service = new Google_UrlshortenerService($gClient);
// Check if a URL has been passed
if (isset($_GET['url'])) {
$url = new Google_Url();
$url->longUrl = $_GET['url'];
$shortURL = $url_service->url->insert($url);
....
This is the exact line where the code breaks $shortURL = $url_service->url->insert($url); I was successful in getting the token using the Session variable and created a successful URL Service object. But just when I call the insert method, that's when it fails.
From the apache error logs :
husain#innovate:~/myprojects/web$ tail -1 /var/log/apache2/error.log | sed -e 's/\\n/\n/g'
[Thu Mar 28 00:42:35 2013] [error] [client 127.0.0.1] PHP Fatal error: Uncaught exception 'Google_ServiceException' with message 'Error calling POST https://www.googleapis.com/urlshortener/v1/url?key=AIzaSyCxfXP-xS-QYJw-7mM4SNG3EW9ryj_Oiv4: (401) Invalid Credentials' in /home/husain/myprojects/web/apps/src/io/Google_REST.php:66
Stack trace:
#0 /home/husain/myprojects/web/apps/src/io/Google_REST.php(36): Google_REST::decodeHttpResponse(Object(Google_HttpRequest))
#1 /home/husain/myprojects/web/apps/src/service/Google_ServiceResource.php(177): Google_REST::execute(Object(Google_HttpRequest))
#2 /home/husain/myprojects/web/apps/src/contrib/Google_UrlshortenerService.php(38): Google_ServiceResource->__call('insert', Array)
#3 /home/husain/myprojects/web/apps/shorten.php(44): Google_UrlServiceResource->insert(Object(Google_Url))
#4 {main}
thrown in /home/husain/myprojects/web/apps/src/io/Google_REST.php on line 66
When I dump the Google_Client variables on the index.php and shorten.php files, this is what I get.
index.php
Google_Client Object
(
[scopes:protected] => Array
(
)
[useObjects:protected] =>
[services:protected] => Array
(
[oauth2] => Array
(
[scope] => Array
(
[0] => https://www.googleapis.com/auth/userinfo.profile
[1] => https://www.googleapis.com/auth/userinfo.email
)
)
)
[authenticated:Google_Client:private] =>
)
shorten.php
object(Google_Client)#1 (4) {
["scopes":protected]=>
array(0) {
}
["useObjects":protected]=>
bool(false)
["services":protected]=>
array(1) {
["urlshortener"]=>
array(1) {
["scope"]=>
string(44) "https://www.googleapis.com/auth/urlshortener"
}
}
["authenticated":"Google_Client":private]=>
bool(false)
}
and both aint the same so I'm assuming that there is something not right here. Help or direction please.
You're not requesting the UrlShortener scope when authenticating, that's why it's failing.
To get the scope added, you can create an UrlshortenerService before authenticating in index.php, passing the same instance of the client, as in:
//start session
session_start();
$gClient = new Google_Client();
$gClient->setApplicationName('Test App');
$gClient->setClientId($google_client_id);
$gClient->setClientSecret($google_client_secret);
$gClient->setRedirectUri($google_redirect_url);
$gClient->setDeveloperKey($google_developer_key);
$google_oauthV2 = new Google_Oauth2Service($gClient);
$url_service = new Google_UrlshortenerService($gClient);
Alternatively, you can use setScopes to override the automatically generated scope

Resources