| 1 | <?php |
| 2 | declare(strict_types=1); |
| 3 | require __DIR__ . '/lib/bootstrap.php'; |
| 4 | require __DIR__ . '/lib/I18n.php'; |
| 5 | |
| 6 | try { |
| 7 | $state = $_GET['state'] ?? null; |
| 8 | if (!is_string($state) || !isset($_SESSION['oauth_state']) |
| 9 | || !hash_equals((string) $_SESSION['oauth_state'], $state) |
| 10 | || time() - (int) ($_SESSION['oauth_started'] ?? 0) > 600) { |
| 11 | throw new RuntimeException('Ongeldige of verlopen login.'); |
| 12 | } |
| 13 | unset($_SESSION['oauth_state'], $_SESSION['oauth_started']); |
| 14 | $code = $_GET['code'] ?? null; |
| 15 | if (!is_string($code) || $code === '') { |
| 16 | throw new RuntimeException('De login is niet afgerond.'); |
| 17 | } |
| 18 | $cfg = config(); |
| 19 | $token = authRequest('/oauth/token', [ |
| 20 | 'grant_type' => 'authorization_code', |
| 21 | 'code' => $code, |
| 22 | 'client_id' => $cfg['client_id'], |
| 23 | 'client_secret' => $cfg['client_secret'], |
| 24 | 'redirect_uri' => baseUrl() . '/callback.php', |
| 25 | ]); |
| 26 | if (!isset($token['access_token'], $token['expires_in']) || !is_string($token['access_token'])) { |
| 27 | throw new RuntimeException('Geen toegangstoken ontvangen.'); |
| 28 | } |
| 29 | $me = authRequest('/api/me', null, $token['access_token']); |
| 30 | if (!isset($me['user']) || !is_array($me['user'])) { |
| 31 | throw new RuntimeException('Het profiel ontbreekt.'); |
| 32 | } |
| 33 | [$id, $name, $avatar] = authIdentity($me['user']); |
| 34 | loginUser($id, $name, $avatar); |
| 35 | $_SESSION['token'] = $token['access_token']; |
| 36 | $_SESSION['expires'] = time() + (int) $token['expires_in']; |
| 37 | if ((int) $token['expires_in'] < 86400) { |
| 38 | // Keep our session for the full TTL even if the access token is shorter; |
| 39 | // we only needed it to identify the user. |
| 40 | $_SESSION['expires'] = time() + ALLIANTIES_SESSION_TTL; |
| 41 | } |
| 42 | $dest = $_SESSION['after_login'] ?? 'index.html'; |
| 43 | unset($_SESSION['after_login']); |
| 44 | header('Location: ' . $dest); |
| 45 | } catch (Throwable $e) { |
| 46 | http_response_code(401); |
| 47 | header('Content-Type: text/html; charset=utf-8'); |
| 48 | $lang = I18n::htmlLang(); |
| 49 | echo '<!DOCTYPE html><html lang="' . htmlspecialchars($lang) . '"><meta charset="utf-8"><title>Allianties</title>'; |
| 50 | echo htmlspecialchars(I18n::t('auth.failed')) . ' ' . htmlspecialchars($e->getMessage()); |
| 51 | echo ' <a href="auth.php">' . htmlspecialchars(I18n::t('auth.retry')) . '</a> · <a href="index.html">' . htmlspecialchars(I18n::t('auth.back')) . '</a>'; |
| 52 | } |
projects-timfalken-com allianties