Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- diff --git a/src/Form/TfaLoginForm.php b/src/Form/TfaLoginForm.php
- index b21e13a..559249a 100644
- --- a/src/Form/TfaLoginForm.php
- +++ b/src/Form/TfaLoginForm.php
- @@ -150,12 +150,16 @@ class TfaLoginForm extends UserLoginForm {
- $tfa_setup_link = Url::fromRoute('tfa.overview', array(
- 'user' => $account->id(),
- ));
- +///////////////////////////////////////////////temp hack //////////////////////
- + $user_edit_link = '/user/' . $current_uid . '/edit';
- +
- $tfa_setup_link = $tfa_setup_link->toString();
- drupal_set_message($this->t('You are required to setup two-factor
- authentication <a href="@link">here.</a> You have @skipped attempts
- left after this you will be unable to login.', [
- '@skipped' => $left,
- - '@link' => $tfa_setup_link,
- + //'@link' => $tfa_setup_link,
- + '@link' => $user_edit_link,
- ]), 'error');
- $this->tfaSaveTfaData($account->id(), $this->userData, $tfa_data);
- user_login_finalize($account);
- @@ -273,3 +277,4 @@ class TfaLoginForm extends UserLoginForm {
- }
- }
- +
- diff --git a/src/Plugin/TfaSetup/TfaBasicSmsSetup.php b/src/Plugin/TfaSetup/TfaBasicSmsSetup.php
- new file mode 100644
- index 0000000..c2a8664
- --- /dev/null
- +++ b/src/Plugin/TfaSetup/TfaBasicSmsSetup.php
- @@ -0,0 +1,141 @@
- +<?php
- +
- +namespace Drupal\tfa\Plugin\TfaSetup;
- +
- +use Drupal\tfa\Plugin\TfaSetupInterface;
- +use Drupal\tfa\Plugin\TfaValidation\TfaBasicSms;
- +use Drupal\Core\Url;
- +use Drupal\Core\Form\FormStateInterface;
- +use Drupal\user\Entity\User;
- +
- +/**
- + * @TfaSetup(
- + * id = "tfa_basic_sms_setup",
- + * label = @Translation("TFA SMS Setup"),
- + * description = @Translation("TFA Basic SMS Setup Plugin")
- + * )
- + */
- +class TfaBasicSmsSetup extends TfaBasicSms implements TfaSetupInterface {
- +
- + public function __construct(array $configuration, $plugin_id, $plugin_definition,
- + \Drupal\user\UserDataInterface $user_data,
- + \Drupal\encrypt\EncryptionProfileManagerInterface $encryption_profile_manager,
- + \Drupal\encrypt\EncryptServiceInterface $encrypt_service) {
- + parent::__construct( $configuration, $plugin_id, $plugin_definition,
- + $user_data,
- + $encryption_profile_manager,
- + $encrypt_service);
- + $this->user = User::load($this->userId);
- +
- + }
- +
- + public function begin() {
- + if (empty($this->code)) {
- + $this->code = $this->generate();
- + if (!$this->sendCode($this->code)) {
- + // @todo decide on error text
- + $this->errorMessages[''] = t('Unable to deliver code to that number.');
- + }
- + }
- + }
- +
- + /**
- + * {@inheritdoc}
- + */
- + public function getSetupMessages() {
- + return ($this->pluginDefinition['setupMessages']) ?: '';
- + }
- +
- + /**
- + * {@inheritdoc}
- + */
- + public function getOverview($params) {
- +
- + $output = [
- + 'heading' => [
- + '#theme' => 'html_tag',
- + '#tag' => 'h3',
- + '#value' => t('SMS TWILIO '),
- + ],
- + 'description' => [
- + '#theme' => 'html_tag',
- + '#tag' => 'p',
- + '#value' => t('Dont know yet.'),
- + ],
- + ];
- + if (!empty($trusted_browsers)) {
- +
- + $output['list'] = [
- + '#theme' => 'item_list',
- + '#items' => $trusted_browsers,
- + '#title' => t('Dont know yet.2'),
- + ];
- + }
- + $output['link'] = [
- + '#theme' => 'links',
- + '#links' => [
- + 'admin' => [
- + 'title' => 'Configure SMS',
- + 'url' => Url::fromRoute('tfa.validation.setup', [
- + 'user' => $params['account']->id(),
- + 'method' => $params['plugin_id'],
- + ]),
- + ],
- + ],
- + ];
- +
- + return $output;
- + }
- +
- + /**
- + * @copydoc TfaSetupPluginInterface::getSetupForm()
- + */
- + public function getSetupForm(array $form, FormStateInterface $form_state) {
- + $form['sms_code'] = array(
- + '#type' => 'textfield',
- + '#title' => t('Verification Code'),
- + '#required' => TRUE,
- + '#description' => t('Enter @length-character code sent to your device.', array('@length' => $this->codeLength)),
- + );
- + $form['actions']['verify'] = array(
- + '#type' => 'submit',
- + '#value' => t('Verify and save'),
- + );
- +
- + return $form;
- + }
- +
- + /**
- + * @copydoc TfaSetupPluginInterface::validateSetupForm()
- + */
- + public function validateSetupForm(array $form, FormStateInterface $form_state) {
- +
- + //if (!$this->validate($form_state['values']['sms_code'])) {
- + if (!$this->validate((string)$form_state->getValue('sms_code'))) {
- + $this->errorMessages['sms_code'] = t('Invalid code. Please try again.');
- + return FALSE;
- + }
- + else {
- + $phone_verification = $this->phone_verification_service->getPhoneVerificationByEntity($this->user, $this->mobileNumber);
- + $phone_verification->setStatus(TRUE)->save();
- + return TRUE;
- + }
- + }
- +
- + /**
- + * @copydoc TfaSetupPluginInterface::submitSetupForm()
- + */
- + public function submitSetupForm(array $form, FormStateInterface $form_state) {
- + // No submission handling required.
- + return TRUE;
- + }
- +
- + /**
- + * Get list of helper links for the plugin
- + *
- + * @return array List of helper links
- + */
- + public function getHelpLinks(){
- + return $this->pluginDefinition['help_links'];
- + }
- +}
- diff --git a/src/Plugin/TfaValidation/TfaBasicSms.php b/src/Plugin/TfaValidation/TfaBasicSms.php
- new file mode 100644
- index 0000000..7906508
- --- /dev/null
- +++ b/src/Plugin/TfaValidation/TfaBasicSms.php
- @@ -0,0 +1,277 @@
- +<?php
- +
- +namespace Drupal\tfa\Plugin\TfaValidation;
- +
- +use Drupal\sms\Entity\PhoneNumberSettings;
- +use Drupal\sms\Entity\PhoneNumberVerification;
- +use Drupal\sms\Exception\SmsException;
- +use Drupal\sms_twilio\Plugin\SmsGateway\Twilio;
- +use Drupal\tfa\Plugin\TfaBasePlugin;
- +use Drupal\tfa\Plugin\TfaValidationInterface;
- +use Drupal\tfa\Plugin\TfaSendInterface;
- +use Drupal\Core\Form\FormStateInterface;
- +use Drupal\user\Entity\User;
- +use Twilio\Rest\Client;
- +
- +/**
- + * @TfaValidation(
- + * id = "tfa_basic_sms",
- + * label = @Translation("TFA SMS"),
- + * description = @Translation("TFA SMS Validation Plugin")
- + * )
- + */
- +class TfaBasicSms extends TfaBasePlugin implements TfaValidationInterface {
- +
- + protected $client;
- +
- + protected $twilioNumber;
- +
- + protected $mobileNumber;
- +
- + protected $messageText;
- +
- + protected $code;
- +
- + protected $user;
- +
- + protected $userId;
- +
- + protected $status;
- +
- + protected $phone_verification_service;
- +
- + protected $phone_verification;
- +
- + public function __construct(array $configuration, $plugin_id, $plugin_definition,
- + \Drupal\user\UserDataInterface $user_data,
- + \Drupal\encrypt\EncryptionProfileManagerInterface $encryption_profile_manager,
- + \Drupal\encrypt\EncryptServiceInterface $encrypt_service) {
- +
- + parent::__construct($configuration, $plugin_id, $plugin_definition, $user_data, $encryption_profile_manager, $encrypt_service);
- +
- + $sid = \Drupal::config('trinity_twilio_settings')->get('sid');
- + $token = \Drupal::config('trinity_twilio_settings')->get('token');
- + $this->twilioNumber = \Drupal::config('trinity_twilio_settings')
- + ->get('twilioNumber');
- + //$this->mobileNumber = \Drupal::config('trinity_twilio_settings')->get('mobileNumber');
- + $this->user = $user_data;
- + $this->userId = $configuration['uid'];
- + $this->biggerUser = \Drupal\user\Entity\User::load($this->userId);
- + $this->mobileNumber = $this->biggerUser->get('phone_number')->value;
- + $this->phone_verification_service = \Drupal::service('sms.phone_number.verification');
- + $this->client = new Client($sid, $token);
- + $this->codeLength = 6;
- + $this->messageText = ('Verification code: ');
- +
- + $this->phone_verification = \Drupal::entityTypeManager()
- + ->getStorage('sms_phone_number_verification')
- + ->loadByProperties([
- + 'entity__target_id' => $this->userId,
- + ]);
- + if (isset($this->phone_verification[array_keys($this->phone_verification)[0]])) {
- + // id as index which gives awkward [4]=> instead of [0]=>
- + if (($this->phone_verification[array_keys($this->phone_verification)[0]])->get('status')->value == 0) {
- + $this->code = $this->phone_verification[array_keys($this->phone_verification)[0]]->get('code')->value;
- + }
- + else {
- + if (!empty ($this->userData->get('tfa', $configuration['uid'], 'tfa_basic_sms'))) {
- + $this->code = ($this->userData->get(
- + 'tfa',
- + $configuration['uid'],
- + 'tfa_basic_sms'
- + ));
- + }
- + else {
- + $is_admin = \Drupal::service('router.admin_context')->isAdminRoute();
- + if (!$is_admin && $this->ready()) {
- + $this->begin();
- + }
- + }
- + }
- + }
- + }
- +
- + /**
- + *
- + */
- + public function begin() {
- + if (!$this->code) {
- + $this->code = $this->generate();
- + if (!$this->sendCode($this->code)) {
- + drupal_set_message(t('Unable to deliver the code. Please contact support.'), 'error');
- + }
- + }
- + }
- +
- + /**
- + * {@inheritdoc}
- + */
- + public function ready() {
- +
- + //do we return a tfa page? false = no
- +
- + /* There are three states for the verification object.
- + 1) null = non-existent object. user has not yet logged in
- + 2) status = 0 user has been sent phone verification number
- + 3) status = 1 user has verified
- + */
- + $user = User::load($this->userId);
- + $verification = \Drupal::entityTypeManager()
- + ->getStorage('sms_phone_number_verification')
- + ->loadByProperties([
- + 'entity__target_id' => $this->userId,
- + ]);
- + // id as index which gives awkward [4]=> instead of [0]=>
- + if ($verification[array_keys($verification)[0]]) {
- + if ($verification[array_keys($verification)[0]]->get('status')->value == 1) {
- + return TRUE;
- + }
- + }
- + // phone was not verified - don'tshow tfa
- + return FALSE;
- + }
- +
- + public function getForm(array $form, \Drupal\Core\Form\FormStateInterface $form_state) {
- + $form['code'] = array(
- + '#type' => 'textfield',
- + '#title' => t('Verification Code'),
- + '#required' => TRUE,
- + '#description' => t('Enter @length-character code sent to your device.', array('@length' => $this->codeLength)),
- + );
- + $form['actions']['#type'] = 'actions';
- + // @todo optionally report on when code was sent/delivered.
- + $form['actions']['login'] = array(
- + '#type' => 'submit',
- + '#value' => t('Verify'),
- + );
- + $form['actions']['resend'] = array(
- + '#type' => 'submit',
- + '#value' => t('Resend'),
- + '#submit' => array('tfa_form_submit'),
- + '#limit_validation_errors' => array(),
- + );
- + return $form;
- + }
- +
- + public function validateForm(array $form, FormStateInterface $form_state) {
- + if ((string) $form_state->getValue('op') === (string) $form_state->getValue('resend')) {
- + // if sms_basic_sms exists and is blank a new code will be sent
- + $this->setUserData('tfa', ['tfa_basic_sms' => ''], $this->uid, $this->userData);
- + $form_state->setFormState(array(NULL));
- + return FALSE;
- + }
- + elseif (!parent::validate((string) $form_state->getValue('code'))) {
- + $this->errorMessages['code'] = t('Invalid code.');
- + return FALSE;
- + }
- + else {
- + // Once the code is validated do we need to clear the resend value and the code value?
- + $this->setUserData('tfa', ['tfa_basic_sms' => ''], $this->uid, $this->userData);
- + $form_state->setFormState(array(NULL));
- + return TRUE;
- + }
- + }
- +
- + public function submitForm(array $form, FormStateInterface &$form_state) {
- +
- + if ((string) $form_state->getValue('op') === (string) $form_state->getValue('resend')) {
- + $this->code = $this->generate();
- +
- + if (!$this->sendCode($this->code)) {
- + drupal_set_message(t('Unable to deliver the code. Please contact support.'), 'error');
- + }
- + else {
- + // Once the code is validated do we need to clear the resend value and the code value
- + $this->setUserData('tfa', ['tfa_basic_sms' => $this->code], $this->uid, $this->userData);
- + drupal_set_message(t('Code resent'));
- + }
- + return FALSE;
- + }
- + else {
- + return parent::submitForm($form, $form_state);
- + }
- + }
- +
- + /**
- + * Return context for this plugin.
- + *
- + * @return array
- + */
- + public function getPluginContext() {
- + return array(
- + 'code' => $this->code,
- + );
- + }
- +
- + protected function generate() {
- + $characters = '0123456789';
- + $string = '';
- + $max = strlen($characters) - 1;
- + for ($p = 0; $p < $this->codeLength; $p++) {
- + $string .= $characters[mt_rand(0, $max)];
- + }
- + return $string;
- + }
- +
- + protected function getAccountNumber() {
- + return $this->mobileNumber;
- + }
- +
- + /**
- + * Send the code via the client.
- + *
- + * @param string $code
- + * @return bool
- + */
- + protected function sendCode($code) {
- +
- + // $to = $this->getAccountNumber();
- + try {
- + // $message = $this->client->sendMessage($this->twilioNumber, $to, t($this->messageText, array('!code' => $code)));
- + $message = $this->client->messages->create(
- + $this->mobileNumber, // Text this number
- + array(
- + 'from' => $this->twilioNumber, // From a valid Twilio number
- + 'body' => t($this->messageText . " : " . $code)
- + )
- +
- + );
- + /*
- + // @todo Consider storing date_sent or date_updated to inform user.
- + watchdog('tfa_basic', 'Message !id sent to user !uid on @sent', array(
- + '@sent' => $message->date_sent,
- + '!id' => $message->sid,
- + '!uid' => $this->context['uid'],
- + ), WATCHDOG_INFO);
- + */
- +
- + $this->user->set('tfa', $this->userId, 'tfa_basic_sms', $code);
- + return TRUE;
- + } catch (SmsException $e) {
- + /*
- + // @todo Consider more detailed reporting by mapping Twilio error codes to
- + // messages.
- + watchdog('tfa_basic', 'Twilio send message error to user !uid @code @link', array(
- + '!uid' => $this->context['uid'],
- + '@code' => $e->getStatus(),
- + '@link' => $e->getInfo(),
- + ), WATCHDOG_ERROR);
- + */
- + return FALSE;
- + }
- + }
- +
- + /**
- + * {@inheritdoc}
- + */
- + public function isFallback() {
- + return TRUE;
- + }
- +
- + /**
- + * {@inheritdoc}
- + */
- + public function getFallbacks() {
- + return ($this->pluginDefinition['fallbacks']) ?: '';
- + }
- +}
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement