Commit 8ecb760a authored by Fabian de Rijk's avatar Fabian de Rijk
Browse files

Issue #3271664: Convert O365ProfileAjaxController to a proper REST service

parent c7bea50b
Loading
Loading
Loading
Loading
+16 −0
Original line number Diff line number Diff line
status: true
dependencies:
  module:
    - o365_profile
    - serialization
    - user
id: o365_profile_rest_status
plugin_id: o365_profile_rest_status
granularity: resource
configuration:
  methods:
    - GET
  formats:
    - json
  authentication:
    - cookie
+9 −0
Original line number Diff line number Diff line
name: 'Office 365 - Profiles and Personas REST endpoints'
type: module
description: 'Profile and Persona data from Office 365 accessible in REST'
core_version_requirement: ^8 || ^9
package: 'Microsoft Office'
dependencies:
  - drupal:rest
  - o365:o365_profile
  - externalauth:externalauth
+25 −0
Original line number Diff line number Diff line
<?php

/**
 * @file
 * Install and update hooks for the o365_profile_rest module.
 */

use Drupal\user\Entity\Role;

function o365_profile_rest_install() {
  // Set permissions for authenticated users.
  $role_object = Role::load('authenticated');
  $role_object->grantPermission('restful get o365_profile_rest_status');
  $role_object->save();
}

/**
 * Permissions for authenticated users: 'restful get o365_profile_rest_status'.
 */
function o365_profile_rest_update_9001() {
  // Set permissions for authenticated users.
  $role_object = Role::load('authenticated');
  $role_object->grantPermission('restful get o365_profile_rest_status');
  $role_object->save();
}
+141 −0
Original line number Diff line number Diff line
<?php

namespace Drupal\o365_profile_rest\Plugin\rest\resource;

use Drupal\Component\Utility\Html;
use Drupal\Core\StringTranslation\TranslatableMarkup;
use Drupal\externalauth\Authmap;
use Drupal\o365_profile\O365ProfileGetDataService;
use Drupal\rest\Plugin\ResourceBase;
use Drupal\rest\ResourceResponse;
use Drupal\user\Entity\User;
use Psr\Log\LoggerInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\HttpKernel\Exception\BadRequestHttpException;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;

/**
 * Provides a resource for get the Office 365 profile data.
 *
 * @RestResource(
 *   id = "o365_profile_rest_status",
 *   label = @Translation("Office 365 Connector - Profile status"),
 *   uri_paths = {
 *     "canonical" = "/o365/profile_rest/user_status/{uid}"
 *   }
 * )
 */
class O365ProfileRestResource extends ResourceBase {

  /**
   * The externalauth authmap service.
   *
   * @var \Drupal\externalauth\Authmap
   */
  protected $authmap;

  /**
   * The service we use to get user data.
   *
   * @var \Drupal\o365_profile\O365ProfileGetDataService
   */
  protected $getDataService;

  /**
   * The resource constructor.
   */
  public function __construct(array $configuration, $plugin_id, $plugin_definition, array $serializer_formats, LoggerInterface $logger, Authmap $authmap, O365ProfileGetDataService $getDataService) {
    $this->authmap = $authmap;
    $this->getDataService = $getDataService;
    parent::__construct($configuration, $plugin_id, $plugin_definition, $serializer_formats, $logger);
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
    return new static(
      $configuration,
      $plugin_id,
      $plugin_definition,
      $container->getParameter('serializer.formats'),
      $container->get('logger.factory')->get('rest'),
      $container->get('externalauth.authmap'),
      $container->get('o365_profile.get_data')
    );
  }

  public function get($uid = NULL) {
    if ($uid) {
      $auth = $this->authmap->get($uid, 'o365_sso');

      if (!empty($auth)) {
        $user = User::load($uid);
        if ($user) {
          $return = [];
          $return['mail'] = $user->getEmail();
          $return['displayName'] = $user->getDisplayName();

          $userData = $this->getDataService->getProfileData($auth);
          $return['initials'] = $userData['initials'];
          $return['user_img'] = $userData['imageSrc'];

          if (isset($userData['presenceData']['activity']) && !empty($userData['presenceData']['activity'])) {
            $return['presence'] = $userData['presenceData']['activity'];
            $class = Html::cleanCssIdentifier($userData['presenceData']['activity']);
            $return['presence_class'] = strtolower($class);
          }

          if (isset($userData['userData']['givenName']) && !empty($userData['userData']['givenName'])) {
            $return['givenName'] = $userData['userData']['givenName'];
          }

          if (isset($userData['userData']['surname']) && !empty($userData['userData']['surname'])) {
            $return['surname'] = $userData['userData']['surname'];
          }

          if (isset($userData['userData']['businessPhones']) && !empty($userData['userData']['businessPhones'])) {
            $businessText = new TranslatableMarkup('Call on business phone');
            $return['businessPhones'] = [
              'number' => $userData['userData']['businessPhones'][0],
              'text' => $businessText->render(),
            ];
          }

          if (isset($userData['userData']['mobilePhone']) && !empty($userData['userData']['mobilePhone'])) {
            $mobileText = new TranslatableMarkup('Call on mobile phone');
            $return['mobilePhone'] = [
              'number' => $userData['userData']['mobilePhone'],
              'text' => $mobileText->render(),
            ];
          }

          $callText = new TranslatableMarkup('Call with Teams');
          $return['call'] = [
            'url' => 'https://teams.microsoft.com/l/call/0/0?users=' . $user->getEmail(),
            'text' => $callText->render(),
          ];
          $chatText = new TranslatableMarkup('Chat with Teams');
          $return['chat'] = [
            'url' => 'https://teams.microsoft.com/l/chat/0/0?users=' . $user->getEmail(),
            'text' => $chatText->render(),
          ];
          $videocallText = new TranslatableMarkup('Video call with Teams');
          $return['videocall'] = [
            'url' => 'https://teams.microsoft.com/l/call/0/0?users=' . $user->getEmail() . '&Withvideo=true',
            'text' => $videocallText->render(),
          ];

          return new ResourceResponse($return);
        }

        throw new NotFoundHttpException("The user with ID '$uid' was not found.");
      }

      throw new NotFoundHttpException("The user with ID '$uid' was not found in the external auth map table.");
    }

    throw new BadRequestHttpException('No user ID was provided');
  }

}