Skip to content
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

Extract all email verification logic to service #7

Merged
merged 1 commit into from
Apr 19, 2021
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
19 changes: 12 additions & 7 deletions phpstan.neon
Original file line number Diff line number Diff line change
@@ -1,11 +1,16 @@
includes:
- vendor/nunomaduro/larastan/extension.neon
- vendor/phpstan/phpstan-mockery/extension.neon
- vendor/phpstan/phpstan-phpunit/extension.neon
- vendor/phpstan/phpstan-phpunit/rules.neon
- vendor/thecodingmachine/phpstan-safe-rule/phpstan-safe-rule.neon
- vendor/nunomaduro/larastan/extension.neon
- vendor/phpstan/phpstan-mockery/extension.neon
- vendor/phpstan/phpstan-phpunit/extension.neon
- vendor/phpstan/phpstan-phpunit/rules.neon
- vendor/thecodingmachine/phpstan-safe-rule/phpstan-safe-rule.neon

parameters:
level: max
paths:
- src
- tests
- src
- tests
ignoreErrors:
-
message: '#Parameter \#1 \$(function|callback) of function call_user_func expects callable\(\): mixed, Closure\|null given\.#'
path: tests/Integration/Services/EmailVerificationServiceTest.php
20 changes: 20 additions & 0 deletions src/Contracts/Services/EmailVerificationServiceInterface.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
<?php

declare(strict_types=1);

namespace DanielDeWit\LighthouseSanctum\Contracts\Services;

use Illuminate\Auth\AuthenticationException;
use Illuminate\Contracts\Auth\MustVerifyEmail;

interface EmailVerificationServiceInterface
{
public function setVerificationUrl(string $url): void;

/**
* @param MustVerifyEmail $user
* @param string $hash
* @throws AuthenticationException
*/
public function verify(MustVerifyEmail $user, string $hash): void;
}
31 changes: 12 additions & 19 deletions src/GraphQL/Mutations/Register.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,12 +4,12 @@

namespace DanielDeWit\LighthouseSanctum\GraphQL\Mutations;

use DanielDeWit\LighthouseSanctum\Contracts\Services\EmailVerificationServiceInterface;
use DanielDeWit\LighthouseSanctum\Enums\RegisterStatus;
use DanielDeWit\LighthouseSanctum\Traits\CreatesUserProvider;
use Exception;
use Illuminate\Auth\AuthManager;
use Illuminate\Auth\EloquentUserProvider;
use Illuminate\Auth\Notifications\VerifyEmail;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Contracts\Config\Repository as Config;

Expand All @@ -19,11 +19,16 @@ class Register

protected AuthManager $authManager;
protected Config $config;

public function __construct(AuthManager $authManager, Config $config)
{
$this->authManager = $authManager;
$this->config = $config;
protected EmailVerificationServiceInterface $emailVerificationService;

public function __construct(
AuthManager $authManager,
Config $config,
EmailVerificationServiceInterface $emailVerificationService
) {
$this->authManager = $authManager;
$this->config = $config;
$this->emailVerificationService = $emailVerificationService;
}

/**
Expand All @@ -43,19 +48,7 @@ public function __invoke($_, array $args): array

if ($user instanceof MustVerifyEmail) {
if ($args['verification_url']) {
VerifyEmail::createUrlUsing(function ($notifiable) use ($args) {
$urlWithHash = str_replace(
'{{HASH}}',
sha1($notifiable->getEmailForVerification()),
$args['verification_url'],
);

return str_replace(
'{{ID}}',
$notifiable->getKey(),
$urlWithHash,
);
});
$this->emailVerificationService->setVerificationUrl($args['verification_url']);
}

$user->sendEmailVerificationNotification();
Expand Down
24 changes: 13 additions & 11 deletions src/GraphQL/Mutations/VerifyEmail.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,13 @@

namespace DanielDeWit\LighthouseSanctum\GraphQL\Mutations;

use DanielDeWit\LighthouseSanctum\Contracts\Services\EmailVerificationServiceInterface;
use DanielDeWit\LighthouseSanctum\Enums\EmailVerificationStatus;
use DanielDeWit\LighthouseSanctum\Traits\CreatesUserProvider;
use Exception;
use Illuminate\Auth\AuthManager;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Contracts\Config\Repository as Config;
use Illuminate\Support\Facades\Validator;
use Nuwave\Lighthouse\Exceptions\ValidationException;
use RuntimeException;

class VerifyEmail
Expand All @@ -19,18 +19,23 @@ class VerifyEmail

protected AuthManager $authManager;
protected Config $config;
protected EmailVerificationServiceInterface $emailVerificationService;

public function __construct(AuthManager $authManager, Config $config)
{
$this->authManager = $authManager;
$this->config = $config;
public function __construct(
AuthManager $authManager,
Config $config,
EmailVerificationServiceInterface $emailVerificationService
) {
$this->authManager = $authManager;
$this->config = $config;
$this->emailVerificationService = $emailVerificationService;
}

/**
* @param mixed $_
* @param array<string, string|int> $args
* @return array<string, EmailVerificationStatus>
* @throws ValidationException
* @throws Exception
*/
public function __invoke($_, array $args): array
{
Expand All @@ -42,10 +47,7 @@ public function __invoke($_, array $args): array
throw new RuntimeException('User not instance of MustVerifyEmail');
}

if (! hash_equals((string) $args['hash'],
sha1($user->getEmailForVerification()))) {
throw new ValidationException('The provided id and hash are incorrect.', Validator::make([], []));
}
$this->emailVerificationService->verify($user, (string) $args['hash']);

$user->markEmailAsVerified();

Expand Down
7 changes: 7 additions & 0 deletions src/Providers/LighthouseSanctumServiceProvider.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,11 @@

namespace DanielDeWit\LighthouseSanctum\Providers;

use DanielDeWit\LighthouseSanctum\Contracts\Services\EmailVerificationServiceInterface;
use DanielDeWit\LighthouseSanctum\Enums\EmailVerificationStatus;
use DanielDeWit\LighthouseSanctum\Enums\LogoutStatus;
use DanielDeWit\LighthouseSanctum\Enums\RegisterStatus;
use DanielDeWit\LighthouseSanctum\Services\EmailVerificationService;
use Illuminate\Contracts\Events\Dispatcher;
use Illuminate\Support\ServiceProvider;
use Nuwave\Lighthouse\Schema\TypeRegistry;
Expand All @@ -16,6 +18,11 @@ class LighthouseSanctumServiceProvider extends ServiceProvider
{
protected TypeRegistry $typeRegistry;

public function register(): void
{
$this->app->singleton(EmailVerificationServiceInterface::class, EmailVerificationService::class);
}

public function boot(Dispatcher $dispatcher, TypeRegistry $typeRegistry): void
{
$this->typeRegistry = $typeRegistry;
Expand Down
43 changes: 43 additions & 0 deletions src/Services/EmailVerificationService.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
<?php

declare(strict_types=1);

namespace DanielDeWit\LighthouseSanctum\Services;

use DanielDeWit\LighthouseSanctum\Contracts\Services\EmailVerificationServiceInterface;
use Illuminate\Auth\Notifications\VerifyEmail;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Nuwave\Lighthouse\Exceptions\AuthenticationException;

class EmailVerificationService implements EmailVerificationServiceInterface
{
public function setVerificationUrl(string $url): void
{
VerifyEmail::createUrlUsing(function ($notifiable) use ($url) {
return str_replace([
'{{ID}}',
'{{HASH}}'
], [
$notifiable->getKey(),
$this->createHash($notifiable),
], $url);
});
}

/**
* @param MustVerifyEmail $user
* @param string $hash
* @throws AuthenticationException
*/
public function verify(MustVerifyEmail $user, string $hash): void
{
if (! hash_equals($hash, $this->createHash($user))) {
throw new AuthenticationException('The provided id and hash are incorrect.');
}
}

protected function createHash(MustVerifyEmail $user): string
{
return sha1($user->getEmailForVerification());
}
}
54 changes: 54 additions & 0 deletions tests/Integration/Services/EmailVerificationServiceTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
<?php

declare(strict_types=1);

namespace DanielDeWit\LighthouseSanctum\Tests\Integration\Services;

use DanielDeWit\LighthouseSanctum\Services\EmailVerificationService;
use DanielDeWit\LighthouseSanctum\Tests\Integration\AbstractIntegrationTest;
use DanielDeWit\LighthouseSanctum\Tests\stubs\Users\UserMustVerifyEmail;
use Illuminate\Auth\Notifications\VerifyEmail;
use Nuwave\Lighthouse\Exceptions\AuthenticationException;

class EmailVerificationServiceTest extends AbstractIntegrationTest
{
protected EmailVerificationService $service;

protected function setUp(): void
{
parent::setUp();

$this->service = new EmailVerificationService();
}

/**
* @test
*/
public function it_sets_the_verification_url(): void
{
/** @var UserMustVerifyEmail $user */
$user = UserMustVerifyEmail::factory()->create([
'id' => 12345,
'email' => 'user@example.com',
]);

$this->service->setVerificationUrl('https://mysite.com/verify-email/{{ID}}/{{HASH}}');

$url = call_user_func(VerifyEmail::$createUrlCallback, $user);

static::assertSame('https://mysite.com/verify-email/12345/' . sha1($user->getEmailForVerification()), $url);
}

/**
* @test
*/
public function it_throws_an_exception_if_the_hash_is_incorrect(): void
{
static::expectException(AuthenticationException::class);
static::expectExceptionMessage('The provided id and hash are incorrect.');

$user = UserMustVerifyEmail::factory()->create();

$this->service->verify($user, 'foobar');
}
}
64 changes: 64 additions & 0 deletions tests/Unit/Services/EmailVerificationServiceTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
<?php

declare(strict_types=1);

namespace DanielDeWit\LighthouseSanctum\Tests\Unit\Services;

use DanielDeWit\LighthouseSanctum\Services\EmailVerificationService;
use DanielDeWit\LighthouseSanctum\Tests\Unit\AbstractUnitTest;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Mockery;
use Mockery\MockInterface;
use Nuwave\Lighthouse\Exceptions\AuthenticationException;

class EmailVerificationServiceTest extends AbstractUnitTest
{
protected EmailVerificationService $service;

protected function setUp(): void
{
parent::setUp();

$this->service = new EmailVerificationService();
}

/**
* @test
*/
public function it_throws_an_exception_if_the_hash_is_incorrect(): void
{
static::expectException(AuthenticationException::class);
static::expectExceptionMessage('The provided id and hash are incorrect.');

$this->service->verify(
$this->mockUser('user@example.com'),
sha1('foo@bar.com'),
);
}

/**
* @test
*/
public function it_does_nothing_if_the_hash_is_correct(): void
{
$this->service->verify(
$this->mockUser('user@example.com'),
sha1('user@example.com'),
);
}

/**
* @param string $email
* @return MustVerifyEmail|MockInterface
*/
protected function mockUser(string $email)
{
/** @var MustVerifyEmail|MockInterface $user */
$user = Mockery::mock(MustVerifyEmail::class)
->shouldReceive('getEmailForVerification')
->andReturn($email)
->getMock();

return $user;
}
}