<commit_before># frozen_string_literal: true

require 'rack'
require 'securerandom'

require_relative '../redd'

module Redd
  # Rack middleware.
  # TODO: deal with setting the correct expiry time on the access
  class Middleware
    # @param opts [Hash] the options to create the object with
    # @option opts [String] :user_agent your app's *unique* and *descriptive* user agent
    # @option opts [String] :client_id the client id of your app
    # @option opts [String] :redirect_uri the provided redirect URI
    # @option opts [String] :secret ('') the app secret (for the web type)
    # @option opts [Array<String>] :scope (['identity']) a list of scopes to request
    # @option opts ['temporary', 'permanent'] :duration ('permanent') the duration to request the
    #   code for.
    # @option opts [String] :via ('/auth/reddit') the relative path in the application that
    #   redirects a user to reddit
    def initialize(app, opts = {})
      @app = app
      strategy_opts = opts.select { |k| %i(user_agent client_id secret redirect_uri).include?(k) }
      @strategy = Redd::AuthStrategies::Web.new(strategy_opts)

      @user_agent   = opts.fetch(:user_agent, "Redd:Web Application:v#{Redd::VERSION} (by unknown)")
      @client_id    = opts.fetch(:client_id)
      @redirect_uri = opts.fetch(:redirect_uri)
      @scope        = opts.fetch(:scope, ['identity'])
      @duration     = opts.fetch(:duration, 'permanent')
      @via          = opts.fetch(:via, '/auth/reddit')
    end

    def call(env)
      # This is done for thread safety so that each thread has its own copy
      # of the middleware logic.
      dup._call(env)
    end

    protected

    def _call(env)
      @request = Rack::Request.new(env)
      return redirect_to_reddit! if @request.path == @via

      before_call
      @app.call(env)
      after_call
    end

    private

    # Do any setup before calling the rest of the application.
    def before_call
      # Convert the code to an access token if returning from authentication.
      create_session! if @request.base_url + @request.path == @redirect_uri
      # Clear the state for any other request.
      @request.session.delete(:redd_state)
      # Load a Session model from the access token in the user's cookies.
      @request.env['redd.session'] = parse_session
    end

    # Do any cleanup or changes after calling the application.
    def after_call
      # Clear the session if the app explicitly set 'redd.session' to nil.
      # XXX: does this seem like a good approach?
      @request.session.delete(:redd_session) if @request.env['redd.session'].nil?
    end

    # Creates a unique state and redirects the user to reddit for authentication.
    def redirect_to_reddit!
      state = SecureRandom.urlsafe_base64
      url = Redd.url(
        client_id: @client_id,
        redirect_uri: @redirect_uri,
        scope: @scope,
        duration: @duration,
        state: state
      )
      @request.session[:redd_state] = state
      [302, { 'Location' => url, 'Content-Type' => 'text/html' }, ["<a href=\"#{url}\">Login</a>"]]
    end
<commit_msg>Properly return response after processing.<commit_after># frozen_string_literal: true

require 'rack'
require 'securerandom'

require_relative '../redd'

module Redd
  # Rack middleware.
  # TODO: deal with setting the correct expiry time on the access
  class Middleware
    # @param opts [Hash] the options to create the object with
    # @option opts [String] :user_agent your app's *unique* and *descriptive* user agent
    # @option opts [String] :client_id the client id of your app
    # @option opts [String] :redirect_uri the provided redirect URI
    # @option opts [String] :secret ('') the app secret (for the web type)
    # @option opts [Array<String>] :scope (['identity']) a list of scopes to request
    # @option opts ['temporary', 'permanent'] :duration ('permanent') the duration to request the
    #   code for.
    # @option opts [String] :via ('/auth/reddit') the relative path in the application that
    #   redirects a user to reddit
    def initialize(app, opts = {})
      @app = app
      strategy_opts = opts.select { |k| %i(user_agent client_id secret redirect_uri).include?(k) }
      @strategy = Redd::AuthStrategies::Web.new(strategy_opts)

      @user_agent   = opts.fetch(:user_agent, "Redd:Web Application:v#{Redd::VERSION} (by unknown)")
      @client_id    = opts.fetch(:client_id)
      @redirect_uri = opts.fetch(:redirect_uri)
      @scope        = opts.fetch(:scope, ['identity'])
      @duration     = opts.fetch(:duration, 'permanent')
      @via          = opts.fetch(:via, '/auth/reddit')
    end

    def call(env)
      # This is done for thread safety so that each thread has its own copy
      # of the middleware logic.
      dup._call(env)
    end

    protected

    def _call(env)
      @request = Rack::Request.new(env)
      return redirect_to_reddit! if @request.path == @via

      before_call
      response = @app.call(env)
      after_call

      response
    end

    private

    # Do any setup before calling the rest of the application.
    def before_call
      # Convert the code to an access token if returning from authentication.
      create_session! if @request.base_url + @request.path == @redirect_uri
      # Clear the state for any other request.
      @request.session.delete(:redd_state)
      # Load a Session model from the access token in the user's cookies.
      @request.env['redd.session'] = parse_session
    end

    # Do any cleanup or changes after calling the application.
    def after_call
      # Clear the session if the app explicitly set 'redd.session' to nil.
      # XXX: does this seem like a good approach?
      @request.session.delete(:redd_session) if @request.env['redd.session'].nil?
    end

    # Creates a unique state and redirects the user to reddit for authentication.
    def redirect_to_reddit!
      state = SecureRandom.urlsafe_base64
      url = Redd.url(
        client_id: @client_id,
        redirect_uri: @redirect_uri,
        scope: @scope,
        duration: @duration,
        state: state
      )
      @request.session[:redd_state] = state
      [302, { 'Location' => url }, []]
    end

{'fraction_non_alphanumeric': 0.10335419675814476, 'fraction_numerical': 0.0016048788316482105, 'mean_word_length': 2.92196349905601, 'pattern_counts': {'":': 0, '<': 7, '<?xml version=': 0, '>': 10, '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': '476419', 'n_tokens_mistral': 1854, 'n_tokens_neox': 1834, 'n_words': 624}