Skip to content

Commit

Permalink
Merge pull request #17 from socketlabs/usr/mike.boshuyzen/Add-api-key…
Browse files Browse the repository at this point in the history
…-parser

Usr/mike.boshuyzen/add api key parser
  • Loading branch information
david-schrenker authored May 22, 2023
2 parents 61f060e + 90cebc7 commit 2c4e91b
Show file tree
Hide file tree
Showing 17 changed files with 1,157 additions and 28 deletions.
16 changes: 16 additions & 0 deletions .vs/VSWorkspaceState.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
{
"ExpandedNodes": [
"",
"\\InjectionApi",
"\\InjectionApi\\Examples",
"\\InjectionApi\\Examples\\ExampleCode",
"\\InjectionApi\\Examples\\ExampleCode\\Basic",
"\\InjectionApi\\Examples\\Index",
"\\InjectionApi\\Examples\\Index\\Js",
"\\InjectionApi\\src",
"\\InjectionApi\\src\\Core",
"\\InjectionApi\\src\\Core\\Models"
],
"SelectedNode": "\\InjectionApi\\Examples\\Index\\Js\\Index.js",
"PreviewInSolutionExplorer": false
}
Binary file added .vs/slnx.sqlite
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Empty file.
972 changes: 972 additions & 0 deletions .vs/socketlabs-php/config/applicationhost.config

Large diffs are not rendered by default.

Binary file added .vs/socketlabs-php/v17/.suo
Binary file not shown.
Binary file added .vs/socketlabs-php/v17/TestStore/0/000.testlog
Binary file not shown.
Binary file added .vs/socketlabs-php/v17/TestStore/0/testlog.manifest
Binary file not shown.
46 changes: 46 additions & 0 deletions InjectionApi/src/Core/ApiKeyParseResult.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
<?php

namespace Socketlabs\Core;

/**
* A code describing the result of an attempt to parse an Api key.
*/
abstract class ApiKeyParseResult
{
/// <summary>
/// No result could be produced.
/// </summary>
const None = "None";
/// <summary>
/// The key was found to be the improper length.
/// </summary>
const InvalidKeyLength = "InvalidKeyLength";
/// <summary>
/// The key was found to be blank or invalid.
/// </summary>
const InvalidEmptyOrWhitespace = "InvalidEmptyOrWhitespace";
/// <summary>
/// The key was found to be blank or invalid.
/// </summary>
const Invalid = "Invalid";
/// <summary>
/// The public portion of the key was unable to be parsed.
/// </summary>
const InvalidUnableToExtractPublicPart = "InvalidUnableToExtractPublicPart";
/// <summary>
/// The secret portion of the key was unable to be parsed.
/// </summary>
const InvalidUnableToExtractSecretPart = "InvalidUnableToExtractSecretPart";
/// <summary>
/// The public portion of the key has an invalid length.
/// </summary>
const InvalidPublicPartLength = "InvalidPublicPartLength";
/// <summary>
/// The secret portion of the key has an invalid length.
/// </summary>
const InvalidSecretPartLength = "InvalidSecretPartLength";
/// <summary>
/// Key was successfully parsed.
/// </summary>
const Success = "Success";
}
61 changes: 61 additions & 0 deletions InjectionApi/src/Core/ApiKeyParser.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
<?php
namespace Socketlabs\Core;
/**
* Contains the method for parsing the Api Key.
*/
class ApiKeyParser {

/** Parse the API key to determine what kind of key was provided
. */
public function parse($wholeApiKey)
{

if ($wholeApiKey == null || trim($wholeApiKey) == '')
{
$result = ApiKeyParseResult::InvalidEmptyOrWhitespace;
return $result;
}

if (strlen($wholeApiKey) !== 61)
{
$result = ApiKeyParseResult::InvalidKeyLength;
return $result;
}

$splitPosition = strpos($wholeApiKey, '.');

if ($splitPosition === false)
{
$result = ApiKeyParseResult::Invalid;
return $result;
}

//extract the public part
$maxCount = min(50, strlen($wholeApiKey));

if ($splitPosition === false)
{
$result = ApiKeyParseResult::InvalidUnableToExtractPublicPart;
return $result;
}

$publicPart = substr($wholeApiKey,0, $splitPosition);

if (strlen($publicPart) !== 20)
{
$result = ApiKeyParseResult::InvalidPublicPartLength;
return $result;
}

$privatePart = substr($wholeApiKey, ($splitPosition + 1), strlen($wholeApiKey));

if (strlen($privatePart) !== 40)
{
$result = ApiKeyParseResult::InvalidSecretPartLength;
return $result;
}

$result = ApiKeyParseResult::Success;
return $result;
}
}
80 changes: 52 additions & 28 deletions InjectionApi/src/SocketLabsClient.php
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ class SocketLabsClient{
private $serverId;
private $apiKey;

const VERSION = "1.2.2";
const VERSION = "1.4.2";
public $version = self::VERSION;

/**
Expand Down Expand Up @@ -66,10 +66,28 @@ public function send($message){
$validationResult = Core\SendValidator::validateMessage($message);
if($validationResult->result != \Socketlabs\SendResult::Success) return $validationResult;


$factory = new Core\InjectionRequestFactory($this->serverId, $this->apiKey);
$newRequest = $factory->generateRequest($message);

$options = $this->createStreamOptions($newRequest);

$apiKeyParser = new Core\ApiKeyParser();

$parseResult = $apiKeyParser->parse($this->apiKey);

$options;

if ($parseResult === Core\ApiKeyParseResult::Success)
{
$options = $this->createStreamOptions($newRequest, $this->apiKey);
}
else {

$options = $this->createStreamOptions($newRequest, '');
}

$debug_export = var_export($options, true);
error_log($debug_export);

$retrySettings = new RetrySettings($this->numberOfRetries);
$retryHandler = new Core\RetryHandler($options, $this->endpointUrl, $retrySettings);
Expand All @@ -93,38 +111,44 @@ private function setUserAgent(){
* Helper function to create the stream options
* @param $injectionRequest
*/
private function createStreamOptions($injectionRequest){
$http = array(
'method' => 'POST',
'header' => 'Content-type: application/json',
'content' => json_encode($injectionRequest),
'timeout' => $this->requestTimeout
);

//proxy not enabled, return these simple options
if($this->proxyUrl == null){
return array('http' => $http);
}
private function createStreamOptions($injectionRequest, $bearerToken){

$header = array('Content-type: application/json');
if (strlen($bearerToken) > 0) {
$header = array('Content-type: application/json', 'Authorization: Bearer '.$bearerToken);
$injectionRequest->ApiKey = '';
}
$http = array(
'method' => 'POST',
'header' => $header,
'content' => json_encode($injectionRequest),
'timeout' => $this->requestTimeout
);

//proxy not enabled, return these simple options
if($this->proxyUrl == null){
return array('http' => $http);
}

//shape proxy url to use 'tcp'
$tcpUrl = str_replace('https', 'tcp', $this->proxyUrl);
$tcpUrl = str_replace('http', 'tcp', $tcpUrl);
//set proxy
$http += ['proxy' => $tcpUrl];

//include ssl options
return array(
"http" => $http
// If you are having trouble configuring a proxy tool such as fiddler, this can be a quick fix,
// but it is not recommended for production. The best way is to configure the appropriate certificate
// authority property in your php.ini, for example: 'openssl.cafile'

//Proxy Quick Fix:
//,
//"ssl"=> array(
// "verify_peer"=>false,
// "verify_peer_name"=>false,
//)
);
//include ssl options
return array(
"http" => $http
// If you are having trouble configuring a proxy tool such as fiddler, this can be a quick fix,
// but it is not recommended for production. The best way is to configure the appropriate certificate
// authority property in your php.ini, for example: 'openssl.cafile'

//Proxy Quick Fix:
//,
//"ssl"=> array(
// "verify_peer"=>false,
// "verify_peer_name"=>false,
//)
);
}
}
3 changes: 3 additions & 0 deletions InjectionApi/src/includes.php
Original file line number Diff line number Diff line change
@@ -1,9 +1,12 @@
<?php
if (!defined('SOCKETLABS_INJECTION_API_ROOT_PATH')) define('SOCKETLABS_INJECTION_API_ROOT_PATH', dirname(__DIR__));

include_once(SOCKETLABS_INJECTION_API_ROOT_PATH . "/src/Core/ApiKeyParser.php");
include_once(SOCKETLABS_INJECTION_API_ROOT_PATH . "/src/Core/ApiKeyParseResult.php");
include_once(SOCKETLABS_INJECTION_API_ROOT_PATH . "/src/Core/InjectionRequest.php");
include_once(SOCKETLABS_INJECTION_API_ROOT_PATH . "/src/Core/RetryHandler.php");
include_once(SOCKETLABS_INJECTION_API_ROOT_PATH . "/src/Core/InjectionRequestFactory.php");
include_once(SOCKETLABS_INJECTION_API_ROOT_PATH . "/src/Core/ApiKeyParser.php");
include_once(SOCKETLABS_INJECTION_API_ROOT_PATH . "/src/Core/InjectionResponseParser.php");
include_once(SOCKETLABS_INJECTION_API_ROOT_PATH . "/src/Core/SendValidator.php");

Expand Down
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -199,6 +199,7 @@ For more information about AMP please see [AMP Project](https://amp.dev/document

<a name="version"></a>
# Version
* 1.4.2 - Adding API Key Authorization
* 1.4.0 - Adding Metadata and Tags
* 1.2.1 - Adding optional retry logic for Http requests. If configured, the request will retry when certain 500 errors occur (500, 502, 503, 504)
* 1.1.2 - Add support of PHP 8.0
Expand Down
6 changes: 6 additions & 0 deletions composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,12 @@
"email": "developers@socketlabs.com",
"homepage": "https://www.socketlabs.com",
"role": "Developer/Contributor"
},
{
"name": "Mike Boshuyzen",
"email": "developers@socketlabs.com",
"homepage": "https://www.socketlabs.com",
"role": "Developer"
}
],
"require": {
Expand Down

0 comments on commit 2c4e91b

Please sign in to comment.