how to get HTTPS headers from webhook requester - request-headers

I have a webhook to receive updates that I am trying to configure. I need to get the bearer token from the header, but I am not able to retrieve it. Can someone shed some light on this issue? I am stumped!
receiving url is https://example.com/receive
$data = file_get_contents("php://input",true);
$events= json_decode($data, true);

If you're looking for an OAuth bearer token these are usually transferred in the request HTTP Authorization header. In PHP these can be a little tricky to read since different web servers have different approaches to reading the Authorization header.
There's a good example of how to read a bearer token in this answer. Copied here for convenience:
<?PHP
/**
* Get hearder Authorization
* */
function getAuthorizationHeader() {
$headers = null;
if (isset($_SERVER['Authorization'])) {
$headers = trim($_SERVER["Authorization"]);
} else if (isset($_SERVER['HTTP_AUTHORIZATION'])) { //Nginx or fast CGI
$headers = trim($_SERVER["HTTP_AUTHORIZATION"]);
} elseif (function_exists('apache_request_headers')) {
$requestHeaders = apache_request_headers();
// Server-side fix for bug in old Android versions (a nice side-effect of this fix means we don't care about capitalization for Authorization)
$requestHeaders = array_combine(array_map('ucwords', array_keys($requestHeaders)), array_values($requestHeaders));
if (isset($requestHeaders['Authorization'])) {
$headers = trim($requestHeaders['Authorization']);
}
}
return $headers;
}
/**
* get access token from header
* */
function getBearerToken() {
$headers = getAuthorizationHeader();
// HEADER: Get the access token from the header
if (!empty($headers)) {
if (preg_match('/Bearer\s(\S+)/', $headers, $matches)) {
return $matches[1];
}
}
return null;
}
?>

Related

Laravel Unit Testing - add cookie to request?

I want to send a cookie with json POST:
public function testAccessCookie()
{
$response = $this->json('POST', route('publications'))->withCookie(Cookie::create('test'));
//some asserts
}
publications route has some middleware:
public function handle($request, Closure $next)
{
Log::debug('cookie', [$request->cookies]);
//cookie validation
return $next($request);
}
But while running testAccessCookie(), there is [null] inside log. No cookies attached.
What's wrong?
There is no such problem with real (in-browser) requests.
You can add cookies to calls in tests:
$cookies = ['test' => 'value'];
$response = $this->call('POST', route('publications'), [], $cookies);
See https://laravel.com/api/5.4/Illuminate/Foundation/Testing/Concerns/MakesHttpRequests.html#method_call
However you will run into a cookie encryption problem. You can temporarily disable cookies during testing with:
use Illuminate\Cookie\Middleware\EncryptCookies;
/**
* #param array|string $cookies
* #return $this
*/
protected function disableCookiesEncryption($name)
{
$this->app->resolving(EncryptCookies::class,
function ($object) use ($name)
{
$object->disableFor($name);
});
return $this;
}
Adding $this->disableCookiesEncryption('test'); at the start of the test.
You may need to add headers to specify a json response.
This should work in recent versions (Laravel 6):
Either:
$this->disableCookieEncryption();
or:
$cookies = ['test' => encrypt('value', false)];
$response = $this->call('POST', route('publications'), [], $cookies);
Since Laravel 5.2 you get the \App\Http\Middleware\EncryptCookies::class middleware defined by default in the web middleware group and it will set all unencrypted cookies to null.
Unfortunately all cookies you send with $request->call(), $request->get() and $request->post() in unit testing are usually unencrypted and nothing in the official documentation tells you they need to be encrypted.
If you don't want to call $request->disableCookieEncryption() everytime, as a permanent solution you can simply redefine the isDisabled() method in App\Http\Middleware\EncryptCookies.php to ignore cookies encryption during unit testing.
Here is the implementation I made for Laravel 6.x, it should work on earlier versions too.
<?php
namespace App\Http\Middleware;
use Illuminate\Cookie\Middleware\EncryptCookies as Middleware;
class EncryptCookies extends Middleware
{
/**
* The names of the cookies that should not be encrypted.
*
* #var array
*/
protected $except = [
//
];
public function isDisabled($name)
{
if (app()->runningUnitTests()) {
return true; // Disable cookies encryption/decryption during unit testing
}
return parent::isDisabled($name);
}
}

Drupal 8 Class 'Drupal\Core\Session\AccountInterface' not found

I am trying to write a custom php script in my Drupal site root that checks if the user is logged in. To check this I import bootstrap.inc. However when I do this it throws me this error
This is the code of the php script in my site root:
<?php
require_once './core/includes/bootstrap.inc';
drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);
global $user;
var_dump($user->uid);
?>
Anyone has a solution to this?
To bootstrap Drupal 8, you need different code. Drupal 8 doesn't have any drupal_bootstrap() function, so the code you are using would throw a PHP error.
You can use authorize.php as guideline to write your own script.
use Drupal\Core\DrupalKernel;
use Symfony\Component\HttpKernel\Exception\HttpExceptionInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
$autoloader = (require_once 'autoload.php');
try {
$request = Request::createFromGlobals();
$kernel = DrupalKernel::createFromRequest($request, $autoloader, 'prod');
$kernel->prepareLegacyRequest($request);
} catch (HttpExceptionInterface $e) {
$response = new Response('', $e->getStatusCode());
$response
->prepare($request)
->send();
exit;
}
\Drupal::moduleHandler()
->addModule('system', 'core/modules/system');
\Drupal::moduleHandler()
->addModule('user', 'core/modules/user');
\Drupal::moduleHandler()
->load('system');
\Drupal::moduleHandler()
->load('user');
$account = \Drupal::service('authentication')
->authenticate($request);
if ($account) {
\Drupal::currentUser()
->setAccount($account);
if (\Drupal::currentUser()->isAuthenticated() {
// The user is logged-in.
}
}
I fixed this by using a complete different approach. I wrote a module which sets a cookie on the moment that the user logs in to drupal (I use the hook_user_login for this). When the user logs out I delete that cookie (I use the hook_user_logout for this). This is the code of my test.module:
/**
* #param $account
*/
function intersoc_content_user_login($account)
{
setcookie("user", "loggedin", time() + (86400 * 30),"/");
}
/**
* #param $account
*/
function intersoc_content_user_logout($account)
{
if (isset($_COOKIE['user']))
{
unset($_COOKIE['user']);
setcookie('user', '', time() - 3600, '/'); //Clearing cookie
}
}
Then in my custom script in the site root I check if the cookie is set. When the cookie exists => The user is logged in. If the cookie doesn't exist then the user isn't logged in. The isLoggedIn() function below:
/**
* #return bool which indicates if the user is logged in or not
*/
private function isLoggedIn()
{
if(isset($_COOKIE["user"]))
{
return TRUE;
}
else
{
return FALSE;
}
}
It isn't the most beautiful solution, but it works!!!

Google Calendar Server to Server

I use to make appointments a calendar based on FULLCALENDAR with backup of the rdv in a database mysql on my own local server. So far, so good. I wish I could synchronize the rdvs thus taken, on the google calendar and inversely be able to import into my database mysql the rdvs taken on the account of google on line.
I tried to understand and read the API doc of google calendar here and here
I only get error messages.
I tried to do it directly in fullcalendar but the calendar must be declared in public, something I can not do.
The ideal would be to be able to make server calls in php (login and password of google clandier backup in local mysql database), for which I create my API key and a service account, but again I do not get only error messages.
Would there be a link or a really functional tutorial that I could use to learn
I tried with this link but never succeeded
thanks in advance.
EDIT : I try this.
quickstart.php
<?php
require_once __DIR__ . '/vendor/autoload.php';
define('APPLICATION_NAME', 'Google Calendar API PHP Quickstart');
define('CREDENTIALS_PATH', '~/.credentials/calendar-php-quickstart.json');
define('CLIENT_SECRET_PATH', __DIR__ . '/client_id.json');
// If modifying these scopes, delete your previously saved credentials
// at ~/.credentials/calendar-php-quickstart.json
define('SCOPES', implode(' ', array(
Google_Service_Calendar::CALENDAR_READONLY)
));
if (php_sapi_name() != 'cli') {
throw new Exception('This application must be run on the command line.');
}
/**
* Returns an authorized API client.
* #return Google_Client the authorized client object
*/
function getClient() {
$client = new Google_Client();
$client->setApplicationName(APPLICATION_NAME);
$client->setScopes(SCOPES);
$client->setAuthConfig(CLIENT_SECRET_PATH);
$client->setAccessType('offline');
// Load previously authorized credentials from a file.
$credentialsPath = expandHomeDirectory(CREDENTIALS_PATH);
if (file_exists($credentialsPath)) {
$accessToken = json_decode(file_get_contents($credentialsPath), true);
} else {
// Request authorization from the user.
$authUrl = $client->createAuthUrl();
printf("Open the following link in your browser:\n%s\n", $authUrl);
print 'Enter verification code: ';
$authCode = trim(fgets(STDIN));
// Exchange authorization code for an access token.
$accessToken = $client->fetchAccessTokenWithAuthCode($authCode);
// Store the credentials to disk.
if(!file_exists(dirname($credentialsPath))) {
mkdir(dirname($credentialsPath), 0700, true);
}
file_put_contents($credentialsPath, json_encode($accessToken));
printf("Credentials saved to %s\n", $credentialsPath);
}
$client->setAccessToken($accessToken);
// Refresh the token if it's expired.
if ($client->isAccessTokenExpired()) {
$client->fetchAccessTokenWithRefreshToken($client->getRefreshToken());
file_put_contents($credentialsPath, json_encode($client->getAccessToken()));
}
return $client;
}
/**
* Expands the home directory alias '~' to the full path.
* #param string $path the path to expand.
* #return string the expanded path.
*/
function expandHomeDirectory($path) {
$homeDirectory = getenv('HOME');
if (empty($homeDirectory)) {
$homeDirectory = getenv('HOMEDRIVE') . getenv('HOMEPATH');
}
return str_replace('~', realpath($homeDirectory), $path);
}
// Get the API client and construct the service object.
$client = getClient();
$service = new Google_Service_Calendar($client);
// Print the next 10 events on the user's calendar.
$calendarId = 'primary';
$optParams = array(
'maxResults' => 10,
'orderBy' => 'startTime',
'singleEvents' => TRUE,
'timeMin' => date('c'),
);
$results = $service->events->listEvents($calendarId, $optParams);
if (count($results->getItems()) == 0) {
print "No upcoming events found.\n";
} else {
print "Upcoming events:\n";
foreach ($results->getItems() as $event) {
$start = $event->start->dateTime;
if (empty($start)) {
$start = $event->start->date;
}
printf("%s (%s)\n", $event->getSummary(), $start);
}
}
php quickstart.php
PHP Fatal error: Uncaught InvalidArgumentException: missing the required redirect URI in /Users/krislec/Desktop/vendor/google/auth/src/OAuth2.php:648
Stack trace:
#0 /Users/krislec/Desktop/vendor/google/apiclient/src/Google/Client.php(340): Google\Auth\OAuth2->buildFullAuthorizationUri(Array)
#1 /Users/krislec/Desktop/quickstart.php(36): Google_Client->createAuthUrl()
#2 /Users/krislec/Desktop/quickstart.php(75): getClient()
#3 {main}
thrown in /Users/krislec/Desktop/vendor/google/auth/src/OAuth2.php on line 648
Fatal error: Uncaught InvalidArgumentException: missing the required redirect URI in /Users/krislec/Desktop/vendor/google/auth/src/OAuth2.php:648
Stack trace:
#0 /Users/krislec/Desktop/vendor/google/apiclient/src/Google/Client.php(340): Google\Auth\OAuth2->buildFullAuthorizationUri(Array)
#1 /Users/krislec/Desktop/quickstart.php(36): Google_Client->createAuthUrl()
#2 /Users/krislec/Desktop/quickstart.php(75): getClient()
#3 {main}
thrown in /Users/krislec/Desktop/vendor/google/auth/src/OAuth2.php on line 648

Header HTTP apikey missing token authentication

I'm trying to authenticate users via ApiToken Authentication. The problem I'm facing right now is that I don't know how to retrieve the header Apikey just created that contains the token for the logged in user.
After I authenticate the user, I generate for him a token and then I tried to set in Apikey HTTP Header that specific token in order to use it in my api. But after I set it, when I try to access an url from api, the Apikey header is missing.
local.web.com/api/login
public function loginAction(Request $request)
{
(...)
$tokenUser = $serviceUser->generateToken($username);
$request->headers->add(array('apikey' => $tokenUser));
$response = new Response($request);
$response->send();
return $response;
}
local.web.com/api/list/products
public function createToken(Request $request, $providerKey)
{
$apiToken = $request->headers->get('apikey');
return new PreAuthenticatedToken(
'anon.',
$apiToken,
$providerKey
);
}
The HTTP Header Apikey is missing.
Any advice?

Sending a HTTP Post from magento 1.6 after customer registration?

can anyone point me in the right direction I need to send a HTTP post when a customer registers and or makes a purchase from Magento to a third part server ?
It will be the basic information like name, address, postcode , email ect.
Not sure where to start ?
Many thanks
$client = new Varien_Http_Client('http://www.example.com/');
$client->setMethod(Varien_Http_Client::POST);
$client->setParameterPost('name', $name);
$client->setParameterPost('address', $address);
//more parameters
try{
$response = $client->request();
if ($response->isSuccessful()) {
echo $response->getBody();
}
} catch (Exception $e) {
}

Resources