user_api-1.0.0-beta1/modules/user_api_passwordless/src/Plugin/rest/resource/InitUnsetPasswordResource.php
modules/user_api_passwordless/src/Plugin/rest/resource/InitUnsetPasswordResource.php
<?php
declare(strict_types=1);
namespace Drupal\user_api_passwordless\Plugin\rest\resource;
use Drupal\Component\Serialization\Json;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Session\AccountProxyInterface;
use Drupal\Core\StringTranslation\TranslatableMarkup;
use Drupal\rest\Attribute\RestResource;
use Drupal\rest\Plugin\ResourceBase;
use Drupal\user\UserInterface;
use Drupal\user_api\ErrorCode;
use Drupal\user_api_passwordless\Event\InitUnsetPasswordEvent;
use Psr\Log\LoggerInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Contracts\EventDispatcher\EventDispatcherInterface;
use Wunderwerk\HttpApiUtils\HttpApiValidationTrait;
use Wunderwerk\JsonApiError\JsonApiErrorResponse;
/**
* Provides a resource to initialize flow to unset a user's password.
*/
#[RestResource(
id: "user_api_passwordless_init_unset_password",
label: new TranslatableMarkup("Initialize unset user password"),
uri_paths: [
"create" => "/user-api/unset-password/init",
]
)]
class InitUnsetPasswordResource extends ResourceBase {
use HttpApiValidationTrait;
/**
* Request payload schema.
*/
protected array $schema = [
'type' => 'object',
'properties' => [
'email' => [
'type' => 'string',
'format' => 'email',
],
],
'required' => ['email'],
];
/**
* The user entity.
*/
protected UserInterface $user;
/**
* Constructs a new InitSetPasswordResource object.
*/
public function __construct(
array $configuration,
$plugin_id,
$plugin_definition,
array $serializer_formats,
LoggerInterface $logger,
protected AccountProxyInterface $currentUser,
protected EntityTypeManagerInterface $entityTypeManager,
protected EventDispatcherInterface $eventDispatcher,
) {
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('current_user'),
$container->get('entity_type.manager'),
$container->get('event_dispatcher'),
);
}
/**
* Responds to POST requests.
*
* @return \Symfony\Component\HttpFoundation\JsonResponse
* The response indicating success or failure.
*/
public function post(Request $request) {
$jsonBody = $request->getContent();
$data = Json::decode($jsonBody);
$result = $this->validateArray($data, $this->schema);
if (!$result->isValid()) {
return $result->getResponse();
}
$result = $this->entityTypeManager->getStorage('user')->loadByProperties([
'mail' => $data['email'],
]);
if (empty($result)) {
return JsonApiErrorResponse::fromError(
status: 400,
code: ErrorCode::InvalidEmail->getCode(),
title: 'Invalid email address.'
);
}
/** @var \Drupal\user\UserInterface $user */
$user = reset($result);
$currentUser = $this->getCurrentUser();
// If user is logged in, the reset password email can only be sent
// if the requested email matches that of the authenticated account.
if ($currentUser->isAuthenticated() && $currentUser->id() !== $user->id()) {
return JsonApiErrorResponse::fromError(
status: 403,
code: ErrorCode::EmailNotMatching->getCode(),
title: 'E-Mail address does not match'
);
}
// Dispatch event.
$event = new InitUnsetPasswordEvent($user);
$this->eventDispatcher->dispatch($event, $event::getName());
if ($event->isAborted()) {
return $event->getResponse();
}
_user_api_passwordless_mail_notify('unset_password', $user);
return new JsonResponse([
'status' => 'success',
]);
}
/**
* Loads the user entity for the current user.
*
* @return \Drupal\user\UserInterface|null
* The user entity.
*/
protected function getCurrentUser(): ?UserInterface {
return $this->entityTypeManager->getStorage('user')->load(
$this->currentUser->id()
);
}
}
