sqrl-2.0.0-rc1/src/Form/ProfileEdit.php

src/Form/ProfileEdit.php
<?php

namespace Drupal\sqrl\Form;

use Drupal\Component\Utility\Random;
use Drupal\Core\Access\AccessResult;
use Drupal\Core\Entity\EntityStorageException;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Mail\MailManagerInterface;
use Drupal\Core\Messenger\MessengerInterface;
use Drupal\Core\Session\AccountProxyInterface;
use Drupal\sqrl\Identities;
use Drupal\sqrl\Nut;
use Drupal\sqrl\Sqrl;
use Drupal\sqrl\StringManipulation;
use Drupal\user\Entity\User;
use Drupal\user\UserDataInterface;
use Drupal\user\UserInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;

/**
 * Provides a SQRL form.
 */
class ProfileEdit extends FormBase {

  use StringManipulation;

  /**
   * The entity type manager.
   *
   * @var \Drupal\Core\Entity\EntityTypeManagerInterface
   */
  protected EntityTypeManagerInterface $entityTypeManager;

  /**
   * The identities.
   *
   * @var \Drupal\sqrl\Identities
   */
  protected Identities $identities;

  /**
   * The current user.
   *
   * @var \Drupal\Core\Session\AccountProxyInterface
   */
  protected AccountProxyInterface $currentUser;

  /**
   * The nut service.
   *
   * @var \Drupal\sqrl\Nut
   */
  protected Nut $nut;

  /**
   * The mail manager.
   *
   * @var \Drupal\Core\Mail\MailManagerInterface
   */
  protected MailManagerInterface $mailManager;

  /**
   * The user data service.
   *
   * @var \Drupal\user\UserDataInterface
   */
  protected UserDataInterface $userData;

  /**
   * The random service.
   *
   * @var \Drupal\Component\Utility\Random
   */
  protected Random $random;

  /**
   * Link constructor.
   *
   * @param \Drupal\Core\Entity\EntityTypeManagerInterface $entity_type_manager
   *   The entity type manager.
   * @param \Drupal\sqrl\Sqrl $sqrl
   *   The sqrl service.
   * @param \Drupal\sqrl\Identities $identities
   *   The identities.
   * @param \Drupal\Core\Session\AccountProxyInterface $current_user
   *   The current user.
   * @param \Drupal\Core\Messenger\MessengerInterface $messenger
   *   The messenger service.
   * @param \Drupal\Core\Mail\MailManagerInterface $mail_manager
   *   The mail manager.
   * @param \Drupal\user\UserDataInterface $user_data
   *   The user data service.
   */
  final public function __construct(EntityTypeManagerInterface $entity_type_manager, Sqrl $sqrl, Identities $identities, AccountProxyInterface $current_user, MessengerInterface $messenger, MailManagerInterface $mail_manager, UserDataInterface $user_data) {
    $this->entityTypeManager = $entity_type_manager;
    $this->identities = $identities;
    $this->currentUser = $current_user;
    $this->messenger = $messenger;
    $this->mailManager = $mail_manager;
    $this->userData = $user_data;

    $this->nut = $sqrl->getNewNut();
    $this->nut->fetch();
    $this->random = new Random();
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container): ProfileEdit {
    return new ProfileEdit(
      $container->get('entity_type.manager'),
      $container->get('sqrl.handler'),
      $container->get('sqrl.identities'),
      $container->get('current_user'),
      $container->get('messenger'),
      $container->get('plugin.manager.mail'),
      $container->get('user.data')
    );
  }

  /**
   * {@inheritdoc}
   */
  public function getFormId(): string {
    return 'sqrl_profile_edit';
  }

  /**
   * Checks the access permission.
   *
   * @param \Drupal\user\UserInterface $user
   *   The user.
   * @param string $token
   *   The token.
   *
   * @return \Drupal\Core\Access\AccessResult
   *   The access result.
   */
  public function access(UserInterface $user, string $token): AccessResult {
    if ($this->nut->isValid() && $this->nut->getLoginToken() === $token && $this->currentUser->id() === $user->id()) {
      return AccessResult::allowed();
    }
    return AccessResult::forbidden();
  }

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state, ?UserInterface $user = NULL): array {
    $email = ($user === NULL) ? '' : $user->getEmail();
    $form['pass'] = [
      '#type' => 'password_confirm',
      '#size' => 25,
      '#description' => $this->t('To set your user password, enter the password in both fields.'),
    ];
    $form['mail'] = [
      '#type' => 'email',
      '#title' => $this->t('Email address'),
      '#description' => $this->t('A valid email address. All emails from the system will be sent to this address. The email address is not made public and will only be used if you wish to receive a new password or wish to receive certain news or notifications by email.'),
      '#default_value' => $this->identities->isDummyMail($email) ? '' : $email,
    ];
    $form['unset'] = [
      '#type' => 'checkbox',
      '#title' => $this->t('Unset password and email address'),
      '#default_value' => FALSE,
    ];

    $form['#validate'][] = [$this, 'validateMail'];

    $form['actions'] = [
      '#type' => 'actions',
    ];
    $form['actions']['submit'] = [
      '#type' => 'submit',
      '#value' => $this->t('Save'),
    ];

    return $form;
  }

  /**
   * Validates the mail.
   *
   * @param array $form
   *   The form array.
   * @param \Drupal\Core\Form\FormStateInterface $form_state
   *   The form state.
   *
   * @throws \Drupal\Component\Plugin\Exception\InvalidPluginDefinitionException
   * @throws \Drupal\Component\Plugin\Exception\PluginNotFoundException
   */
  public function validateMail(array $form, FormStateInterface $form_state): void {
    $mail = trim($form_state->getValue('mail'));
    $users = $this->entityTypeManager->getStorage('user')->loadByProperties(['mail' => $mail]);
    foreach ($users as $user) {
      if ($user->id() !== $this->currentUser->id()) {
        $form_state->setErrorByName('mail', $this->t('Mail address already taken.'));
        return;
      }
    }
  }

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state): void {
    /** @var \Drupal\user\UserInterface $account */
    $account = User::load($this->currentUser->id());

    if ($form_state->getValue('unset')) {
      $account->setEmail($this->identities->dummyMail());
      $account->setPassword($this->random->string(32));
      $changed = TRUE;
      $this->messenger->addStatus($this->t('Your password and email address have been removed.'));
    }
    else {
      $pass = trim($form_state->getValue('pass'));
      $mail = trim($form_state->getValue('mail'));

      $changed = FALSE;
      if (!empty($mail) && $mail !== $account->getEmail()) {
        if ($this->configFactory()->get('sqrl.settings')->get('mail_verification')) {
          $token = $this->base64Encode($this->randomBytes(8));
          // Store mail address.
          $this->userData->set('sqrl', $this->currentUser->id(), $token, $mail);
          // Send out email.
          $this->mailManager->mail('sqrl', 'confirm_email', $mail, $this->currentUser->getPreferredLangcode(), [
            'account' => $this->currentUser,
            'token' => $token,
          ]);
          $this->messenger->addStatus($this->t('We have sent you an email with a link to confirm your new email address.'));
        }
        else {
          $account->setEmail($mail);
          $changed = TRUE;
        }
      }
      if (!empty($pass)) {
        $account->setPassword($pass);
        $changed = TRUE;
      }
    }
    if ($changed) {
      try {
        $account->save();
      }
      catch (EntityStorageException) {
        // @todo Log this exception.
      }
    }

    // Redirect back to the user profile.
    $form_state->setRedirect('user.page');
  }

}

Главная | Обратная связь

drupal hosting | друпал хостинг | it patrol .inc