Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to add Auth::Basic to simple Rack application

Tags:

ruby

rack

how can I add this

use Rack::Auth::Basic do |username, password|
  username == 'pippo' && password == 'pluto'
end

to this

class HelloWorld
  def call(env)
    req = Rack::Request.new(env)
    case req.path_info
    when /badges/
      [200, {"Content-Type" => "text/html"},  ['This is great !!!!']]
    when /goodbye/
      [500, {"Content-Type" => "text/html"}, ["Goodbye Cruel World!"]]
    else
      [404, {"Content-Type" => "text/html"}, ["I'm Lost!"]]
    end
  end
end


run HelloWorld.new

I have this simple Rack application and I need to add Auth::Basic.

Thanks

like image 657
Sig Avatar asked Oct 20 '25 21:10

Sig


1 Answers

You need to use Rack::Builder to compose a stack of rack applications.

Example:

# app.ru
require 'rack'

class HelloWorld
  def call(env)
    req = Rack::Request.new(env)
    case req.path_info
    when /badges/
      [200, {"Content-Type" => "text/html"},  ['This is great !!!!']]
    when /goodbye/
      [500, {"Content-Type" => "text/html"}, ["Goodbye Cruel World!"]]
    else
      [404, {"Content-Type" => "text/html"}, ["I'm Lost!"]]
    end
  end
end

app = Rack::Builder.new do
  use Rack::Auth::Basic do |username, password|
    username == 'pippo' && password == 'pluto'
  end

  map '/' do
    run HelloWorld.new
  end
end

run app

And to start it up:

$ rackup app.ru
like image 57
Kimmo Lehto Avatar answered Oct 23 '25 11:10

Kimmo Lehto



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!