class ApplicationController < ActionController::Base
  # Prevent CSRF attacks by raising an exception.
  # For APIs, you may want to use :null_session instead.
  protect_from_forgery with: :exception

  def authenticate_user!
    if json_request?
      if (request.headers["X-API-Auth"] != Rails.application.secrets.x_api_auth)
        render json: "Access denied", status: :unauthorized
      end
    else
      if current_user.nil?
        render json: "Access denied", status: :unauthorized
      end
    end
  end

  def json_request?
    request.format.json?
  end

  def current_user
    @current_user ||= User.find_by_id(session[:user_id]) if session[:user_id]
    @current_user
  end

end
