88 lines
2.5 KiB
PHP
88 lines
2.5 KiB
PHP
<?php
|
|
|
|
require_once __DIR__ . '/../vendor/autoload.php';
|
|
|
|
use Jakach\Logging\Storage\Database;
|
|
use Jakach\Logging\Storage\Repository;
|
|
|
|
function isSafeRedirect(string $url): bool
|
|
{
|
|
if ($url === '' || $url === '/') return true;
|
|
$host = parse_url($url, PHP_URL_HOST);
|
|
if ($host === null || $host === '') return true;
|
|
return str_ends_with($host, '.jakach.ch') || $host === 'jakach.ch';
|
|
}
|
|
|
|
session_set_cookie_params([
|
|
'lifetime' => 86400 * 7,
|
|
'path' => '/',
|
|
'httponly' => true,
|
|
'secure' => true,
|
|
'samesite' => 'Lax',
|
|
]);
|
|
session_start();
|
|
|
|
$authToken = $_GET['auth'] ?? '';
|
|
$errorRedirect = isSafeRedirect($_GET['redirect'] ?? '') ? $_GET['redirect'] : '/';
|
|
|
|
if (!$authToken) {
|
|
$_SESSION['auth_error'] = 'Missing authentication token.';
|
|
header('Location: ' . $errorRedirect);
|
|
exit;
|
|
}
|
|
|
|
$checkUrl = 'https://auth.jakach.ch/api/auth/check_auth_key.php?auth_token=' . urlencode($authToken);
|
|
|
|
$ch = curl_init();
|
|
curl_setopt($ch, CURLOPT_URL, $checkUrl);
|
|
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
|
|
curl_setopt($ch, CURLOPT_TIMEOUT, 15);
|
|
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);
|
|
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
|
|
$response = curl_exec($ch);
|
|
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
|
|
$curlError = curl_error($ch);
|
|
curl_close($ch);
|
|
|
|
if ($httpCode !== 200 || !$response) {
|
|
$_SESSION['auth_error'] = "Auth server unreachable ($httpCode)";
|
|
header('Location: ' . $errorRedirect);
|
|
exit;
|
|
}
|
|
|
|
$data = json_decode($response, true);
|
|
|
|
if (!isset($data['status']) || $data['status'] !== 'success') {
|
|
$_SESSION['auth_error'] = 'Authentication failed: ' . ($data['msg'] ?? 'Unknown error');
|
|
header('Location: ' . $errorRedirect);
|
|
exit;
|
|
}
|
|
|
|
$userToken = $data['user_token'] ?? '';
|
|
|
|
$db = new Database();
|
|
$repo = new Repository($db);
|
|
|
|
$allowedTokens = $repo->getAllowedUserTokens();
|
|
|
|
if (empty($allowedTokens)) {
|
|
$repo->setAllowedUserTokens([$userToken]);
|
|
} elseif (!in_array($userToken, $allowedTokens, true)) {
|
|
$_SESSION['auth_error'] = 'Your Jakach account is not authorized to access this system. Contact an administrator.';
|
|
header('Location: ' . $errorRedirect);
|
|
exit;
|
|
}
|
|
|
|
session_regenerate_id(true);
|
|
|
|
$_SESSION['loggedin'] = true;
|
|
$_SESSION['username'] = $data['username'] ?? 'unknown';
|
|
$_SESSION['id'] = $data['id'] ?? '';
|
|
$_SESSION['email'] = $data['email'] ?? '';
|
|
$_SESSION['telegram_id'] = $data['telegram_id'] ?? '';
|
|
$_SESSION['user_token'] = $userToken;
|
|
unset($_SESSION['auth_error']);
|
|
|
|
$redirect = isSafeRedirect($_GET['redirect'] ?? '') ? $_GET['redirect'] : '/';
|
|
header('Location: ' . $redirect);
|
|
exit; |