72 lines
1.9 KiB
PHP
72 lines
1.9 KiB
PHP
<?php
|
|
|
|
namespace App\Http\Controllers;
|
|
|
|
use App\Actions\Auth\AuthenticateOidcUser;
|
|
use App\DTOs\OidcUserData;
|
|
use Illuminate\Auth\AuthenticationException;
|
|
use Illuminate\Support\Facades\Auth;
|
|
use Laravel\Socialite\Facades\Socialite;
|
|
|
|
use Symfony\Component\HttpFoundation\Response;
|
|
|
|
class OidcController extends Controller
|
|
{
|
|
/**
|
|
* Redirect the user to the OIDC authentication page.
|
|
*/
|
|
public function redirect(): Response
|
|
{
|
|
if (! config('services.oidc.client_id')) {
|
|
abort(404, 'OIDC is not configured.');
|
|
}
|
|
|
|
return Socialite::driver('oidc')->redirect();
|
|
}
|
|
|
|
/**
|
|
* Handle the callback from the OIDC Identity Provider.
|
|
*/
|
|
public function callback(AuthenticateOidcUser $authenticateUser): Response
|
|
{
|
|
if (! config('services.oidc.client_id')) {
|
|
abort(404, 'OIDC is not configured.');
|
|
}
|
|
|
|
try {
|
|
$socialiteUser = Socialite::driver('oidc')->user();
|
|
} catch (\Exception $e) {
|
|
return redirect()->route('login')->withErrors([
|
|
'email' => 'Authentication failed: '.$e->getMessage(),
|
|
]);
|
|
}
|
|
|
|
$email = $socialiteUser->getEmail();
|
|
$sub = $socialiteUser->getId();
|
|
|
|
if (! $email || ! $sub) {
|
|
return redirect()->route('login')->withErrors([
|
|
'email' => 'Required user attributes (email, sub) not provided by IDP.',
|
|
]);
|
|
}
|
|
|
|
$userData = new OidcUserData(
|
|
sub: $sub,
|
|
email: $email,
|
|
name: $socialiteUser->getName()
|
|
);
|
|
|
|
try {
|
|
$user = $authenticateUser->execute($userData);
|
|
} catch (AuthenticationException $e) {
|
|
return redirect()->route('login')->withErrors([
|
|
'email' => $e->getMessage(),
|
|
]);
|
|
}
|
|
|
|
Auth::login($user, true);
|
|
|
|
return redirect()->intended(config('fortify.home', '/dashboard'));
|
|
}
|
|
}
|