ltsecurityinc安防产品在线商城代码

This commit is contained in:
2026-09-14 17:47:10 +08:00
parent 57d8444c15
commit 6a3c9c5bd8
14539 changed files with 1775310 additions and 0 deletions
@@ -0,0 +1,217 @@
<?php
/**
* Helper class for generating OAuth related credentials
*
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\TestFramework\Authentication;
use Magento\Framework\Exception\IntegrationException;
use Magento\Framework\Exception\LocalizedException;
use Magento\Framework\Oauth\Exception;
use Magento\TestFramework\Authentication\Rest\OauthClient;
use Magento\TestFramework\Helper\Bootstrap;
use OAuth\Common\Consumer\Credentials;
use Laminas\Stdlib\Exception\LogicException;
use Magento\Integration\Model\Integration;
/**
* Authentication Oauth helper
*/
class OauthHelper
{
/** @var array */
protected static $_apiCredentials;
/**
* Generate authentication credentials
*
* @param string $date consumer creation date
* @return array
* <pre>
* array (
* 'key' => 'ajdsjashgdkahsdlkjasldkjals', //consumer key
* 'secret' => 'alsjdlaskjdlaksjdlasjkdlas', //consumer secret
* 'verifier' => 'oiudioqueoiquweoiqwueoqwuii'
* 'consumer' => $consumer, // retrieved consumer Model
* 'token' => $token // retrieved token Model
* );
* </pre>
* @throws LocalizedException
* @throws Exception
*/
public static function getConsumerCredentials($date = null)
{
$integration = self::_createIntegration('all');
$objectManager = Bootstrap::getObjectManager();
/** @var $oauthService \Magento\Integration\Api\OauthServiceInterface */
$oauthService = $objectManager->get(\Magento\Integration\Api\OauthServiceInterface::class);
$consumer = $oauthService->loadConsumer($integration->getConsumerId());
$url = TESTS_BASE_URL;
$consumer->setCallbackUrl($url);
$consumer->setRejectedCallbackUrl($url);
if ($date !== null) {
$consumer->setCreatedAt($date);
}
$consumer->save();
$token = $objectManager->create(\Magento\Integration\Model\Oauth\Token::class);
$verifier = $token->createVerifierToken($consumer->getId())->getVerifier();
return [
'key' => $consumer->getKey(),
'secret' => $consumer->getSecret(),
'verifier' => $verifier,
'consumer' => $consumer,
'token' => $token
];
}
/**
* Create an access token to associated to a consumer to access APIs. No resources are available to this consumer.
*
* @return array comprising of token key and secret
* <pre>
* array (
* 'key' => 'ajdsjashgdkahsdlkjasldkjals', //token key
* 'secret' => 'alsjdlaskjdlaksjdlasjkdlas', //token secret
* 'oauth_client' => $oauthClient // OauthClient instance used to fetch the access token
* );
* </pre>
* @throws LocalizedException
* @throws Exception
* @throws \OAuth\Common\Http\Exception\TokenResponseException
*/
public static function getAccessToken()
{
$consumerCredentials = self::getConsumerCredentials();
$credentials = new Credentials($consumerCredentials['key'], $consumerCredentials['secret'], TESTS_BASE_URL);
$oAuthClient = new OauthClient($credentials);
$requestToken = $oAuthClient->requestRequestToken();
$accessToken = $oAuthClient->requestAccessToken(
$requestToken->getRequestToken(),
$consumerCredentials['verifier'],
$requestToken->getRequestTokenSecret()
);
/** TODO: Reconsider return format. It is not aligned with method name. */
return [
'key' => $accessToken->getAccessToken(),
'secret' => $accessToken->getAccessTokenSecret(),
'oauth_client' => $oAuthClient
];
}
/**
* Create an access token, tied to integration which has permissions to all API resources in the system.
*
* @param array $resources list of resources to grant to the integration
* @param \Magento\Integration\Model\Integration|null $integrationModel
* @return array
* <pre>
* array (
* 'key' => 'ajdsjashgdkahsdlkjasldkjals', //token key
* 'secret' => 'alsjdlaskjdlaksjdlasjkdlas', //token secret
* 'oauth_client' => $oauthClient // OauthClient instance used to fetch the access token
* 'integration' => $integration // Integration instance associated with access token
* );
* </pre>
* @throws LocalizedException
* @throws Exception
*/
public static function getApiAccessCredentials($resources = null, Integration $integrationModel = null)
{
if (!self::$_apiCredentials) {
$integration = $integrationModel === null ? self::_createIntegration($resources) : $integrationModel;
$objectManager = Bootstrap::getObjectManager();
/** @var \Magento\Integration\Api\OauthServiceInterface $oauthService */
$oauthService = $objectManager->get(\Magento\Integration\Api\OauthServiceInterface::class);
$oauthService->createAccessToken($integration->getConsumerId());
$accessToken = $oauthService->getAccessToken($integration->getConsumerId());
if (!$accessToken) {
throw new LogicException('Access token was not created.');
}
$consumer = $oauthService->loadConsumer($integration->getConsumerId());
$credentials = new Credentials($consumer->getKey(), $consumer->getSecret(), TESTS_BASE_URL);
/** @var $oAuthClient OauthClient */
$oAuthClient = new OauthClient($credentials);
self::$_apiCredentials = [
'key' => $accessToken->getToken(),
'secret' => $accessToken->getSecret(),
'oauth_client' => $oAuthClient,
'integration' => $integration,
];
}
return self::$_apiCredentials;
}
/**
* Forget API access credentials.
*/
public static function clearApiAccessCredentials()
{
self::$_apiCredentials = false;
}
/**
* Remove fs element with nested elements.
*
* @param string $dir
* @param bool $doSaveRoot
*/
protected static function _rmRecursive($dir, $doSaveRoot = false)
{
if (is_dir($dir)) {
foreach (glob($dir . '/*') as $object) {
if (is_dir($object)) {
self::_rmRecursive($object);
} else {
unlink($object);
}
}
if (!$doSaveRoot) {
rmdir($dir);
}
} else {
unlink($dir);
}
}
/**
* Create integration instance.
*
* @param array $resources
* @return \Magento\Integration\Model\Integration
* @throws LogicException
* @throws IntegrationException
*/
protected static function _createIntegration($resources)
{
$objectManager = Bootstrap::getObjectManager();
/** @var $integrationService \Magento\Integration\Api\IntegrationServiceInterface */
$integrationService = $objectManager->get(\Magento\Integration\Api\IntegrationServiceInterface::class);
$params = ['name' => 'Integration' . microtime()];
if ($resources === null || $resources == 'all') {
$params['all_resources'] = true;
} else {
$params['resource'] = $resources;
}
$integration = $integrationService->create($params);
$integration->setStatus(\Magento\Integration\Model\Integration::STATUS_ACTIVE)->save();
/** Magento cache must be cleared to activate just created ACL role. */
$varPath = realpath(BP . '/var');
if (!$varPath) {
throw new LogicException("Magento cache cannot be cleared after new ACL role creation.");
} else {
$cachePath = $varPath . '/cache';
if (is_dir($cachePath)) {
self::_rmRecursive($cachePath, true);
}
}
return $integration;
}
}
@@ -0,0 +1,40 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\TestFramework\Authentication\Rest;
use OAuth\Common\Http\Uri\UriInterface;
/**
* Custom Client implementation for cURL
*/
class CurlClient extends \OAuth\Common\Http\Client\CurlClient
{
/**
* @inheritdoc
*/
public function retrieveResponse(
UriInterface $endpoint,
$requestBody,
array $extraHeaders = [],
$method = 'POST'
) {
$this->setCurlParameters([CURLOPT_FAILONERROR => true]);
return parent::retrieveResponse($endpoint, $requestBody, $extraHeaders, $method);
}
/**
* @inheritdoc
*/
public function normalizeHeaders(&$headers)
{
array_walk(
$headers,
function (&$val, $key) {
$val = ucfirst(strtolower($key)) . ': ' . $val;
}
);
}
}
@@ -0,0 +1,296 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\TestFramework\Authentication\Rest;
use Magento\TestFramework\Helper\Bootstrap;
use OAuth\Common\Consumer\Credentials;
use OAuth\Common\Http\Client\ClientInterface;
use OAuth\Common\Http\Exception\TokenResponseException;
use OAuth\Common\Http\Uri\Uri;
use OAuth\Common\Http\Uri\UriInterface;
use OAuth\Common\Storage\TokenStorageInterface;
use OAuth\OAuth1\Service\AbstractService;
use OAuth\OAuth1\Signature\SignatureInterface;
use OAuth\OAuth1\Token\StdOAuth1Token;
use OAuth\OAuth1\Token\TokenInterface;
/**
* @SuppressWarnings(PHPMD.CouplingBetweenObjects)
*/
class OauthClient extends AbstractService
{
/**
* The maximum timeout for http request in seconds
*/
public const DEFAULT_TIMEOUT = 120;
/** @var string|null */
protected $_oauthVerifier = null;
/**
* @param Credentials $credentials
* @param ClientInterface|null $httpClient
* @param TokenStorageInterface|null $storage
* @param SignatureInterface|null $signature
* @param UriInterface|null $baseApiUri
*/
public function __construct(
Credentials $credentials,
ClientInterface $httpClient = null,
TokenStorageInterface $storage = null,
SignatureInterface $signature = null,
UriInterface $baseApiUri = null
) {
if (!isset($httpClient)) {
$httpClient = new \Magento\TestFramework\Authentication\Rest\CurlClient();
$httpClient->setTimeout(self::DEFAULT_TIMEOUT);
}
if (!isset($storage)) {
$storage = new \OAuth\Common\Storage\Memory();
}
if (!isset($signature)) {
$signature = new \Magento\TestFramework\Authentication\Rest\OauthClient\Signature($credentials);
}
parent::__construct($credentials, $httpClient, $storage, $signature, $baseApiUri);
}
/**
* @inheritDoc
*/
public function getRequestTokenEndpoint()
{
return new Uri(TESTS_BASE_URL . '/oauth/token/request');
}
/**
* @inheritDoc
*/
public function getAuthorizationEndpoint()
{
throw new \OAuth\Common\Exception\Exception(
'Magento REST API is 2-legged. Current operation is not available.'
);
}
/**
* Returns the access token API endpoint.
*
* @return UriInterface
*/
public function getAccessTokenEndpoint()
{
return new Uri(TESTS_BASE_URL . '/oauth/token/access');
}
/**
* Returns the TestModule1 Rest API endpoint.
*
* @return UriInterface
*/
public function getTestApiEndpoint()
{
$defaultStoreCode = Bootstrap::getObjectManager()->get(\Magento\Store\Model\StoreManagerInterface::class)
->getStore()->getCode();
return new Uri(TESTS_BASE_URL . '/rest/' . $defaultStoreCode . '/V1/testmodule1');
}
/**
* Parses the access token response and returns a TokenInterface.
*
* @return TokenInterface
* @param string $responseBody
*/
protected function parseAccessTokenResponse($responseBody)
{
return $this->_parseToken($responseBody);
}
/**
* Parses the request token response and returns a TokenInterface.
*
* @return TokenInterface
* @param string $responseBody
* @throws TokenResponseException
*/
protected function parseRequestTokenResponse($responseBody)
{
$data = $this->_parseResponseBody($responseBody);
if (isset($data['oauth_verifier'])) {
$this->_oauthVerifier = $data['oauth_verifier'];
}
return $this->_parseToken($responseBody);
}
/**
* Parse response body and create oAuth token object based on parameters provided.
*
* @param string $responseBody
* @return StdOAuth1Token
* @throws TokenResponseException
*/
protected function _parseToken($responseBody)
{
$data = $this->_parseResponseBody($responseBody);
$token = new StdOAuth1Token();
$token->setRequestToken($data['oauth_token']);
$token->setRequestTokenSecret($data['oauth_token_secret']);
$token->setAccessToken($data['oauth_token']);
$token->setAccessTokenSecret($data['oauth_token_secret']);
$token->setEndOfLife(StdOAuth1Token::EOL_NEVER_EXPIRES);
unset($data['oauth_token'], $data['oauth_token_secret']);
$token->setExtraParams($data);
return $token;
}
/**
* Parse response body and return data in array.
*
* @param string $responseBody
* @return array
* @throws \OAuth\Common\Http\Exception\TokenResponseException
*/
protected function _parseResponseBody($responseBody)
{
if (!is_string($responseBody)) {
throw new TokenResponseException("Response body is expected to be a string.");
}
parse_str($responseBody, $data);
if (null === $data || !is_array($data)) {
throw new TokenResponseException('Unable to parse response.');
} elseif (isset($data['error'])) {
throw new TokenResponseException("Error occurred: '{$data['error']}'");
}
return $data;
}
/**
* Retrieve oAuth verifier that was obtained during request token request.
*
* @return string
* @throws \OAuth\Common\Http\Exception\TokenResponseException
*/
public function getOauthVerifier()
{
if (empty($this->_oauthVerifier)) {
throw new TokenResponseException("oAuth verifier must be obtained during request token request.");
}
return $this->_oauthVerifier;
}
/**
* Builds the authorization header for an authenticated API request.
*
* Fixing this method since parent implementation from lib not sending the oauth_verifier
* when requesting access token.
*
* @param string $method
* @param UriInterface $uri the uri the request is headed
* @param \OAuth\OAuth1\Token\TokenInterface $token
* @param array|null $bodyParams
* @return string
*/
protected function buildAuthorizationHeaderForAPIRequest(
$method,
UriInterface $uri,
TokenInterface $token,
$bodyParams = null
) {
$this->signature->setTokenSecret($token->getAccessTokenSecret());
$parameters = $this->getBasicAuthorizationHeaderInfo();
if (isset($parameters['oauth_callback'])) {
unset($parameters['oauth_callback']);
}
$parameters = array_merge($parameters, ['oauth_token' => $token->getAccessToken()]);
$parameters = array_merge($parameters, $bodyParams);
$parameters['oauth_signature'] = $this->signature->getSignature($uri, $parameters, $method);
$authorizationHeader = 'OAuth ';
$delimiter = '';
foreach ($parameters as $key => $value) {
$authorizationHeader .= $delimiter . rawurlencode($key) . '="' . rawurlencode($value) . '"';
$delimiter = ', ';
}
return $authorizationHeader;
}
/**
* Builds the oAuth authorization header for an authenticated API request
*
* @param UriInterface $uri the uri the request is headed
* @param \OAuth\OAuth1\Token\TokenInterface $token
* @param string $tokenSecret used to verify the passed token
* @param array $bodyParams
* @param string $method HTTP method to use
* @return array
*/
public function buildOauthAuthorizationHeader($uri, $token, $tokenSecret, $bodyParams, $method = 'GET')
{
$uri = new Uri($uri);
$tokenObj = new StdOAuth1Token();
$tokenObj->setAccessToken($token);
$tokenObj->setAccessTokenSecret($tokenSecret);
$tokenObj->setEndOfLife(StdOAuth1Token::EOL_NEVER_EXPIRES);
return [
'Authorization: ' . $this->buildAuthorizationHeaderForAPIRequest($method, $uri, $tokenObj, $bodyParams)
];
}
/**
* Builds the bearer token authorization header
*
* @param string $token
* @return array
*/
public function buildBearerTokenAuthorizationHeader($token)
{
return [
'Authorization: Bearer ' . $token
];
}
/**
* Validates a Test REST api call access using oauth access token
*
* @param TokenInterface $token The access token.
* @param string $method HTTP method.
* @return array
* @throws TokenResponseException
*/
public function validateAccessToken($token, $method = 'GET')
{
//Need to add Accept header else Magento errors out with 503
$extraAuthenticationHeaders = ['Accept' => 'application/json'];
$this->signature->setTokenSecret($token->getAccessTokenSecret());
$authorizationHeader = [
'Authorization' => $this->buildAuthorizationHeaderForAPIRequest(
$method,
$this->getTestApiEndpoint(),
$token,
[]
),
];
$headers = array_merge($authorizationHeader, $extraAuthenticationHeaders);
$responseBody = $this->httpClient->retrieveResponse($this->getTestApiEndpoint(), [], $headers, $method);
return json_decode($responseBody);
}
/**
* @inheritDoc
*/
protected function getSignatureMethod()
{
return 'HMAC-SHA256';
}
}
@@ -0,0 +1,68 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\TestFramework\Authentication\Rest\OauthClient;
use OAuth\Common\Http\Uri\UriInterface;
/**
* Signature class for Magento REST API.
*/
class Signature extends \OAuth\OAuth1\Signature\Signature
{
/**
* @inheritDoc
*
* In addition to the original method, allows array parameters for filters.
*/
public function getSignature(UriInterface $uri, array $params, $method = 'POST')
{
$queryStringData = !$uri->getQuery() ? [] : array_reduce(
explode('&', $uri->getQuery()),
function ($carry, $item) {
list($key, $value) = explode('=', $item, 2);
$carry[rawurldecode($key)] = rawurldecode($value);
return $carry;
},
[]
);
$signatureData = [];
foreach (array_merge($queryStringData, $params) as $key => $value) {
$signatureData[rawurlencode($key)] = rawurlencode($value);
}
ksort($signatureData);
// determine base uri
$baseUri = $uri->getScheme() . '://' . $uri->getRawAuthority();
if ('/' == $uri->getPath()) {
$baseUri .= $uri->hasExplicitTrailingHostSlash() ? '/' : '';
} else {
$baseUri .= $uri->getPath();
}
$baseString = strtoupper($method) . '&';
$baseString .= rawurlencode($baseUri) . '&';
$baseString .= rawurlencode($this->buildSignatureDataString($signatureData));
return base64_encode($this->hash($baseString));
}
/**
* @inheritDoc
*/
protected function hash($data)
{
switch (strtoupper($this->algorithm)) {
case 'HMAC-SHA256':
return hash_hmac('sha256', $data, $this->getSigningKey(), true);
default:
return parent::hash($data);
}
}
}