I have the following code which is supposed to authenticate a user from an external system and log them in. However this does not authenticate the user and I am a little bit clueless right now as I took it from @luceos (https://discuss.flarum.org/d/30137-login-a-user-inside-of-flarum-code/5) and the LoginController in the vendor folder.
<?php
declare(strict_types=1);
namespace Wulfheart\FlarumDnwAuth\Controller;
use Flarum\Foundation\Application;
use Flarum\Http\Rememberer;
use Flarum\Http\SessionAuthenticator;
use Flarum\Settings\SettingsRepositoryInterface;
use Flarum\User\User;
use Illuminate\Support\Str;
use Laminas\Diactoros\Response\RedirectResponse;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\RequestHandlerInterface;
use Wulfheart\FlarumDnwAuth\DnwAccessToken;
use Wulfheart\FlarumDnwAuth\Repository\ExtendedUserRepository;
use Wulfheart\FlarumDnwAuth\TokenValidator;
final class AuthCallbackController implements RequestHandlerInterface
{
public function __construct(
private SessionAuthenticator $authenticator,
private Application $app,
private SettingsRepositoryInterface $settings,
private ExtendedUserRepository $users,
private Rememberer $rememberer,
)
{
}
public function handle(ServerRequestInterface $request): ResponseInterface
{
/** @var \Illuminate\Session\Store $session */
$session = $request->getAttribute('session');
$queryParams = $request->getQueryParams();
$token = $queryParams['token'] ?? '';
$state = $queryParams['state'] ?? '';
$secret = $this->settings->get('dnw-sso.client_secret');
$externalUserData = (new TokenValidator($secret))->validate($token);
$user = $this->users->findByExternalId($externalUserData->externalAuthId);
if ($user === null) {
$user = User::register(
$externalUserData->username,
$externalUserData->email,
Str::uuid() . Str::random()
);
// Probably would better to have it in another table but here we go, YOLO
$user->external_auth_id = $externalUserData->externalAuthId;
$user->activate();
$user->save();
} else {
$user->changeEmail($externalUserData->email);
$user->username = $externalUserData->username;
$user->save();
}
$token = DnwAccessToken::generate($user->id);
$token->save();
$this->authenticator->logIn($session, $token);
$decodedState = base64_decode($state);
$url = $decodedState === '' ? $this->app->url() : $decodedState;
$response = new RedirectResponse($url);
// THIS SHOULD BE DISPATCHED ON THE EVENT BUS, not the command one, but dunno
// $this->bus->dispatch(new LoggedIn($user, $token));
return $this->rememberer->remember($response, $token);
}
}