Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

OAuth2.0 #4102

Draft
wants to merge 16 commits into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
82 changes: 82 additions & 0 deletions app/code/core/Mage/Api2/Model/Auth/Adapter/Oauth2.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
<?php
/**
* OpenMage
*
* This source file is subject to the Open Software License (OSL 3.0)
* that is bundled with this package in the file LICENSE.txt.
* It is also available at https://opensource.org/license/osl-3-0-php
*
* @category Mage
* @package Mage_Api2
* @license https://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
*/

/**
* OAuth2 Authentication adapter
*
* @category Mage
* @package Mage_Api2
*/
class Mage_Api2_Model_Auth_Adapter_Oauth2 extends Mage_Api2_Model_Auth_Adapter_Abstract
{
/**
* Process request and figure out an API user type and its identifier
*
* Returns stdClass object with two properties: type and id
*
* @return stdClass
*/
public function getUserParams(Mage_Api2_Model_Request $request)
{
$userParamsObj = (object) ['type' => null, 'id' => null];

try {
$token = $this->_validateToken($request);
$userType = $token->getUserType();

if ($userType === 'admin') {
$userParamsObj->id = $token->getAdminId();
} else {
$userParamsObj->id = $token->getCustomerId();
}
$userParamsObj->type = $userType;
} catch (Exception $e) {
throw new Mage_Api2_Exception($e->getMessage(), Mage_Api2_Model_Server::HTTP_UNAUTHORIZED);
}

return $userParamsObj;
}

/**
* Validate the OAuth2 token
*
* @return Mage_Oauth2_Model_AccessToken
* @throws Exception
*/
protected function _validateToken(Mage_Api2_Model_Request $request)
{
$authorizationHeader = $request->getHeader('Authorization');
if (!$authorizationHeader || strpos($authorizationHeader, 'Bearer ') !== 0) {
throw new Exception('Missing or invalid Authorization header');
}

$accessToken = substr($authorizationHeader, 7);
$token = Mage::getModel('oauth2/accessToken')->load($accessToken, 'access_token');
if (!$token->getId() || $token->getExpiresIn() < time() || $token->getRevoked()) {
throw new Exception('Invalid or expired access token');
}

return $token;
}

/**
* Check if request contains authentication info for adapter
*
* @return bool
*/
public function isApplicableToRequest(Mage_Api2_Model_Request $request)
{
$headerValue = $request->getHeader('Authorization');
return $headerValue && strtolower(substr($headerValue, 0, 7)) === 'bearer ';
}
}
6 changes: 6 additions & 0 deletions app/code/core/Mage/Api2/etc/config.xml
Original file line number Diff line number Diff line change
Expand Up @@ -97,6 +97,12 @@
<enabled>1</enabled>
<order>10</order>
</oauth>
<oauth2 module="api2" translate="label">
<model>api2/auth_adapter_oauth2</model>
<label>OAuth2</label>
<enabled>1</enabled>
<order>20</order>
</oauth2>
</auth_adapters>
<user_types>
<admin>
Expand Down
21 changes: 21 additions & 0 deletions app/code/core/Mage/Oauth2/Block/Adminhtml/Client.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
<?php

/**
* OAuth2 Client Admin Grid Container
*/
class Mage_Oauth2_Block_Adminhtml_Client extends Mage_Adminhtml_Block_Widget_Grid_Container
{
/**
* Constructor
*/
public function __construct()
{
$this->_blockGroup = 'oauth2';
$this->_controller = 'adminhtml_client';

$this->_headerText = $this->__('Manage OAuth2 Clients');
$this->_addButtonLabel = $this->__('Add New Client');

parent::__construct();
}
}
78 changes: 78 additions & 0 deletions app/code/core/Mage/Oauth2/Block/Adminhtml/Client/Edit.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
<?php

class Mage_Oauth2_Block_Adminhtml_Client_Edit extends Mage_Adminhtml_Block_Widget_Form_Container
{
protected $_model;

/**
* Constructs the object and initializes the block group, controller, and mode.
* Updates the save and delete buttons with localized labels.
* Removes the delete button if the user is not allowed to perform the delete action.
* Adds a save and continue button with a localized label and onclick event.
* Adds a form script to submit the form with a specific action.
*
* @return void
*/
public function __construct()
{
parent::__construct();
$this->_blockGroup = 'oauth2';
$this->_controller = 'adminhtml_client';
$this->_mode = 'edit';

$this->_updateButton('save', 'label', $this->__('Save'));
$this->_updateButton('save', 'id', 'save_button');
$this->_updateButton('delete', 'label', $this->__('Delete'));
$this->_updateButton('delete', 'onclick', 'if(confirm(\'' . Mage::helper('core')->jsQuoteEscape(
$this->__('Are you sure you want to do this?')
) . '\')) editForm.submit(\'' . $this->getUrl('*/*/delete', ['id' => $this->getModel()->getId()]) . '\'); return false;');

if (!$this->_isAllowedAction('delete')) {
$this->_removeButton('delete');
}

$this->_addButton('save_and_continue', [
'label' => $this->__('Save and Continue Edit'),
'onclick' => 'saveAndContinueEdit()',
'class' => 'save'
], 100);

$this->_formScripts[] = 'function saveAndContinueEdit()' .
"{editForm.submit($('edit_form').action + 'back/edit/');}";
}

/**
* Prepares the layout for the block.
*
*/
public function getHeaderText()
{
return $this->getModel()->getId()
? $this->__("Edit Client '%s'", $this->escapeHtml($this->getModel()->getName()))
: $this->__('New Client');
}

/**
* Check if the current user is allowed to perform the specified action.
*
* @param string $action The action to check.
* @return bool Returns true if the user is allowed, false otherwise.
*/
protected function _isAllowedAction($action)
{
return Mage::getSingleton('admin/session')->isAllowed('system/oauth2/client/' . $action);
}

/**
* Retrieves the model object from the registry if it is not already set.
*
* @return mixed The model object from the registry.
*/
protected function getModel()
{
if (null === $this->_model) {
$this->_model = Mage::registry('current_oauth2_client');
}
return $this->_model;
}
}
86 changes: 86 additions & 0 deletions app/code/core/Mage/Oauth2/Block/Adminhtml/Client/Edit/Form.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,86 @@
<?php

class Mage_Oauth2_Block_Adminhtml_Client_Edit_Form extends Mage_Adminhtml_Block_Widget_Form
{
protected $_model;

/**
* Prepares the form for the admin edit client block.
*
* @return Mage_Core_Block_Abstract
*/
protected function _prepareForm()
{
$form = new Varien_Data_Form(
[
'id' => 'edit_form',
'action' => $this->getData('action'),
'method' => 'post'
]
);

$fieldset = $form->addFieldset('base_fieldset', [
'legend' => $this->__('Client Information'),
'class' => 'fieldset-wide'
]);

$fieldset->addType('text', Mage::getConfig()->getBlockClassName('oauth2/adminhtml_text'));

$fieldset->addField('name', 'text', [
'label' => $this->__('Client Name'),
'name' => 'name',
'required' => true,
'value' => $this->getModel()->getName(),
]);
$fieldset->addField('secret', 'text', [
'label' => $this->__('Client Secret'),
'name' => 'secret',
'required' => true,
'disabled' => true,
'data-copy-text' => $this->getModel()->getSecret(),
'value' => $this->getModel()->getSecret(),
]);

$fieldset->addField('redirect_uri', 'text', [
'label' => $this->__('Redirect URI'),
'name' => 'redirect_uri',
'required' => true,
'value' => $this->getModel()->getRedirectUri(),
]);
$fieldset->addField('grant_types', 'multiselect', [
'label' => $this->__('Grant Types'),
'class' => 'required-entry',
'required' => true,
'name' => 'grant_types[]',
'values' => [
['value' => 'authorization_code', 'label' => $this->__('Authorization Code')],
['value' => 'refresh_token', 'label' => $this->__('Refresh Token')],
],
'value' => $this->getModel()->getGrantTypes(),
]);

$fieldset->addField('current_password', 'obscure', [
'name' => 'current_password',
'label' => $this->__('Current Admin Password'),
'required' => true
]);

$form->setAction($this->getUrl('*/*/save', ['id' => $this->getModel()->getId()]));
$form->setUseContainer(true);
$this->setForm($form);
return parent::_prepareForm();
}

/**
* Retrieves the model object from the registry if it is not already set.
*
* @return mixed The model object from the registry.
*/
protected function getModel()
{
if (null === $this->_model) {
$this->_model = Mage::registry('current_oauth2_client');
}
return $this->_model;
}
}
102 changes: 102 additions & 0 deletions app/code/core/Mage/Oauth2/Block/Adminhtml/Client/Grid.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,102 @@
<?php

/**
* OAuth2 Client Grid Block
*/
class Mage_Oauth2_Block_Adminhtml_Client_Grid extends Mage_Adminhtml_Block_Widget_Grid
{
/**
* @var bool
*/
protected $_editAllow = false;

/**
* Constructor
*/
public function __construct()
{
parent::__construct();
$this->setId('oauth2_client_grid')
->setDefaultSort('entity_id')
->setDefaultDir('DESC')
->setSaveParametersInSession(true);

$this->_editAllow = Mage::getSingleton('admin/session')->isAllowed('system/oauth/consumer/edit');
}

/**
* Prepare collection
*
* @return Mage_Oauth2_Block_Adminhtml_Client_Grid
*/
protected function _prepareCollection()
{
$collection = Mage::getModel('oauth2/client')->getCollection();
$this->setCollection($collection);
return parent::_prepareCollection();
}

/**
* Prepare columns
*
* @return Mage_Oauth2_Block_Adminhtml_Client_Grid
*/
protected function _prepareColumns()
{
$this->addColumn('entity_id', [
'header' => $this->__('Entity ID'),
'index' => 'entity_id',
'type' => 'number',
]);

$this->addColumn('secret', [
'header' => $this->__('Secret'),
'index' => 'secret',
]);

$this->addColumn('redirect_uri', [
'header' => $this->__('Redirect URI'),
'index' => 'redirect_uri',
]);

$this->addColumn('grant_types', [
'header' => $this->__('Grant Types'),
'index' => 'grant_types',
]);

$this->addColumn('created_at', [
'header' => $this->__('Created At'),
'index' => 'created_at',
'type' => 'datetime',
]);

$this->addColumn('updated_at', [
'header' => $this->__('Updated At'),
'index' => 'updated_at',
'type' => 'datetime',
]);

return parent::_prepareColumns();
}

/**
* Get grid URL
*
* @return string
*/
public function getGridUrl()
{
return $this->getUrl('*/*/grid', ['_current' => true]);
}

/**
* Get row URL
*
* @param Mage_Core_Model_Abstract $row
* @return string|null
*/
public function getRowUrl($row)
{
return $this->_editAllow ? $this->getUrl('*/*/edit', ['id' => $row->getId()]) : null;
}
}
Loading
Loading