我正在尝试实施基本的http身份验证,但我需要根据身份验证帐户的状态返回不同的HTTP状态代码。 我正在使用Sinatra来托管API,这就是我的应用程序的样子:
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
基本上,它返回状态200用于ok验证,403用于禁止用户,412用于未验证用户,400用于验证失败。
问题是我无法让我的测试正确使用它。正常身份验证的测试工作和传递,但需要检查自定义HTTP状态响应的测试失败,并出现以下错误:
ArgumentError:uncaught throw:halt ./app.rb:23:in
throw' ./app.rb:23:in
阻止' ./features/step_definitions/when_steps.rb:8:in/^I make the call to the API$/' ./features/banned.feature:8:in
当我打电话给 API“跳过步骤
有人可以解释一下我做错了什么或错过了什么让我按照我的意愿去做?
答案 0 :(得分:0)
将禁止和未验证的检查移至动作正文并在那里处理结果。
羞耻我无法在Rack helper中做到这一点......