Why Gemfury? Push, build, and install  RubyGems npm packages Python packages Maven artifacts PHP packages Go Modules Debian packages RPM packages NuGet packages

Repository URL to install this package:

Details    
uoy-faculty-sinatra / lib / sinatra / basic_passwordless_auth.rb
Size: Mime:
# frozen_string_literal: true

module Sinatra
  # Helpers for development mode - using basic auth
  module BasicPasswordlessAuth
    # Sinatra instance methods (callable from routes, etc)
    module Helpers
      include Sinatra::AuthHelpers

      def authenticate!
        headers['WWW-Authenticate'] = 'Basic realm="Development"'

        auth = Rack::Auth::Basic::Request.new(request.env)
        if auth.provided? && auth.basic? && auth.credentials
          username, = auth.credentials
          halt 401, "Not authorized\n" if username.empty?
          session[:username] = username
        else
          halt 401, "Not authorized\n"
        end
      end
    end

    def self.registered(app) # rubocop:disable Metrics/MethodLength, Metrics/AbcSize
      raise 'Refusing to use passwordless auth in production' if app.production?

      app.helpers Helpers

      app.get '/logout' do
        auth = Rack::Auth::Basic::Request.new(request.env)
        if auth.provided? && auth.basic? && auth.credentials
          username, = auth.credentials
          if username == params[:user].to_s
            session.clear
            redirect '/'
          end
        end

        headers['WWW-Authenticate'] = 'Basic realm="Development"'
        halt 401, "Not authorized\n"
      end
    end
  end
end