Skip to content

Instantly share code, notes, and snippets.

@bensie
Created June 30, 2011 14:40
Show Gist options
  • Select an option

  • Save bensie/1056354 to your computer and use it in GitHub Desktop.

Select an option

Save bensie/1056354 to your computer and use it in GitHub Desktop.
Sinatra authentication helpers
def auth
@auth ||= Rack::Auth::Basic::Request.new(request.env)
end
def current_user
@current_user
end
def authenticated?
request.env['REMOTE_USER']
end
def authenticate(email, password)
if @current_user = User.find_by_email(email)
@current_user.valid_password?(password)
end
end
def authenticate!
return if authenticated?
halt_with_401_authorization_required unless auth.provided?
handle_authentication_credentials
end
def permit_authentication
return if authenticated?
handle_authentication_credentials if auth.provided?
end
def handle_authentication_credentials
halt_with_400_bad_request unless auth.basic? && auth.credentials
halt_with_401_authorization_required("Bad credentials") unless authenticate(*auth.credentials)
request.env['REMOTE_USER'] = auth.username
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment