Search code examples
sinatrabasic-authentication

Sinatra HTTP Basic Authentication get user and keep to use inside routes


I'm building an small API in sinatra. I need to authenticate the routes, and I have that already working doing the following (as read from the documentation)

use Rack::Auth::Basic,"Protected Area" do |username, password|
   user = User.validate username, password
end

But I'll have multiple users, so I'm doing something like this:

class Protected < Sinatra::Base
    use Rack::Auth::Basic,"Protected Area" do |username, password|
        User.validate username, password
    end

    get '/users' do
        content_type :json
        #I want to return the user who was authenticated
    end    
end

The class method Validate returns the user if the user does exists in the database or returns false if it doesn't exists. But what I have no idea how to do is how to access that user from inside a route, for example get '/users' do

Thanks!


Solution

  • If HTTP Authentication is enforced, the user's name is available in the request object, for instance:

    use Rack::Auth::Basic,"Protected Area" do |username, password|
      User.validate username, password
    end
    
    get '/' do
      user = request.env["REMOTE_USER"]
      "Hello, #{user}"
    end
    

    Please note that the HTTP authentication scheme can be awkward to use, you might want to consider using sessions instead.