BlueGit

projects-timfalken-com meteors

Files

meteors / server / callback.php

callback.php

callback.php 2.4 KiB Download Raw
1<?php
2declare(strict_types=1);
3require __DIR__ . '/lib/bootstrap.php';
4require __DIR__ . '/lib/I18n.php';
5
6try {
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 $loginReturn = loginReturnTarget($_SESSION['login_return'] ?? null);
14 unset($_SESSION['oauth_state'], $_SESSION['oauth_started'], $_SESSION['login_return']);
15 $code = $_GET['code'] ?? null;
16 if (!is_string($code) || $code === '') {
17 throw new RuntimeException('De login is niet afgerond.');
18 }
19 $cfg = config();
20 $token = authRequest('/oauth/token', [
21 'grant_type' => 'authorization_code',
22 'code' => $code,
23 'client_id' => $cfg['client_id'],
24 'client_secret' => $cfg['client_secret'],
25 'redirect_uri' => baseUrl() . '/callback.php',
26 ]);
27 if (!isset($token['access_token'], $token['expires_in']) || !is_string($token['access_token'])) {
28 throw new RuntimeException('Geen toegangstoken ontvangen.');
29 }
30 $me = authRequest('/api/me', null, $token['access_token']);
31 if (!isset($me['user']) || !is_array($me['user'])) {
32 throw new RuntimeException('Het profiel ontbreekt.');
33 }
34 [$id, $name, $avatar] = authIdentity($me['user']);
35 loginUser($id, $name, $avatar);
36 $_SESSION['token'] = $token['access_token'];
37 $_SESSION['expires'] = time() + (int) $token['expires_in'];
38 // t1250: OIDC locale claim from /api/me, or from the token user payload.
39 storeAuthLocale(authLocaleFromPayload($me) ?? authLocaleFromPayload($token));
40 // t1193: back to the main menu unless the login started from Online.
41 header('Location: ' . baseUrl() . '/' . loginReturnPath($loginReturn));
42} catch (Throwable $e) {
43 http_response_code(401);
44 header('Content-Type: text/html; charset=utf-8');
45 $lang = I18n::htmlLang();
46 echo '<!DOCTYPE html><html lang="' . htmlspecialchars($lang) . '"><meta charset="utf-8"><title>Meteors</title>';
47 echo htmlspecialchars(I18n::t('auth.failed')) . ' ' . htmlspecialchars($e->getMessage());
48 echo ' <a href="auth.php">' . htmlspecialchars(I18n::t('auth.retry')) . '</a> · <a href="index.html">' . htmlspecialchars(I18n::t('auth.back')) . '</a>';
49}