Ruby on Rails HTTP based authorization:
def get_auth_data
user, pass, authdata = ”, ”, nil
# mod rewrite, normal, apache
[‘X-HTTP_AUTHORIZATION’, ‘HTTP_AUTHORIZATION’, ‘Authorization’].each do |key|
# extract authorisation credentials
if request.env.has_key? key
authdata = @request.env[key].to_s.split
end
end
# at the moment we only support basic authentication
if authdata and authdata[0] == ‘Basic’
user, pass = Base64.decode64(authdata[1]).split(‘:’)[0..1]
end
return [user, pass]
end
def admin_required(realm=’Admin Password’, errormessage=”Couldn’t authenticate you”)
username, passwd = get_auth_data
user = User.authenticate(username, passwd)
if user and user.admin?
@user = user
else
# bad user/pass, or not authorized
@response.headers[“Status”] = “Unauthorized”
@response.headers[“WWW-Authenticate”] = “Basic realm="#{realm}"”
render :text => errormessage, :status => 401
return false
end
end