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

[9.x] User authentication for Pusher #42531

Merged
merged 6 commits into from
Jun 1, 2022
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: 19 additions & 0 deletions src/Illuminate/Broadcasting/BroadcastController.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
use Illuminate\Http\Request;
use Illuminate\Routing\Controller;
use Illuminate\Support\Facades\Broadcast;
use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;

class BroadcastController extends Controller
{
Expand All @@ -22,4 +23,22 @@ public function authenticate(Request $request)

return Broadcast::auth($request);
}

/**
* Authenticate the current user.
*
* See: https://pusher.com/docs/channels/server_api/authenticating-users/#user-authentication.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function authenticateUser(Request $request)
{
if ($request->hasSession()) {
$request->session()->reflash();
rennokki marked this conversation as resolved.
Show resolved Hide resolved
}

return Broadcast::resolveAuthenticatedUser($request)
?? throw new AccessDeniedHttpException;
}
}
5 changes: 5 additions & 0 deletions src/Illuminate/Broadcasting/BroadcastManager.php
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,11 @@ public function routes(array $attributes = null)
['get', 'post'], '/broadcasting/auth',
'\\'.BroadcastController::class.'@authenticate'
)->withoutMiddleware([\Illuminate\Foundation\Http\Middleware\VerifyCsrfToken::class]);

$router->match(
['get', 'post'], '/broadcasting/user-auth',
'\\'.BroadcastController::class.'@authenticateUser'
)->withoutMiddleware([\Illuminate\Foundation\Http\Middleware\VerifyCsrfToken::class]);
});
}

Expand Down
36 changes: 36 additions & 0 deletions src/Illuminate/Broadcasting/Broadcasters/Broadcaster.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

namespace Illuminate\Broadcasting\Broadcasters;

use Closure;
use Exception;
use Illuminate\Container\Container;
use Illuminate\Contracts\Broadcasting\Broadcaster as BroadcasterContract;
Expand All @@ -17,6 +18,13 @@

abstract class Broadcaster implements BroadcasterContract
{
/**
* The callback to resolve the authenticated user information.
*
* @var \Closure|null
*/
protected $authenticatedUserCallback = null;

/**
* The registered channel authenticators.
*
Expand All @@ -38,6 +46,34 @@ abstract class Broadcaster implements BroadcasterContract
*/
protected $bindingRegistrar;

/**
* Resolve the authenticated user payload for the incoming connection request.
*
* See: https://pusher.com/docs/channels/library_auth_reference/auth-signatures/#user-authentication.
*
* @param \Illuminate\Http\Request $request
* @return array|null
*/
public function resolveAuthenticatedUser($request)
{
if ($this->authenticatedUserCallback) {
return $this->authenticatedUserCallback->__invoke($request);
}
}

/**
* Register the user retrieval callback used to authenticate connections.
*
* See: https://pusher.com/docs/channels/library_auth_reference/auth-signatures/#user-authentication.
*
* @param \Closure $callback
* @return void
*/
public function resolveAuthenticatedUserUsing(Closure $callback)
{
$this->authenticatedUserCallback = $callback;
}

/**
* Register a channel authenticator.
*
Expand Down
29 changes: 29 additions & 0 deletions src/Illuminate/Broadcasting/Broadcasters/PusherBroadcaster.php
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,35 @@ public function __construct(Pusher $pusher)
$this->pusher = $pusher;
}

/**
* Resolve the authenticated user payload for an incoming connection request.
*
* See: https://pusher.com/docs/channels/library_auth_reference/auth-signatures/#user-authentication
* See: https://pusher.com/docs/channels/server_api/authenticating-users/#response
*
* @param \Illuminate\Http\Request $request
* @return array|null
*/
public function resolveAuthenticatedUser($request)
{
if (! $user = parent::resolveAuthenticatedUser($request)) {
return;
}

$settings = $this->pusher->getSettings();
$encodedUser = json_encode($user);
$decodedString = "{$request->socket_id}::user::{$encodedUser}";

$auth = $settings['auth_key'].':'.hash_hmac(
'sha256', $decodedString, $settings['secret']
);

return [
'auth' => $auth,
'user_data' => $encodedUser,
];
}

/**
* Authenticate the incoming request for a given channel.
*
Expand Down
5 changes: 3 additions & 2 deletions src/Illuminate/Support/Facades/Broadcast.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,10 +6,11 @@

/**
* @method static \Illuminate\Broadcasting\Broadcasters\Broadcaster channel(string $channel, callable|string $callback, array $options = [])
* @method static mixed auth(\Illuminate\Http\Request $request)
* @method static \Illuminate\Broadcasting\BroadcastManager socket($request = null)
* @method static \Illuminate\Contracts\Broadcasting\Broadcaster connection($name = null);
* @method static mixed auth(\Illuminate\Http\Request $request)
* @method static void resolveAuthenticatedUserUsing(Closure $callback)
* @method static void routes(array $attributes = null)
* @method static \Illuminate\Broadcasting\BroadcastManager socket($request = null)
*
* @see \Illuminate\Contracts\Broadcasting\Factory
*/
Expand Down
31 changes: 31 additions & 0 deletions tests/Broadcasting/BroadcasterTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
use Illuminate\Http\Request;
use Mockery as m;
use PHPUnit\Framework\TestCase;
use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
use Symfony\Component\HttpKernel\Exception\HttpException;

class BroadcasterTest extends TestCase
Expand Down Expand Up @@ -284,6 +285,36 @@ public function testRetrieveUserDontUseDefaultGuardWhenMultipleGuardsSpecified()
$this->broadcaster->retrieveUser($request, 'somechannel');
}

public function testUserAuthenticationWithValidUser()
{
$this->broadcaster->resolveAuthenticatedUserUsing(function ($request) {
return ['id' => '12345', 'socket' => $request->socket_id];
});

$user = $this->broadcaster->resolveAuthenticatedUser(new Request(['socket_id' => '1234.1234']));

$this->assertSame([
'id' => '12345',
'socket' => '1234.1234',
], $user);
}

public function testUserAuthenticationWithInvalidUser()
{
$this->broadcaster->resolveAuthenticatedUserUsing(function ($request) {
return null;
});

$user = $this->broadcaster->resolveAuthenticatedUser(new Request(['socket_id' => '1234.1234']));

$this->assertNull($user);
}

public function testUserAuthenticationWithoutResolve()
{
$this->assertNull($this->broadcaster->resolveAuthenticatedUser(new Request(['socket_id' => '1234.1234'])));
}

/**
* @dataProvider channelNameMatchPatternProvider
*/
Expand Down
25 changes: 25 additions & 0 deletions tests/Broadcasting/PusherBroadcasterTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -146,6 +146,31 @@ public function testValidAuthenticationResponseCallPusherPresenceAuthMethodWithP
);
}

public function testUserAuthenticationForPusher()
{
$this->pusher
->shouldReceive('getSettings')
->andReturn([
'auth_key' => '278d425bdf160c739803',
'secret' => '7ad3773142a6692b25b8',
]);

$this->broadcaster = new PusherBroadcaster($this->pusher);

$this->broadcaster->resolveAuthenticatedUserUsing(function () {
return ['id' => '12345'];
});

$response = $this->broadcaster->resolveAuthenticatedUser(new Request(['socket_id' => '1234.1234']));

// The result is hard-coded from the Pusher docs
// See: https://pusher.com/docs/channels/library_auth_reference/auth-signatures/#user-authentication
$this->assertSame([
'auth' => '278d425bdf160c739803:4708d583dada6a56435fb8bc611c77c359a31eebde13337c16ab43aa6de336ba',
'user_data' => json_encode(['id' => '12345']),
], $response);
}

/**
* @param string $channel
* @return \Illuminate\Http\Request
Expand Down