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

Log in subscribers when broadcasting a subscription update #1306

Merged
merged 16 commits into from
Apr 19, 2020
Merged
Show file tree
Hide file tree
Changes from 4 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
1 change: 1 addition & 0 deletions composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@
"require": {
"php": ">= 7.1",
"ext-json": "*",
"illuminate/auth": "5.5.* || 5.6.* || 5.7.* || 5.8.* || ^6.0 || ^7.0",
"illuminate/contracts": "5.5.* || 5.6.* || 5.7.* || 5.8.* || ^6.0 || ^7.0",
"illuminate/http": "5.5.* || 5.6.* || 5.7.* || 5.8.* || ^6.0 || ^7.0",
"illuminate/pagination": "5.5.* || 5.6.* || 5.7.* || 5.8.* || ^6.0 || ^7.0",
Expand Down
13 changes: 11 additions & 2 deletions src/Subscriptions/Contracts/SubscriptionIterator.php
Original file line number Diff line number Diff line change
Expand Up @@ -8,9 +8,18 @@
interface SubscriptionIterator
{
/**
* Process collection of items.
* Process subscribers.
*
* @param \Illuminate\Support\Collection<\Nuwave\Lighthouse\Subscriptions\Subscriber> $subscribers
* The subscribers that receive the current subscription.
*
* @param \Closure $handleSubscriber
* Receives each subscriber in the passed in collection.
* function(\Nuwave\Lighthouse\Subscriptions\Subscriber $subscriber)
*
* @param \Closure|null $onError
* Is called when $handleSubscriber throws.
* @return void
*/
public function process(Collection $items, Closure $cb, Closure $error = null);
public function process(Collection $subscribers, Closure $handleSubscriber, Closure $onError = null);
stayallive marked this conversation as resolved.
Show resolved Hide resolved
}
66 changes: 66 additions & 0 deletions src/Subscriptions/Iterators/GuardContextSyncIterator.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
<?php

namespace Nuwave\Lighthouse\Subscriptions\Iterators;

use Closure;
use Exception;
use Illuminate\Contracts\Auth\Factory;
use Illuminate\Contracts\Config\Repository;
use Illuminate\Support\Collection;
use Nuwave\Lighthouse\Subscriptions\Contracts\SubscriptionIterator;
use Nuwave\Lighthouse\Subscriptions\Subscriber;
use Nuwave\Lighthouse\Subscriptions\SubscriptionGuard;

class GuardContextSyncIterator implements SubscriptionIterator
spawnia marked this conversation as resolved.
Show resolved Hide resolved
{
/**
* @var \Illuminate\Contracts\Config\Repository
*/
private $configRepository;

/**
* @var \Illuminate\Contracts\Auth\Factory
*/
private $authFactory;

public function __construct(Repository $configRepository, Factory $authFactory)
{
$this->authFactory = $authFactory;
$this->configRepository = $configRepository;
}

public function process(Collection $subscribers, Closure $handleSubscriber, Closure $onError = null): void
{
// Store the previous default guard name so we can restore it after we're done
$previousGuardName = $this->configRepository->get('auth.defaults.guard');

// Set our subscription guard as the default guard for the application
$this->authFactory->shouldUse(SubscriptionGuard::GUARD_NAME);

/** @var \Nuwave\Lighthouse\Subscriptions\SubscriptionGuard $guard */
$guard = $this->authFactory->guard(SubscriptionGuard::GUARD_NAME);

$subscribers->each(static function (Subscriber $item) use ($handleSubscriber, $onError, $guard): void {
// If there is an authenticated user set in the context, set that user as the authenticated user
if ($item->context->user()) {
$guard->setUser($item->context->user());
}

try {
$handleSubscriber($item);
} catch (Exception $e) {
if (! $onError) {
throw $e;
}

$onError($e);
} finally {
// Unset the authenticated user after each iteration to restore the guard to a unauthenticated state
$guard->reset();
}
});

// Restore the previous default guard name
$this->authFactory->shouldUse($previousGuardName);
}
}
13 changes: 5 additions & 8 deletions src/Subscriptions/Iterators/SyncIterator.php
Original file line number Diff line number Diff line change
Expand Up @@ -9,20 +9,17 @@

class SyncIterator implements SubscriptionIterator
{
/**
* Process collection of items.
*/
public function process(Collection $items, Closure $cb, Closure $error = null): void
public function process(Collection $subscribers, Closure $handleSubscriber, Closure $onError = null): void
{
$items->each(function ($item) use ($cb, $error): void {
$subscribers->each(static function ($item) use ($handleSubscriber, $onError): void {
try {
$cb($item);
$handleSubscriber($item);
} catch (Exception $e) {
if (! $error) {
if (! $onError) {
throw $e;
}

$error($e);
$onError($e);
}
});
}
Expand Down
29 changes: 29 additions & 0 deletions src/Subscriptions/SubscriptionGuard.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
<?php

namespace Nuwave\Lighthouse\Subscriptions;

use Illuminate\Auth\GuardHelpers;
use Illuminate\Contracts\Auth\Guard;
use RuntimeException;

class SubscriptionGuard implements Guard
{
use GuardHelpers;

public const GUARD_NAME = 'lighthouse_subscriptions';

public function user()
{
return $this->user;
}

public function reset()
{
$this->user = null;
}

public function validate(array $credentials = [])
{
throw new RuntimeException('The Lighthouse subscription guard cannot be used for credential based authentication.');
}
}
17 changes: 17 additions & 0 deletions src/Subscriptions/SubscriptionServiceProvider.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

namespace Nuwave\Lighthouse\Subscriptions;

use Illuminate\Auth\AuthManager;
use Illuminate\Contracts\Config\Repository as ConfigRepository;
use Illuminate\Contracts\Events\Dispatcher as EventsDispatcher;
use Illuminate\Support\ServiceProvider;
Expand All @@ -16,6 +17,7 @@
use Nuwave\Lighthouse\Subscriptions\Contracts\SubscriptionIterator;
use Nuwave\Lighthouse\Subscriptions\Events\BroadcastSubscriptionEvent;
use Nuwave\Lighthouse\Subscriptions\Events\BroadcastSubscriptionListener;
use Nuwave\Lighthouse\Subscriptions\Iterators\GuardContextSyncIterator;
use Nuwave\Lighthouse\Subscriptions\Iterators\SyncIterator;
use Nuwave\Lighthouse\Support\Contracts\ProvidesSubscriptionResolver;

Expand Down Expand Up @@ -50,6 +52,21 @@ public function boot(EventsDispatcher $eventsDispatcher, ConfigRepository $confi
$this->app->make('router')
);
}

// Test if the auth manager is bound to the container before using it in case the application is not using any authentication
if ($this->app->bound(AuthManager::class)) {
config([
'auth.guards.'.SubscriptionGuard::GUARD_NAME => [
'driver' => SubscriptionGuard::GUARD_NAME,
],
]);

$this->app->bind(SubscriptionIterator::class, GuardContextSyncIterator::class);

$this->app->make(AuthManager::class)->extend(SubscriptionGuard::GUARD_NAME, static function () {
return new SubscriptionGuard;
});
}
}

/**
Expand Down
12 changes: 1 addition & 11 deletions tests/Unit/Subscriptions/BroadcastManagerTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -9,24 +9,14 @@
use Nuwave\Lighthouse\Subscriptions\BroadcastManager;
use Nuwave\Lighthouse\Subscriptions\Contracts\Broadcaster;
use Nuwave\Lighthouse\Subscriptions\Subscriber;
use Nuwave\Lighthouse\Subscriptions\SubscriptionServiceProvider;
use Tests\TestCase;

class BroadcastManagerTest extends TestCase
class BroadcastManagerTest extends SubscriptionTestCase
{
/**
* @var \Nuwave\Lighthouse\Subscriptions\BroadcastManager
*/
protected $broadcastManager;

protected function getPackageProviders($app)
{
return array_merge(
parent::getPackageProviders($app),
[SubscriptionServiceProvider::class]
);
}

/**
* Set up test environment.
*/
Expand Down
173 changes: 173 additions & 0 deletions tests/Unit/Subscriptions/Iterators/GuardContextSyncIteratorTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,173 @@
<?php

namespace Tests\Unit\Subscriptions\Iterators;

use Exception;
use GraphQL\Type\Definition\ResolveInfo;
use Illuminate\Auth\AuthManager;
use Illuminate\Contracts\Auth\Authenticatable;
use Illuminate\Http\Request;
use Illuminate\Support\Collection;
use Mockery\MockInterface;
use Nuwave\Lighthouse\Schema\Context;
use Nuwave\Lighthouse\Subscriptions\Iterators\GuardContextSyncIterator;
use Nuwave\Lighthouse\Subscriptions\Subscriber;
use Nuwave\Lighthouse\Subscriptions\SubscriptionGuard;
use Tests\Unit\Subscriptions\SubscriptionTestCase;

class GuardContextSyncIteratorTest extends SubscriptionTestCase
{
/**
* @var string
*/
public const EXCEPTION_MESSAGE = 'test_exception';

/**
* @var \Nuwave\Lighthouse\Subscriptions\Iterators\GuardContextSyncIterator
*/
protected $iterator;

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

$this->iterator = $this->app->make(GuardContextSyncIterator::class);
}

public function testCanIterateOverItemsWithCallback(): void
{
$items = [];

$this->iterator->process(
$this->subscribers(),
static function ($item) use (&$items): void {
$items[] = $item;
}
);

$this->assertCount(3, $items);
}

public function testCanPassExceptionToHandler(): void
{
/** @var \Exception|null $exception */
$exception = null;

$this->iterator->process(
$this->subscribers(),
static function (): void {
throw new Exception(self::EXCEPTION_MESSAGE);
},
static function (Exception $e) use (&$exception): void {
$exception = $e;
}
);

$this->assertSame(self::EXCEPTION_MESSAGE, $exception->getMessage());
stayallive marked this conversation as resolved.
Show resolved Hide resolved
}

public function testSetsAndResetsGuardContextAfterEachIteration(): void
{
// Give each subscriber a user stub and an ID based on the index of the subscriber in the collection
$subscribers = $this->subscribers()->map(static function (Subscriber $subscriber, int $index) {
$subscriber->context->user = new GuardContextSyncIteratorAuthenticatableStub($index + 1);

return $subscriber;
});

$guard = $this->mock(SubscriptionGuard::class, static function (MockInterface $mock) use ($subscribers) {
$subscribers->each(static function (Subscriber $subscriber) use ($mock) {
$mock->shouldReceive('setUser')->with($subscriber->context->user())->once();
$mock->shouldReceive('user')->andReturn($subscriber->context->user())->once();
$mock->shouldReceive('reset')->once();
});
});

$authManager = $this->app->make(AuthManager::class);

$authManager->extend(SubscriptionGuard::GUARD_NAME, static function () use ($guard) {
return $guard;
});

$processedItems = [];
$authenticatedUser = [];
$guardBeforeIteration = $authManager->guard();

$this->iterator->process(
$subscribers,
static function (Subscriber $subscriber) use (&$processedItems, &$authenticatedUser, $authManager): void {
$processedItems[] = $subscriber;
$authenticatedUser[] = $authManager->user();
}
);

$this->assertCount(3, $processedItems);
$this->assertSame($subscribers->pluck('context.user')->all(), $authenticatedUser);
$this->assertSame($guardBeforeIteration, $authManager->guard());
}

/**
* @return \Illuminate\Support\Collection<\Nuwave\Lighthouse\Subscriptions\Subscriber>
*/
protected function subscribers(): Collection
{
return new Collection([
$this->generateSubscriber(),
$this->generateSubscriber(),
$this->generateSubscriber(),
]);
}

private function generateSubscriber(): Subscriber
{
$resolveInfo = $this->getMockBuilder(ResolveInfo::class)
stayallive marked this conversation as resolved.
Show resolved Hide resolved
->disableOriginalConstructor()
->getMock();

$resolveInfo->operation = (object)[
'name' => (object)[
'value' => 'lighthouse',
],
];

return new Subscriber([], new Context(new Request), $resolveInfo);
}
}

class GuardContextSyncIteratorAuthenticatableStub implements Authenticatable
{
/**
* @var int
*/
private $id;

public function __construct(int $id)
{
$this->id = $id;
}

public function getAuthIdentifierName()
{
}

public function getAuthIdentifier()
{
return $this->id;
}

public function getAuthPassword()
{
}

public function getRememberToken()
{
}

public function setRememberToken($value)
{
}

public function getRememberTokenName()
{
}
}
Loading