I’m trying to implement basic http authentication, but I need to return different HTTP status codes based upon the status of the account beeing authenticated.
I’m using Sinatra to host the API, and this is what my application looks like:
require 'rubygems'
require 'bundler/setup'
require 'sinatra'
require 'active_record'
require 'openssl'
# Define the paths that the application responds to, and include the authentication mechanism to provide
# basic HTTP authentication using the Rack middleware.
use Rack::Auth::Basic do |username, password|
result = LoginApi::User.authenticate(username, password)
# Check the status of the user we just authenticated. If he is banned or unverified then we
# need to return special responses.
throw :halt, [403, 'User is banned'] if LoginApi::AuthUser.user.banned?
throw :halt, [412, 'User is not verified'] unless LoginApi::AuthUser.user.verified?
# Return the result if no exceptions were raised in the meanwhile
result
end
# This action responds on the root of the application and will return the basic authentication of a User
# in the headers. This is done by Rack::Auth, which requires the credentials to be sent in the initial
# call so they can be verified by the application
get '/' do
headers \
"X-UserID" => "#{LoginApi::AuthUser.user.id}|",
"X-P1" => "#{LoginApi::AuthUser.p1}",
"X-P2" => "#{LoginApi::AuthUser.p2}"
end
So basically, it returns a status 200 for ok authentication, 403 for a banned user, 412 for a not verified user and 400 if the authentication fails.
The problem is that I cant get my tests to properly work with this. The test for a normal authentication works fime, and passes, but the tests that need to check for the custom HTTP status reponses fail with the following error:
ArgumentError: uncaught throw :halt ./app.rb:23:in
throw'block in ‘
./app.rb:23:in
./features/step_definitions/when_steps.rb:8:in/^I make the call toWhen I make the call to the
the API$/' ./features/banned.feature:8:in
API’Skipped step
Can someone please explain what I am doing wrong or missing to get this to work as I want it to?
Moved the check for banned and unverified to the body of the action and just handle the result there.
Shame I cannot do it in the Rack helper…