How to make really simple Sinatra LDAP authentication?

I looked at the Sinatra docs and they only refer to HTTP authentication. I am looking for a really simple way to control access to routes based on user authorization / authentication through an LDAP server.

I have already built a class that executes the LDAP bit and returns an LDAP object if the user has successfully authenticated and nil if they did not:

>>DirectoryUser.authenticate('user', 'password')
#<DirectoryUser:0x007ffb589a2328>

I can use this to determine if they have successfully authenticated or not.

As a next step, I want to combine this into a simple Sinatra application that provides a form for collecting LDAP user and password:

require 'directoryUser'
require 'sinatra'

enable :sessions

  get '/form' do
    username        = params[:username]
    password     = params[:password]
    haml :form
  end

Then I want to allow routes only if the "DirectoryUser" object exists:

get '/protected' do # Only if DirectoryUser object exists 
    "This route is protected"
end

get '/unprotected' do  
    "This route is unprotected"
end

, , , .

+5
1

, - :

require 'directoryUser'
require 'sinatra'

enable :sessions

helpers do
  def authorize!
    redirect(to('/login')) unless session[:user_id]
  end
end

get '/login' do
  haml :login # with the login form
end

post '/login' do
  user = DirectoryUser.authenticate(params[:username], params[:password])

  if user
    session[:user_id] = user.id
    # Or: session[:logged_in] = true, depending on your needs.
    redirect to('/protected')
  else
    redirect to('/login')
  end
end

get '/protected' do
  authorize!
  'This route is protected'
end

get '/unprotected' do  
  'This route is unprotected'
end
+2

All Articles