tinyauth-web/public/callback.php

53 lines
1.8 KiB
PHP

<?php
declare(strict_types=1);
require dirname(__DIR__) . '/src/lib.php';
start_session();
try {
if (isset($_GET['error'])) {
throw new RuntimeException('tinyauth returned: ' . (string) $_GET['error']);
}
$expected = $_SESSION['oidc_state'] ?? '';
unset($_SESSION['oidc_state']);
if ($expected === '' || !hash_equals($expected, (string) ($_GET['state'] ?? ''))) {
throw new RuntimeException('Login state did not match. Try logging in again.');
}
$code = (string) ($_GET['code'] ?? '');
if ($code === '') {
throw new RuntimeException('No authorization code received.');
}
$cfg = config();
$discovery = oidc_discovery();
$tokens = http_request('POST', $discovery['token_endpoint'], [
'grant_type' => 'authorization_code',
'code' => $code,
'redirect_uri' => $cfg['redirect_uri'],
'client_id' => $cfg['client_id'],
'client_secret' => $cfg['client_secret'],
]);
if (empty($tokens['access_token'])) {
throw new RuntimeException('tinyauth did not return an access token.');
}
$claims = http_request('GET', $discovery['userinfo_endpoint'], [], [
'Authorization: Bearer ' . $tokens['access_token'],
]);
$groups = $claims[$cfg['groups_claim']] ?? [];
$groups = array_values(array_map('strval', (array) $groups));
$user = (string) ($claims['preferred_username'] ?? $claims['email'] ?? $claims['sub'] ?? 'unknown');
session_regenerate_id(true);
$_SESSION['user'] = $user;
$_SESSION['groups'] = $groups;
redirect('index.php');
} catch (RuntimeException $e) {
page_start('Login error');
echo '<section class="card card-center"><h1>Login failed</h1><div class="flash flash-error">' . h($e->getMessage())
. '</div><a class="btn btn-primary" href="login.php">Try again</a></section>';
page_end();
}