View source
<?php
namespace Drupal\salesforce_oauth\Plugin\SalesforceAuthProvider;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Routing\TrustedRedirectResponse;
use Drupal\Core\Url;
use Drupal\salesforce\SalesforceAuthProviderPluginBase;
class SalesforceOAuthPlugin extends SalesforceAuthProviderPluginBase {
protected $credentials;
public static function defaultConfiguration() {
$defaults = parent::defaultConfiguration();
return array_merge($defaults, [
'consumer_secret' => '',
]);
}
public function buildConfigurationForm(array $form, FormStateInterface $form_state) {
$form['consumer_key'] = [
'#title' => $this
->t('Salesforce consumer key'),
'#type' => 'textfield',
'#description' => $this
->t('Consumer key of the Salesforce remote application you want to grant access to'),
'#required' => TRUE,
'#default_value' => $this
->getCredentials()
->getConsumerKey(),
];
$form['consumer_secret'] = [
'#title' => $this
->t('Salesforce consumer secret'),
'#type' => 'textfield',
'#description' => $this
->t('Consumer secret of the Salesforce remote application.'),
'#required' => TRUE,
'#default_value' => $this
->getCredentials()
->getConsumerSecret(),
];
$form['login_url'] = [
'#title' => $this
->t('Login URL'),
'#type' => 'textfield',
'#default_value' => $this
->getCredentials()
->getLoginUrl(),
'#description' => $this
->t('Enter a login URL, either https://login.salesforce.com or https://test.salesforce.com.'),
'#required' => TRUE,
];
return $form;
}
public function submitConfigurationForm(array &$form, FormStateInterface $form_state) {
parent::submitConfigurationForm($form, $form_state);
$tempstore = \Drupal::service('tempstore.private')
->get('salesforce_oauth');
$tempstore
->set('config_id', $form_state
->getValue('id'));
try {
$path = $this
->getAuthorizationEndpoint();
$query = [
'redirect_uri' => $this
->getCredentials()
->getCallbackUrl(),
'response_type' => 'code',
'client_id' => $this
->getCredentials()
->getConsumerKey(),
];
$form_state
->setResponse(new TrustedRedirectResponse(Url::fromUri($path . '?' . http_build_query($query))
->toString()));
} catch (\Exception $e) {
$form_state
->setError($form, $this
->t("Error during authorization: %message", [
'%message' => $e
->getMessage(),
]));
}
}
public function getConsumerSecret() {
return $this
->getCredentials()
->getConsumerSecret();
}
}