Question

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!

Was it helpful?

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.

OTHER TIPS

TITLE = "Password protected Area"
# TITLE = "The page is password protected, please provide a password. (any username is ok)" # alternative title

use Rack::Auth::Basic, TITLE do |_, password|
  password != File.read("./config/password.txt").strip
end

is he simplest solution in my opinion.

It reads from a text file, that you should add to your gitignore

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top