# Base controller for API endpoints # Provides authentication and common functionality for API controllers class ApiController < ApplicationController # Disable CSRF protection for API requests (token-based authentication instead) protect_from_forgery with: :null_session # Authenticate all API requests using API key # Must be called before any API action before_action :authenticate_api_key private # Authenticates API requests using X-API-Key header or api_key parameter # Returns 401 Unauthorized if key is invalid or missing def authenticate_api_key # Extract API key from header or query parameter api_key = request.headers["X-API-Key"] || params[:api_key] # Validate against environment variable for security expected_key = Rails.application.credentials.api_key || ENV["API_KEY"] unless expected_key.present? && api_key == expected_key render json: { error: "Unauthorized" }, status: :unauthorized end end end