67 lines
2.4 KiB
PHP
67 lines
2.4 KiB
PHP
<?php
|
||
declare(strict_types=1);
|
||
|
||
if (session_status() !== PHP_SESSION_ACTIVE) session_start();
|
||
|
||
require_once dirname(__DIR__, 2) . '/vendor/autoload.php';
|
||
require_once dirname(__DIR__, 2) . '/app/bootstrap.php';
|
||
require_once dirname(__DIR__, 2) . '/config/config.php';
|
||
|
||
if (!function_exists('env')) {
|
||
function env(string $key, ?string $default = null): ?string {
|
||
if (array_key_exists($key, $_ENV) && $_ENV[$key] !== '') return (string)$_ENV[$key];
|
||
$v = getenv($key);
|
||
if ($v !== false && $v !== '') return (string)$v;
|
||
return $default;
|
||
}
|
||
}
|
||
|
||
$flow = $_GET['flow'] ?? 'login'; // 'login' ou 'register'
|
||
if (!in_array($flow, ['login','register'], true)) $flow = 'login';
|
||
|
||
// return_to (URL relative uniquement)
|
||
$defaultReturn = '/';
|
||
$rawReturn = $_GET['return_to'] ?? ($_SERVER['HTTP_REFERER'] ?? $defaultReturn);
|
||
$returnTo = (is_string($rawReturn) && str_starts_with($rawReturn, '/')) ? $rawReturn : $defaultReturn;
|
||
|
||
// Mémorise flow + cible
|
||
$_SESSION['oidc_flow'] = $flow;
|
||
$_SESSION['oidc_return_to'] = $returnTo;
|
||
|
||
// --- OIDC conf ---
|
||
$issuer = rtrim((string)env('OIDC_ISSUER',''), '/');
|
||
$clientId = (string)env('OIDC_CLIENT_ID','');
|
||
$redirectUri = (string)(env('OIDC_REDIRECT_URI') ?: url('oidc/callback'));
|
||
if (!$issuer || !$clientId || !$redirectUri) {
|
||
http_response_code(500);
|
||
echo 'OIDC non configuré (OIDC_ISSUER / OIDC_CLIENT_ID / OIDC_REDIRECT_URI).';
|
||
exit;
|
||
}
|
||
|
||
// --- Endpoints & PKCE ---
|
||
$authEndpoint = $issuer . '/protocol/openid-connect/auth';
|
||
$state = bin2hex(random_bytes(16));
|
||
$nonce = bin2hex(random_bytes(16));
|
||
$codeVerifier = rtrim(strtr(base64_encode(random_bytes(32)), '+/', '-_'), '=');
|
||
$codeChallenge = rtrim(strtr(base64_encode(hash('sha256', $codeVerifier, true)), '+/', '-_'), '=');
|
||
|
||
$_SESSION['oidc_state'] = $state;
|
||
$_SESSION['oidc_nonce'] = $nonce;
|
||
$_SESSION['oidc_code_verifier'] = $codeVerifier;
|
||
|
||
// --- URL d’auth ---
|
||
$params = [
|
||
'response_type' => 'code',
|
||
'client_id' => $clientId,
|
||
'redirect_uri' => $redirectUri,
|
||
'scope' => 'openid email profile',
|
||
'state' => $state,
|
||
'nonce' => $nonce,
|
||
'code_challenge' => $codeChallenge,
|
||
'code_challenge_method' => 'S256',
|
||
'ui_locales' => 'fr',
|
||
];
|
||
|
||
header('Location: ' . $authEndpoint . '?' . http_build_query($params, '', '&', PHP_QUERY_RFC3986), true, 302);
|
||
exit;
|