| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110 |
- <?php
- /**
- * Session Helper for API Authentication
- * Provides session validation functions for API endpoints
- */
- // Start session if not already started
- if (session_status() == PHP_SESSION_NONE) {
- session_start();
- }
- /**
- * Validate user session and return user data
- * @param PDO $db Database connection
- * @return array|null User data if valid, null if invalid
- */
- function validateSession($db) {
- // Check if session exists
- if (!isset($_SESSION['user_id']) || empty($_SESSION['user_id'])) {
- return null;
- }
-
- try {
- // Validate user still exists and is active
- $query = "SELECT id, username, email, first_name, last_name, role, is_active
- FROM users
- WHERE id = ? AND is_active = 1";
-
- $stmt = $db->prepare($query);
- $stmt->bindParam(1, $_SESSION['user_id']);
- $stmt->execute();
-
- $user = $stmt->fetch(PDO::FETCH_ASSOC);
-
- if ($user) {
- return $user;
- } else {
- // User no longer exists or is inactive, destroy session
- session_destroy();
- return null;
- }
- } catch (PDOException $e) {
- // Database error, invalidate session
- session_destroy();
- return null;
- }
- }
- /**
- * Require authentication for API endpoints
- * @param PDO $db Database connection
- * @return array User data
- */
- function requireAuth($db) {
- $user = validateSession($db);
-
- if (!$user) {
- http_response_code(401);
- echo json_encode(array(
- "message" => "Authentication required",
- "error" => "UNAUTHORIZED"
- ));
- exit;
- }
-
- return $user;
- }
- /**
- * Send JSON response with proper headers
- * @param mixed $data Response data
- * @param int $statusCode HTTP status code
- * @param string $message Response message
- */
- function sendJsonResponse($data, $statusCode = 200, $message = '') {
- http_response_code($statusCode);
-
- $response = array();
-
- if (!empty($message)) {
- $response['message'] = $message;
- }
-
- if ($data !== null) {
- if (is_array($data) && isset($data['message'])) {
- $response = array_merge($response, $data);
- } else {
- $response['data'] = $data;
- }
- }
-
- header('Content-Type: application/json');
- echo json_encode($response);
- exit;
- }
- /**
- * Handle CORS preflight requests
- */
- function handleCors() {
- header("Access-Control-Allow-Origin: *");
- header("Content-Type: application/json; charset=UTF-8");
- header("Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS");
- header("Access-Control-Allow-Headers: Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With");
-
- if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
- exit(0);
- }
- }
- ?>
|