You are here

protected function LTIToolProvider::provisionUser in LTI Tool Provider 8

Same name and namespace in other branches
  1. 2.x src/Authentication/Provider/LTIToolProvider.php \Drupal\lti_tool_provider\Authentication\Provider\LTIToolProvider::provisionUser()

Provision a user that matches the LTI request context info.

Throws

Exception

1 call to LTIToolProvider::provisionUser()
LTIToolProvider::authenticate in src/Authentication/Provider/LTIToolProvider.php
Authenticates the user.

File

src/Authentication/Provider/LTIToolProvider.php, line 293

Class

LTIToolProvider
Oauth authentication provider for LTI Tool Provider.

Namespace

Drupal\lti_tool_provider\Authentication\Provider

Code

protected function provisionUser() {
  try {
    $name = 'ltiuser';
    $mail = 'ltiuser@invalid';
    $name_param = $this->consumerEntity
      ->get('name')
      ->getValue()[0]['value'];
    if (isset($this->context[$name_param]) && !empty($this->context[$name_param])) {
      $name = $this->context[$name_param];
    }
    $mail_param = $this->consumerEntity
      ->get('mail')
      ->getValue()[0]['value'];
    if (isset($this->context[$mail_param]) && !empty($this->context[$mail_param])) {
      $mail = $this->context[$mail_param];
    }
    if ($users = $this->entityTypeManager
      ->getStorage('user')
      ->loadByProperties([
      'name' => $name,
      'status' => 1,
    ])) {
      $this->user = reset($users);
    }
    elseif ($users = $this->entityTypeManager
      ->getStorage('user')
      ->loadByProperties([
      'mail' => $mail,
      'status' => 1,
    ])) {
      $this->user = reset($users);
    }
    else {
      $this->user = User::create();
      $this->user
        ->setUsername($name);
      $this->user
        ->setEmail($mail);
      $this->user
        ->setPassword(user_password());
      $this->user
        ->enforceIsNew();
      $this->user
        ->activate();
      $event = new LtiToolProviderProvisionUserEvent($this->context, $this->user);
      LtiToolProviderEvent::dispatchEvent($this->eventDispatcher, $event);
      if ($event
        ->isCancelled()) {
        throw new Exception($event
          ->getMessage());
      }
      $this->context = $event
        ->getContext();
      $this->user = $event
        ->getUser();
      $this->user
        ->save();
    }
  } catch (Exception $e) {
    $this->loggerFactory
      ->warning($e
      ->getMessage());
    $this
      ->sendLtiError($e
      ->getMessage());
  }
}