Skip to content

Password reset #154

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 3 commits into from
Jul 27, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions config/services/managers.yml
Original file line number Diff line number Diff line change
Expand Up @@ -52,3 +52,6 @@ services:
autowire: true
autoconfigure: true

PhpList\Core\Domain\Identity\Service\PasswordManager:
autowire: true
autoconfigure: true
179 changes: 179 additions & 0 deletions src/Identity/Controller/PasswordResetController.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,179 @@
<?php

declare(strict_types=1);

namespace PhpList\RestBundle\Identity\Controller;

use OpenApi\Attributes as OA;
use PhpList\Core\Domain\Identity\Service\PasswordManager;
use PhpList\Core\Security\Authentication;
use PhpList\RestBundle\Common\Controller\BaseController;
use PhpList\RestBundle\Common\Validator\RequestValidator;
use PhpList\RestBundle\Identity\Request\RequestPasswordResetRequest;
use PhpList\RestBundle\Identity\Request\ResetPasswordRequest;
use PhpList\RestBundle\Identity\Request\ValidateTokenRequest;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Attribute\Route;

/**
* This controller provides methods to reset admin passwords.
*/
#[Route('/password-reset', name: 'password_reset_')]
class PasswordResetController extends BaseController
{
private PasswordManager $passwordManager;

public function __construct(
Authentication $authentication,
RequestValidator $validator,
PasswordManager $passwordManager,
) {
parent::__construct($authentication, $validator);

$this->passwordManager = $passwordManager;
}

#[Route('/request', name: 'request', methods: ['POST'])]
#[OA\Post(
path: '/api/v2/password-reset/request',
description: 'Request a password reset token for an administrator account.',
summary: 'Request a password reset.',
requestBody: new OA\RequestBody(
description: 'Administrator email',
required: true,
content: new OA\JsonContent(
required: ['email'],
properties: [
new OA\Property(property: 'email', type: 'string', format: 'email', example: '[email protected]'),
]
)
),
tags: ['password-reset'],
responses: [
new OA\Response(
response: 204,
description: 'Password reset token generated',
),
new OA\Response(
response: 400,
description: 'Failure',
content: new OA\JsonContent(ref: '#/components/schemas/BadRequestResponse')
),
new OA\Response(
response: 404,
description: 'Failure',
content: new OA\JsonContent(ref: '#/components/schemas/NotFoundErrorResponse')
)
]
)]
public function requestPasswordReset(Request $request): JsonResponse
{
/** @var RequestPasswordResetRequest $resetRequest */
$resetRequest = $this->validator->validate($request, RequestPasswordResetRequest::class);

$this->passwordManager->generatePasswordResetToken($resetRequest->email);

return $this->json(null, Response::HTTP_NO_CONTENT);
}

#[Route('/validate', name: 'validate', methods: ['POST'])]
#[OA\Post(
path: '/api/v2/password-reset/validate',
description: 'Validate a password reset token.',
summary: 'Validate a password reset token.',
requestBody: new OA\RequestBody(
description: 'Password reset token',
required: true,
content: new OA\JsonContent(
required: ['token'],
properties: [
new OA\Property(property: 'token', type: 'string', example: 'a1b2c3d4e5f6'),
]
)
),
tags: ['password-reset'],
responses: [
new OA\Response(
response: 200,
description: 'Success',
content: new OA\JsonContent(
properties: [
new OA\Property(property: 'valid', type: 'boolean', example: true),
]
)
),
new OA\Response(
response: 400,
description: 'Failure',
content: new OA\JsonContent(ref: '#/components/schemas/BadRequestResponse')
)
]
)]
public function validateToken(Request $request): JsonResponse
{
/** @var ValidateTokenRequest $validateRequest */
$validateRequest = $this->validator->validate($request, ValidateTokenRequest::class);

$administrator = $this->passwordManager->validatePasswordResetToken($validateRequest->token);

return $this->json([ 'valid' => $administrator !== null]);
}

#[Route('/reset', name: 'reset', methods: ['POST'])]
#[OA\Post(
path: '/api/v2/password-reset/reset',
description: 'Reset an administrator password using a token.',
summary: 'Reset password with token.',
requestBody: new OA\RequestBody(
description: 'Password reset information',
required: true,
content: new OA\JsonContent(
required: ['token', 'newPassword'],
properties: [
new OA\Property(property: 'token', type: 'string', example: 'a1b2c3d4e5f6'),
new OA\Property(
property: 'newPassword',
type: 'string',
format: 'password',
example: 'newSecurePassword123',
),
]
)
),
tags: ['password-reset'],
responses: [
new OA\Response(
response: 200,
description: 'Success',
content: new OA\JsonContent(
properties: [
new OA\Property(property: 'message', type: 'string', example: 'Password updated successfully'),
]
)
),
new OA\Response(
response: 400,
description: 'Invalid or expired token',
content: new OA\JsonContent(ref: '#/components/schemas/BadRequestResponse')
)
]
)]
public function resetPassword(Request $request): JsonResponse
{
/** @var ResetPasswordRequest $resetRequest */
$resetRequest = $this->validator->validate($request, ResetPasswordRequest::class);

$success = $this->passwordManager->updatePasswordWithToken(
$resetRequest->token,
$resetRequest->newPassword
);

if ($success) {
return $this->json([ 'message' => 'Password updated successfully']);
}

return $this->json(['message' => 'Invalid or expired token'], Response::HTTP_BAD_REQUEST);
}
}
21 changes: 21 additions & 0 deletions src/Identity/Request/RequestPasswordResetRequest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
<?php

declare(strict_types=1);

namespace PhpList\RestBundle\Identity\Request;

use PhpList\RestBundle\Common\Request\RequestInterface;
use Symfony\Component\Validator\Constraints as Assert;

class RequestPasswordResetRequest implements RequestInterface
{
#[Assert\NotBlank]
#[Assert\Email]
#[Assert\Type(type: 'string')]
public string $email;

public function getDto(): RequestPasswordResetRequest
{
return $this;
}
}
25 changes: 25 additions & 0 deletions src/Identity/Request/ResetPasswordRequest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
<?php

declare(strict_types=1);

namespace PhpList\RestBundle\Identity\Request;

use PhpList\RestBundle\Common\Request\RequestInterface;
use Symfony\Component\Validator\Constraints as Assert;

class ResetPasswordRequest implements RequestInterface
{
#[Assert\NotBlank]
#[Assert\Type(type: 'string')]
public string $token;

#[Assert\NotBlank]
#[Assert\Type(type: 'string')]
#[Assert\Length(min: 8)]
public string $newPassword;

public function getDto(): ResetPasswordRequest
{
return $this;
}
}
20 changes: 20 additions & 0 deletions src/Identity/Request/ValidateTokenRequest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
<?php

declare(strict_types=1);

namespace PhpList\RestBundle\Identity\Request;

use PhpList\RestBundle\Common\Request\RequestInterface;
use Symfony\Component\Validator\Constraints as Assert;

class ValidateTokenRequest implements RequestInterface
{
#[Assert\NotBlank]
#[Assert\Type(type: 'string')]
public string $token;

public function getDto(): ValidateTokenRequest
{
return $this;
}
}
108 changes: 108 additions & 0 deletions tests/Integration/Identity/Controller/PasswordResetControllerTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,108 @@
<?php

declare(strict_types=1);

namespace PhpList\RestBundle\Tests\Integration\Identity\Controller;

use PhpList\RestBundle\Identity\Controller\PasswordResetController;
use PhpList\RestBundle\Tests\Integration\Common\AbstractTestController;
use PhpList\RestBundle\Tests\Integration\Identity\Fixtures\AdministratorFixture;

class PasswordResetControllerTest extends AbstractTestController
{
public function testControllerIsAvailableViaContainer(): void
{
self::assertInstanceOf(
PasswordResetController::class,
self::getContainer()->get(PasswordResetController::class)
);
}

public function testRequestPasswordResetWithNoJsonReturnsError400(): void
{
$this->jsonRequest('post', '/api/v2/password-reset/request');

$this->assertHttpBadRequest();
$data = $this->getDecodedJsonResponseContent();
$this->assertStringContainsString('Invalid JSON:', $data['message']);
}

public function testRequestPasswordResetWithInvalidEmailReturnsError422(): void
{
$jsonData = json_encode(['email' => 'not-an-email']);
$this->jsonRequest('post', '/api/v2/password-reset/request', [], [], [], $jsonData);

$this->assertHttpUnprocessableEntity();
$data = $this->getDecodedJsonResponseContent();
$this->assertStringContainsString('This value is not a valid email address', $data['message']);
}

public function testRequestPasswordResetWithNonExistentEmailReturnsError404(): void
{
$this->loadFixtures([AdministratorFixture::class]);
$jsonData = json_encode(['email' => '[email protected]']);
$this->jsonRequest('post', '/api/v2/password-reset/request', [], [], [], $jsonData);

$this->assertHttpNotFound();
}

public function testRequestPasswordResetWithValidEmailReturnsSuccess(): void
{
$this->loadFixtures([AdministratorFixture::class]);
$jsonData = json_encode(['email' => '[email protected]']);
$this->jsonRequest('post', '/api/v2/password-reset/request', [], [], [], $jsonData);

$this->assertHttpNoContent();
}

public function testValidateTokenWithNoJsonReturnsError400(): void
{
$this->jsonRequest('post', '/api/v2/password-reset/validate');

$this->assertHttpBadRequest();
$data = $this->getDecodedJsonResponseContent();
$this->assertStringContainsString('Invalid JSON:', $data['message']);
}

public function testValidateTokenWithInvalidTokenReturnsInvalidResult(): void
{
$this->loadFixtures([AdministratorFixture::class]);
$jsonData = json_encode(['token' => 'invalid-token']);
$this->jsonRequest('post', '/api/v2/password-reset/validate', [], [], [], $jsonData);

$this->assertHttpOkay();
$data = $this->getDecodedJsonResponseContent();
$this->assertFalse($data['valid']);
}

public function testResetPasswordWithNoJsonReturnsError400(): void
{
$this->jsonRequest('post', '/api/v2/password-reset/reset');

$this->assertHttpBadRequest();
$data = $this->getDecodedJsonResponseContent();
$this->assertStringContainsString('Invalid JSON:', $data['message']);
}

public function testResetPasswordWithInvalidTokenReturnsBadRequest(): void
{
$this->loadFixtures([AdministratorFixture::class]);
$jsonData = json_encode(['token' => 'invalid-token', 'newPassword' => 'newPassword123']);
$this->jsonRequest('post', '/api/v2/password-reset/reset', [], [], [], $jsonData);

$this->assertHttpBadRequest();
$data = $this->getDecodedJsonResponseContent();
$this->assertEquals('Invalid or expired token', $data['message']);
}

public function testResetPasswordWithShortPasswordReturnsError422(): void
{
$this->loadFixtures([AdministratorFixture::class]);
$jsonData = json_encode(['token' => 'valid-token', 'newPassword' => 'short']);
$this->jsonRequest('post', '/api/v2/password-reset/reset', [], [], [], $jsonData);

$this->assertHttpUnprocessableEntity();
$data = $this->getDecodedJsonResponseContent();
$this->assertStringContainsString('This value is too short', $data['message']);
}
}
22 changes: 22 additions & 0 deletions tests/Unit/Identity/Request/RequestPasswordResetRequestTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
<?php

declare(strict_types=1);

namespace PhpList\RestBundle\Tests\Unit\Identity\Request;

use PhpList\RestBundle\Identity\Request\RequestPasswordResetRequest;
use PHPUnit\Framework\TestCase;

class RequestPasswordResetRequestTest extends TestCase
{
public function testGetDtoReturnsSelf(): void
{
$request = new RequestPasswordResetRequest();
$request->email = '[email protected]';

$dto = $request->getDto();

$this->assertSame($request, $dto);
$this->assertEquals('[email protected]', $dto->email);
}
}
Loading
Loading