You are here

class SamlSpConfig in SAML Service Provider 8.2

Same name and namespace in other branches
  1. 8.3 src/Form/SamlSpConfig.php \Drupal\saml_sp\Form\SamlSpConfig
  2. 4.x src/Form/SamlSpConfig.php \Drupal\saml_sp\Form\SamlSpConfig
  3. 3.x src/Form/SamlSpConfig.php \Drupal\saml_sp\Form\SamlSpConfig

Hierarchy

Expanded class hierarchy of SamlSpConfig

1 string reference to 'SamlSpConfig'
saml_sp.routing.yml in ./saml_sp.routing.yml
saml_sp.routing.yml

File

src/Form/SamlSpConfig.php, line 17
Contains \Drupal\saml_sp\Form\SamlSpConfigSPForm.

Namespace

Drupal\saml_sp\Form
View source
class SamlSpConfig extends ConfigFormBase {

  /**
   * {@inheritdoc}
   */
  public function getFormId() {
    return 'saml_sp_config_sp';
  }

  /**
   * Check if config variable is overridden by the settings.php.
   *
   * @param string $name
   *   SAML SP settings key.
   *
   * @return bool
   *   Boolean.
   */
  protected function isOverridden($name) {
    $original = $this->configFactory
      ->getEditable('saml_sp.settings')
      ->get($name);
    $current = $this->configFactory
      ->get('saml_sp.settings')
      ->get($name);
    return $original != $current;
  }

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {
    $config = $this->configFactory
      ->getEditable('saml_sp.settings');
    $values = $form_state
      ->getValues();
    $this
      ->configRecurse($config, $values['contact'], 'contact');
    $this
      ->configRecurse($config, $values['organization'], 'organization');
    $this
      ->configRecurse($config, $values['security'], 'security');
    $config
      ->set('strict', (bool) $values['strict']);
    $config
      ->set('debug', (bool) $values['debug']);
    $config
      ->set('key_location', $values['key_location']);
    $config
      ->set('cert_location', $values['cert_location']);
    $config
      ->set('new_cert_location', $values['new_cert_location']);
    $config
      ->set('entity_id', $values['entity_id']);
    $config
      ->save();
    if (method_exists($this, '_submitForm')) {
      $this
        ->_submitForm($form, $form_state);
    }
    parent::submitForm($form, $form_state);
  }

  /**
   * {@inheritdoc}
   */
  public function validateForm(array &$form, FormStateInterface $form_state) {

    // ensure the cert and key files are provided and exist in the system if
    // signed or encryption options require them
    $values = $form_state
      ->getValues();
    if ($values['security']['authnRequestsSigned'] || $values['security']['logoutRequestSigned'] || $values['security']['logoutResponseSigned'] || $values['security']['wantNameIdEncrypted'] || $values['security']['signMetaData']) {
      foreach ([
        'key_location',
        'cert_location',
      ] as $key) {
        if (empty($values[$key])) {
          $form_state
            ->setError($form[$key], $this
            ->t('The %field must be provided.', array(
            '%field' => $form[$key]['#title'],
          )));
        }
        else {
          if (!file_exists($values[$key])) {
            $form_state
              ->setError($form[$key], $this
              ->t('The %input file does not exist.', array(
              '%input' => $values[$key],
            )));
          }
        }
      }
    }
  }

  /**
   * recursively go through the set values to set the configuration
   */
  protected function configRecurse($config, $values, $base = '') {
    foreach ($values as $var => $value) {
      if (!empty($base)) {
        $v = $base . '.' . $var;
      }
      else {
        $v = $var;
      }
      if (!is_array($value)) {
        $config
          ->set($v, $value);
      }
      else {
        $this
          ->configRecurse($config, $value, $v);
      }
    }
  }

  /**
   * {@inheritdoc}
   */
  protected function getEditableConfigNames() {
    return [
      'saml_sp.settings',
    ];
  }

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form = [], FormStateInterface $form_state) {
    $config = $this->configFactory
      ->get('saml_sp.settings');
    $form['entity_id'] = array(
      '#type' => 'textfield',
      '#title' => $this
        ->t('Entity ID'),
      '#description' => $this
        ->t('This is the unique name that the Identity Providers will know your site as. Defaults to the login page %login_url', array(
        '%login_url' => \Drupal::url('user.page', array(), array(
          'absolute' => TRUE,
        )),
      )),
      '#default_value' => $config
        ->get('entity_id'),
      '#disabled' => $this
        ->isOverridden('entity_id'),
    );
    $form['contact'] = array(
      '#type' => 'fieldset',
      '#title' => $this
        ->t('Contact Information'),
      '#description' => $this
        ->t('Information to be included in the federation metadata.'),
      '#tree' => TRUE,
    );
    $form['contact']['technical'] = array(
      '#type' => 'fieldset',
      '#title' => $this
        ->t('Technical'),
    );
    $form['contact']['technical']['name'] = array(
      '#type' => 'textfield',
      '#title' => $this
        ->t('Name'),
      '#default_value' => $config
        ->get('contact.technical.name'),
      '#disabled' => $this
        ->isOverridden('contact.technical.name'),
    );
    $form['contact']['technical']['email'] = array(
      '#type' => 'textfield',
      '#title' => $this
        ->t('Email'),
      '#default_value' => $config
        ->get('contact.technical.email'),
      '#disabled' => $this
        ->isOverridden('contact.technical.email'),
    );
    $form['contact']['support'] = array(
      '#type' => 'fieldset',
      '#title' => $this
        ->t('Support'),
    );
    $form['contact']['support']['name'] = array(
      '#type' => 'textfield',
      '#title' => $this
        ->t('Name'),
      '#default_value' => $config
        ->get('contact.support.name'),
      '#disabled' => $this
        ->isOverridden('contact.support.name'),
    );
    $form['contact']['support']['email'] = array(
      '#type' => 'textfield',
      '#title' => $this
        ->t('Email'),
      '#default_value' => $config
        ->get('contact.support.email'),
      '#disabled' => $this
        ->isOverridden('contact.support.email'),
    );
    $form['organization'] = array(
      '#type' => 'fieldset',
      '#title' => $this
        ->t('Organization'),
      '#description' => $this
        ->t('Organization information for the federation metadata'),
      '#tree' => TRUE,
    );
    $form['organization']['name'] = array(
      '#type' => 'textfield',
      '#title' => $this
        ->t('Name'),
      '#description' => $this
        ->t('This is a short name for the organization'),
      '#default_value' => $config
        ->get('organization.name'),
      '#disabled' => $this
        ->isOverridden('organization.name'),
    );
    $form['organization']['display_name'] = array(
      '#type' => 'textfield',
      '#title' => $this
        ->t('Display Name'),
      '#description' => $this
        ->t('This is a long name for the organization'),
      '#default_value' => $config
        ->get('organization.display_name'),
      '#disabled' => $this
        ->isOverridden('organization.display_name'),
    );
    $form['organization']['url'] = array(
      '#type' => 'textfield',
      '#title' => $this
        ->t('URL'),
      '#description' => $this
        ->t('This is a URL for the organization'),
      '#default_value' => $config
        ->get('organization.url'),
      '#disabled' => $this
        ->isOverridden('organization.url'),
    );
    $form['strict'] = array(
      '#type' => 'checkbox',
      '#title' => t('Strict Protocol'),
      '#description' => t('SAML 2 Strict protocol will be used.'),
      '#default_value' => $config
        ->get('strict'),
      '#disabled' => $this
        ->isOverridden('strict'),
    );
    $form['security'] = array(
      '#type' => 'fieldset',
      '#title' => $this
        ->t('Security'),
      '#tree' => TRUE,
    );
    $form['security']['offered'] = array(
      '#markup' => t('Signatures and Encryptions Offered:'),
    );
    $form['security']['nameIdEncrypted'] = array(
      '#type' => 'checkbox',
      '#title' => $this
        ->t('NameID Encrypted'),
      '#default_value' => $config
        ->get('security.nameIdEncrypted'),
      '#disabled' => $this
        ->isOverridden('security.nameIdEncrypted'),
    );
    $form['security']['authnRequestsSigned'] = array(
      '#type' => 'checkbox',
      '#title' => $this
        ->t('Authn Requests Signed'),
      '#default_value' => $config
        ->get('security.authnRequestsSigned'),
      '#disabled' => $this
        ->isOverridden('security.authnRequestsSigned'),
    );
    $form['security']['logoutRequestSigned'] = array(
      '#type' => 'checkbox',
      '#title' => $this
        ->t('Logout Requests Signed'),
      '#default_value' => $config
        ->get('security.logoutRequestSigned'),
      '#disabled' => $this
        ->isOverridden('security.logoutRequestSigned'),
    );
    $form['security']['logoutResponseSigned'] = array(
      '#type' => 'checkbox',
      '#title' => $this
        ->t('Logout Response Signed'),
      '#default_value' => $config
        ->get('security.logoutResponseSigned'),
      '#disabled' => $this
        ->isOverridden('security.logoutResponseSigned'),
    );
    $form['security']['required'] = array(
      '#markup' => $this
        ->t('Signatures and Encryptions Required:'),
    );
    $form['security']['wantMessagesSigned'] = array(
      '#type' => 'checkbox',
      '#title' => $this
        ->t('Want Messages Signed'),
      '#default_value' => $config
        ->get('security.wantMessagesSigned'),
      '#disabled' => $this
        ->isOverridden('security.wantMessagesSigned'),
    );
    $form['security']['wantAssertionsSigned'] = array(
      '#type' => 'checkbox',
      '#title' => $this
        ->t('Want Assertions Signed'),
      '#default_value' => $config
        ->get('security.wantAssertionsSigned'),
      '#disabled' => $this
        ->isOverridden('security.wantAssertionsSigned'),
    );
    $form['security']['wantNameIdEncrypted'] = array(
      '#type' => 'checkbox',
      '#title' => $this
        ->t('Want NameID Encrypted'),
      '#default_value' => $config
        ->get('security.wantNameIdEncrypted'),
      '#disabled' => $this
        ->isOverridden('security.wantNameIdEncrypted'),
    );
    $form['security']['metadata'] = array(
      '#markup' => $this
        ->t('Metadata:'),
    );
    $form['security']['signMetaData'] = array(
      '#type' => 'checkbox',
      '#title' => $this
        ->t('Sign Meta Data'),
      '#default_value' => $config
        ->get('security.signMetaData'),
      '#disabled' => $this
        ->isOverridden('security.signMetaData'),
    );
    $form['security']['signatureAlgorithm'] = [
      '#type' => 'select',
      '#title' => $this
        ->t('Signature Algorithm'),
      '#description' => $this
        ->t('What algorithm do you want used for messages signatures?'),
      '#options' => [
        //XMLSecurityKey::DSA_SHA1 => 'DSA SHA-1',
        XMLSecurityKey::RSA_SHA1 => 'SHA-1',
        XMLSecurityKey::RSA_SHA256 => 'SHA-256',
        XMLSecurityKey::RSA_SHA384 => 'SHA-384',
        XMLSecurityKey::RSA_SHA512 => 'SHA-512',
      ],
      '#default_value' => $config
        ->get('security.signatureAlgorithm'),
      '#disabled' => $this
        ->isOverridden('security.signatureAlgorithm'),
    ];
    $form['security']['lowercaseUrlencoding'] = [
      '#type' => 'checkbox',
      '#title' => $this
        ->t('Lowercase Url Encoding'),
      //'#description'    => $this->t(""),
      '#default_value' => $config
        ->get('security.lowercaseUrlencoding'),
      '#disabled' => $this
        ->isOverridden('security.lowercaseUrlencoding'),
    ];
    $form['cert_location'] = array(
      '#type' => 'textfield',
      '#title' => $this
        ->t('Certificate Location'),
      '#description' => $this
        ->t('The location of the x.509 certificate file on the server. This must be a location that PHP can read.'),
      '#default_value' => $config
        ->get('cert_location'),
      '#disabled' => $this
        ->isOverridden('cert_location'),
      '#states' => array(
        'required' => array(
          [
            'input[name="security[authnRequestsSigned]"' => [
              'checked' => TRUE,
            ],
          ],
          [
            'input[name="security[logoutRequestSigned]"' => [
              'checked' => TRUE,
            ],
          ],
          [
            'input[name="security[logoutResponseSigned]"' => [
              'checked' => TRUE,
            ],
          ],
          [
            'input[name="security[wantNameIdEncrypted]"' => [
              'checked' => TRUE,
            ],
          ],
          [
            'input[name="security[signMetaData]"' => [
              'checked' => TRUE,
            ],
          ],
        ),
      ),
      '#suffix' => $this
        ->certInfo($config
        ->get('cert_location')),
    );
    $form['key_location'] = array(
      '#type' => 'textfield',
      '#title' => $this
        ->t('Key Location'),
      '#description' => $this
        ->t('The location of the x.509 key file on the server. This must be a location that PHP can read.'),
      '#default_value' => $config
        ->get('key_location'),
      '#disabled' => $this
        ->isOverridden('key_location'),
      '#states' => array(
        'required' => array(
          [
            'input[name="security[authnRequestsSigned]"' => [
              'checked' => TRUE,
            ],
          ],
          [
            'input[name="security[logoutRequestSigned]"' => [
              'checked' => TRUE,
            ],
          ],
          [
            'input[name="security[logoutResponseSigned]"' => [
              'checked' => TRUE,
            ],
          ],
          [
            'input[name="security[wantNameIdEncrypted]"' => [
              'checked' => TRUE,
            ],
          ],
          [
            'input[name="security[signMetaData]"' => [
              'checked' => TRUE,
            ],
          ],
        ),
      ),
    );
    $form['new_cert_location'] = array(
      '#type' => 'textfield',
      '#title' => $this
        ->t('New Certificate Location'),
      '#description' => $this
        ->t('The location of the x.509 certificate file on the server. If the certificate above is about to expire add your new certificate here after you have obtained it. This will add the new certificate to the metadata to let the IdP know of the new certificate. This must be a location that PHP can read.'),
      '#default_value' => $config
        ->get('new_cert_location'),
      '#disabled' => $this
        ->isOverridden('new_cert_location'),
      '#suffix' => $this
        ->certInfo($config
        ->get('new_cert_location')),
    );
    $error = FALSE;
    try {
      $metadata = saml_sp__get_metadata(FALSE);
      if (is_array($metadata)) {
        if (isset($metadata[1])) {
          $errors = $metadata[1];
        }
        $metadata = $metadata[0];
      }
    } catch (Exception $e) {
      drupal_set_message($this
        ->t('Attempt to create metadata failed: %message.', array(
        '%message' => $e
          ->getMessage(),
      )), 'error');
      $metadata = '';
      $error = $e;
    }
    if (empty($metadata) && $error) {
      $no_metadata = $this
        ->t('There is currently no metadata because of the following error: %error. Please resolve the error and return here for your metadata.', array(
        '%error' => $error
          ->getMessage(),
      ));
    }
    $form['metadata'] = array(
      '#type' => 'fieldset',
      '#collapsed' => TRUE,
      '#collapsible' => TRUE,
      '#title' => $this
        ->t('Metadata'),
      '#description' => $this
        ->t('This is the Federation Metadata for this SP, please provide this to the IdP to create a Relying Party Trust (RPT)'),
    );
    if ($metadata) {
      $form['metadata']['data'] = array(
        '#type' => 'textarea',
        '#title' => $this
          ->t('XML Metadata'),
        '#description' => $this
          ->t('This metadata can also be accessed <a href="@url" target="_blank">here</a>', array(
          '@url' => Url::fromRoute('saml_sp.metadata')
            ->toString(),
        )),
        '#disabled' => TRUE,
        '#rows' => 20,
        '#default_value' => trim($metadata),
      );
    }
    else {
      $form['metadata']['none'] = array(
        '#markup' => $no_metadata,
      );
    }
    $form['debug'] = array(
      '#type' => 'checkbox',
      '#title' => $this
        ->t('Turn on debugging'),
      '#description' => $this
        ->t('Some debugging messages will be shown.'),
      '#default_value' => $config
        ->get('debug'),
      '#disabled' => $this
        ->isOverridden('debug'),
    );
    return parent::buildForm($form, $form_state);
  }

  /**
   * with the certificate location retrieve pertinant certificate data and output
   * in a string for display
   */
  function certInfo($cert_location) {
    if (!empty($cert_location) && file_exists($cert_location) && function_exists('openssl_x509_parse')) {
      $encoded_cert = trim(file_get_contents($cert_location));
      $cert = openssl_x509_parse(\OneLogin_Saml2_Utils::formatCert($encoded_cert));

      // flatten the issuer array
      if (!empty($cert['issuer'])) {
        foreach ($cert['issuer'] as $key => &$value) {
          if (is_array($value)) {
            $value = implode("/", $value);
          }
        }
      }
      if ($cert) {
        $info = t('Name: %cert-name<br/>Issued by: %issuer<br/>Valid: %valid-from - %valid-to', array(
          '%cert-name' => isset($cert['name']) ? $cert['name'] : '',
          '%issuer' => isset($cert['issuer']) && is_array($cert['issuer']) ? implode('/', $cert['issuer']) : '',
          '%valid-from' => isset($cert['validFrom_time_t']) ? date('c', $cert['validFrom_time_t']) : '',
          '%valid-to' => isset($cert['validTo_time_t']) ? date('c', $cert['validTo_time_t']) : '',
        ));
        return $info;
      }
    }
    return FALSE;
  }

}

Members

Namesort descending Modifiers Type Description Overrides
ConfigFormBase::create public static function Instantiates a new instance of this class. Overrides FormBase::create 13
ConfigFormBase::__construct public function Constructs a \Drupal\system\ConfigFormBase object. 11
ConfigFormBaseTrait::config protected function Retrieves a configuration object.
DependencySerializationTrait::$_entityStorages protected property An array of entity type IDs keyed by the property name of their storages.
DependencySerializationTrait::$_serviceIds protected property An array of service IDs keyed by property name used for serialization.
DependencySerializationTrait::__sleep public function 1
DependencySerializationTrait::__wakeup public function 2
FormBase::$configFactory protected property The config factory. 1
FormBase::$requestStack protected property The request stack. 1
FormBase::$routeMatch protected property The route match.
FormBase::configFactory protected function Gets the config factory for this form. 1
FormBase::container private function Returns the service container.
FormBase::currentUser protected function Gets the current user.
FormBase::getRequest protected function Gets the request object.
FormBase::getRouteMatch protected function Gets the route match.
FormBase::logger protected function Gets the logger for a specific channel.
FormBase::redirect protected function Returns a redirect response object for the specified route. Overrides UrlGeneratorTrait::redirect
FormBase::resetConfigFactory public function Resets the configuration factory.
FormBase::setConfigFactory public function Sets the config factory for this form.
FormBase::setRequestStack public function Sets the request stack object to use.
LinkGeneratorTrait::$linkGenerator protected property The link generator. 1
LinkGeneratorTrait::getLinkGenerator Deprecated protected function Returns the link generator.
LinkGeneratorTrait::l Deprecated protected function Renders a link to a route given a route name and its parameters.
LinkGeneratorTrait::setLinkGenerator Deprecated public function Sets the link generator service.
LoggerChannelTrait::$loggerFactory protected property The logger channel factory service.
LoggerChannelTrait::getLogger protected function Gets the logger for a specific channel.
LoggerChannelTrait::setLoggerFactory public function Injects the logger channel factory.
MessengerTrait::$messenger protected property The messenger. 29
MessengerTrait::messenger public function Gets the messenger. 29
MessengerTrait::setMessenger public function Sets the messenger.
RedirectDestinationTrait::$redirectDestination protected property The redirect destination service. 1
RedirectDestinationTrait::getDestinationArray protected function Prepares a 'destination' URL query parameter for use with \Drupal\Core\Url.
RedirectDestinationTrait::getRedirectDestination protected function Returns the redirect destination service.
RedirectDestinationTrait::setRedirectDestination public function Sets the redirect destination service.
SamlSpConfig::buildForm public function Form constructor. Overrides ConfigFormBase::buildForm
SamlSpConfig::certInfo function with the certificate location retrieve pertinant certificate data and output in a string for display
SamlSpConfig::configRecurse protected function recursively go through the set values to set the configuration
SamlSpConfig::getEditableConfigNames protected function Gets the configuration names that will be editable. Overrides ConfigFormBaseTrait::getEditableConfigNames
SamlSpConfig::getFormId public function Returns a unique string identifying the form. Overrides FormInterface::getFormId
SamlSpConfig::isOverridden protected function Check if config variable is overridden by the settings.php.
SamlSpConfig::submitForm public function Form submission handler. Overrides ConfigFormBase::submitForm
SamlSpConfig::validateForm public function Form validation handler. Overrides FormBase::validateForm
StringTranslationTrait::$stringTranslation protected property The string translation service. 1
StringTranslationTrait::formatPlural protected function Formats a string containing a count of items.
StringTranslationTrait::getNumberOfPlurals protected function Returns the number of plurals supported by a given language.
StringTranslationTrait::getStringTranslation protected function Gets the string translation service.
StringTranslationTrait::setStringTranslation public function Sets the string translation service to use. 2
StringTranslationTrait::t protected function Translates a string to the current language or to a given language.
UrlGeneratorTrait::$urlGenerator protected property The url generator.
UrlGeneratorTrait::getUrlGenerator Deprecated protected function Returns the URL generator service.
UrlGeneratorTrait::setUrlGenerator Deprecated public function Sets the URL generator service.
UrlGeneratorTrait::url Deprecated protected function Generates a URL or path for a specific route based on the given parameters.