<commit_before># Handles the processing of requests before they reach the controller action method itself.
# All global before_actions should go here.
# The basic flow is:
#
# - Authenticate via token if action was prepended.
# - Check subdomain validity and set current_community.
# - Store the requested URL in case auth fails.
# - Authenticate user via session unless already authenticated.
# - Redirect to an appropriate subdomain or 404 if subdomain missing and this filter not skipped.
# - Ensure the current_user has access to the current_community if both set.
# - Set the current tenant (cluster) based on the current community.
module Concerns::ApplicationController::RequestPreprocessing
  extend ActiveSupport::Concern

  included do
    # This indicates to acts_as_tenant that we're planning to set the tenant via a before_action
    # The actual before_action (set_tenant) is called below.
    set_current_tenant_through_filter

    before_action :log_full_url
    before_action :set_default_nav_context
    before_action :check_subdomain_validity
    before_action :store_current_location
    before_action :authenticate_user!
    before_action :ensure_subdomain
    before_action :check_community_permissions
    before_action :set_tenant
    before_action :set_time_zone

    rescue_from Pundit::NotAuthorizedError, with: :handle_unauthorized
  end

  private

  # Currently we are only checking for calendar_token, but could add others later.
  def authenticate_user_from_token!
    if params[:calendar_token] && user = User.find_by_calendar_token(params[:calendar_token])
      # We are passing store false, so the user is not
      # actually stored in the session and a token is needed for every request.
      sign_in user, store: false
    else
      render_error_page(:forbidden)
    end
  end

  def log_full_url
    Rails.logger.info("Request URL: #{request.url}")
  end

  def set_default_nav_context
    @context = {}
  end

  # Checks that the subdomain's community exists and sets current_community.
  # Does nothing if subdomain is not present.
  # Renders 404 if community not found.
  def check_subdomain_validity
    return unless subdomain.present?
    self.current_community = Community.find_by(slug: subdomain)
    render_error_page(:not_found) if current_community.nil?
  end

  # Saves the location before loading each page so we can return to the right page after sign in.
  def store_current_location
    # If we're on a devise page, we don't want to store that as the
    # place to return to (for example, we don't want to return to the sign in page after signing in).
    return if devise_controller? || request.fullpath == "/?sign-in=1" || request.fullpath =~ %r{\A/\?token=.+}
    session["user_return_to"] = request.url
  end

  # Customize the redirect URL if not signed in.
  # The method suggested in the Devise wiki -- using a custom failure app -- caused multiple complications.
  # For instance, it broke `store_current_location` above.
  def authenticate_user!
    if user_signed_in?
      super
    else<commit_msg>Fixed sign-in redirect on calendar request for non-calendar route<commit_after># Handles the processing of requests before they reach the controller action method itself.
# All global before_actions should go here.
# The basic flow is:
#
# - Authenticate via token if action was prepended.
# - Check subdomain validity and set current_community.
# - Store the requested URL in case auth fails.
# - Authenticate user via session unless already authenticated.
# - Redirect to an appropriate subdomain or 404 if subdomain missing and this filter not skipped.
# - Ensure the current_user has access to the current_community if both set.
# - Set the current tenant (cluster) based on the current community.
module Concerns::ApplicationController::RequestPreprocessing
  extend ActiveSupport::Concern

  included do
    # This indicates to acts_as_tenant that we're planning to set the tenant via a before_action
    # The actual before_action (set_tenant) is called below.
    set_current_tenant_through_filter

    before_action :log_full_url
    before_action :set_default_nav_context
    before_action :check_subdomain_validity
    before_action :store_current_location
    before_action :authenticate_user!
    before_action :ensure_subdomain
    before_action :check_community_permissions
    before_action :set_tenant
    before_action :set_time_zone

    rescue_from Pundit::NotAuthorizedError, with: :handle_unauthorized
  end

  private

  # Currently we are only checking for calendar_token, but could add others later.
  def authenticate_user_from_token!
    if params[:calendar_token] && user = User.find_by_calendar_token(params[:calendar_token])
      # We are passing store false, so the user is not
      # actually stored in the session and a token is needed for every request.
      sign_in user, store: false
    else
      render_error_page(:forbidden)
    end
  end

  def log_full_url
    Rails.logger.info("Request URL: #{request.url}")
  end

  def set_default_nav_context
    @context = {}
  end

  # Checks that the subdomain's community exists and sets current_community.
  # Does nothing if subdomain is not present.
  # Renders 404 if community not found.
  def check_subdomain_validity
    return unless subdomain.present?
    self.current_community = Community.find_by(slug: subdomain)
    render_error_page(:not_found) if current_community.nil?
  end

  # Saves the location before loading each page so we can return to the right page after sign in.
  def store_current_location
    # If we're on a devise page, we don't want to store that as the
    # place to return to (for example, we don't want to return to the sign in page after signing in).
    return if devise_controller? || request.fullpath == "/?sign-in=1" || request.fullpath =~ %r{\A/\?token=.+}
    session["user_return_to"] = request.url
  end

  # Customize the redirect URL if not signed in.
  # The method suggested in the Devise wiki -- using a custom failure app -- caused multiple complications.
  # For instance, it broke `store_current_location` above.
  def authenticate_user!
    if user_signed_in?
      super
    elsif request.format == :ics
      # Dont redirect calendar requests to sign in because that makes no sense.
      # Auth with token already fails hard with 403 but if someone points their calendar app at a bad URL
      # we get errors if we redirect.
      render_error_page(:forbidden)      
    else
{'fraction_non_alphanumeric': 0.057618240640887386, 'fraction_numerical': 0.002619010938222154, 'mean_word_length': 3.9070294784580497, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 3, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '4155550', 'n_tokens_mistral': 1837, 'n_tokens_neox': 1768, 'n_words': 710}