Skip to content

Commit

Permalink
Support the HTTP_REMOTE_USER header (#208)
Browse files Browse the repository at this point in the history
  • Loading branch information
jbrooksuk authored Jan 21, 2025
1 parent 91434f1 commit 1b32bc3
Show file tree
Hide file tree
Showing 3 changed files with 73 additions and 0 deletions.
1 change: 1 addition & 0 deletions config/cachet.php
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,7 @@
*/
'middleware' => [
'web',
// \Cachet\Http\Middleware\AuthenticateRemoteUser::class,
],

'api_middleware' => [
Expand Down
32 changes: 32 additions & 0 deletions src/Http/Middleware/AuthenticateRemoteUser.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
<?php

namespace Cachet\Http\Middleware;

use Cachet\Cachet;
use Cachet\Models\User;
use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;

class AuthenticateRemoteUser
{
/**
* Handle an incoming request.
*
* @param \Closure(\Illuminate\Http\Request): (\Symfony\Component\HttpFoundation\Response) $next
*/
public function handle(Request $request, Closure $next): Response
{
if ($remoteUser = $request->headers->get('REMOTE_USER')) {
$userModel = Cachet::userModel();
/** @var User|null $user */
$user = $userModel::query()->where('email', $remoteUser)->first();

if ($user !== null) {
auth()->login($user);
}
}

return $next($request);
}
}
40 changes: 40 additions & 0 deletions tests/Feature/Http/Middleware/AuthenticateRemoteUserTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
<?php

use Cachet\Http\Middleware\AuthenticateRemoteUser;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Symfony\Component\HttpFoundation\Response;
use Workbench\App\User;

it('authenticates remote user if REMOTE_USER header is present', function () {
$user = User::factory()->create(['email' => '[email protected]']);

$request = Request::create('/test', 'GET', [], [], [], ['HTTP_REMOTE_USER' => '[email protected]']);

$next = function ($request) {
return new Response('OK');
};

$middleware = new AuthenticateRemoteUser();

$response = $middleware->handle($request, $next);

expect(Auth::check())->toBeTrue()
->and(Auth::user()->email)->toBe('[email protected]')
->and($response->getContent())->toBe('OK');
});

it('does not authenticate remote user if REMOTE_USER header is not present', function () {
$request = Request::create('/test');

$next = function ($request) {
return new Response('OK');
};

$middleware = new AuthenticateRemoteUser();

$response = $middleware->handle($request, $next);

expect(Auth::check())->toBeFalse()
->and($response->getContent())->toBe('OK');
});

0 comments on commit 1b32bc3

Please sign in to comment.