ccah-assessment/auth-manager.php

55 lines
1.7 KiB
PHP

<?php
require_once __DIR__ . "/db.php";
if (session_status() === PHP_SESSION_NONE) {
session_start();
}
// Ensure token is provided via GET or Session
if (!isset($_GET['auth']) && !isset($_SESSION['auth_token'])) {
echo "Unauthorized access. Please use the correct link with your authentication token.";
exit;
}
// Use session token if available, otherwise use URL token
$authToken = $_SESSION['auth_token'] ?? $_GET['auth'];
// Ensure database connection is valid
$conn = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);
if ($conn->connect_error) {
error_log("Database connection error: " . $conn->connect_error);
die("Database connection error.");
}
// Fetch user information, including token expiration
$query = "SELECT id, email, given_name, surname, is_board_member, token_expires_at FROM users WHERE auth_token = ?";
$stmt = $conn->prepare($query);
$stmt->bind_param("s", $authToken);
$stmt->execute();
$result = $stmt->get_result();
if ($result->num_rows === 0) {
die("Unauthorized access - Invalid token.");
}
$user = $result->fetch_assoc();
// Check if token is expired
if (strtotime($user['token_expires_at']) < time()) {
die("Unauthorized access - Token expired. Please contact your administrator.");
}
// Store session data
$_SESSION['auth_token'] = $authToken; // Store token for future use
$_SESSION['user_id'] = intval($user['id']);
$_SESSION['email'] = $user['email'];
$_SESSION['full_name'] = $user['given_name'] . " " . $user['surname'];
$_SESSION['is_board_member'] = intval($user['is_board_member']);
// Redirect only if using URL token
if (isset($_GET['auth']) && !isset($_SESSION['auth_token'])) {
header("Location: questionnaire.php");
exit;
}
?>