Skip to content

Commit

Permalink
feat(publisher): create publisher consumer if it does not exist yet (#…
Browse files Browse the repository at this point in the history
  • Loading branch information
colorfield authored Oct 16, 2023
1 parent 5b82c4f commit 3a653b4
Show file tree
Hide file tree
Showing 2 changed files with 70 additions and 0 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
name: Silverback Gatsby OAuth
type: module
description: 'Integration of Publisher with OAuth.'
package: Silverback
dependencies:
- silverback_gatsby:silverback_gatsby
- simple_oauth:simple_oauth
- consumers:consumers
core_version_requirement: ^8 || ^9 || ^10
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
<?php

use Drupal\user\RoleInterface;

function silverback_gatsby_oauth_install() {
// Skip for Silverback environments.
// It might be used for OAuth development purpose only in Silverback
// and can be set manually for this case.
// Matches the default Publisher behavior
// that disables Publisher OAuth for non Lagoon environments.
if (getenv('SB_ENVIRONMENT')) {
return;
}

// Check requirements.
$entityTypeManager = \Drupal::entityTypeManager();
$publisherRole = $entityTypeManager->getStorage('user_role')->load('publisher');
if (!$publisherRole instanceof RoleInterface) {
throw new \Exception('Publisher Role does not exist. It is required to setup the Publisher OAuth Consumer.');
}

$publisherUrl = getenv('PUBLISHER_URL');
if (!$publisherUrl) {
throw new \Exception('PUBLISHER_URL environment variable is not set. It is required to setup the Publisher OAuth Consumer.');
}

$clientSecret = getenv('PUBLISHER_OAUTH2_CLIENT_SECRET');
if (!$clientSecret) {
throw new \Exception('PUBLISHER_OAUTH2_CLIENT_SECRET environment variable is not set. It is required to setup the Publisher OAuth Consumer.');
}

$consumersStorage = $entityTypeManager->getStorage('consumer');
$existingConsumers = $consumersStorage->loadMultiple();
$hasPublisherConsumer = FALSE;
/** @var \Drupal\consumers\Entity\ConsumerInterface $consumer */
foreach($existingConsumers as $consumer) {
// As a side effect, delete the default consumer.
// It is installed by the Consumers module.
if ($consumer->getClientId() === 'default_consumer') {
$consumer->delete();
}
if ($consumer->getClientId() === 'publisher') {
$hasPublisherConsumer = TRUE;
}
}

// Create the Publisher Consumer if it does not exist.
if (!$hasPublisherConsumer) {
$oAuthCallback = $publisherUrl . '/oauth/callback';
$consumersStorage->create([
'label' => 'Publisher',
'client_id' => 'publisher',
'is_default' => TRUE,
'secret' => $clientSecret,
'redirect' => $oAuthCallback,
'roles' => [
'publisher',
],
])->save();
}
}

0 comments on commit 3a653b4

Please sign in to comment.