Skip to content

Instantly share code, notes, and snippets.

@ouranos
Created May 26, 2015 00:21
Show Gist options
  • Save ouranos/5819e9b144c8e7ac7a59 to your computer and use it in GitHub Desktop.
Save ouranos/5819e9b144c8e7ac7a59 to your computer and use it in GitHub Desktop.
# config/application.rb
config.middleware.insert_after ActionDispatch::Flash, Warden::Manager do |manager|
manager.default_strategies :authentication_token, :basic_auth
manager.failure_app = UnauthorizedController
end
#lib/strategies/basic_auth_strategy.rb
class BasicAuthStrategy < ::Warden::Strategies::Base
def auth
@auth ||= Rack::Auth::Basic::Request.new(env)
end
def valid?
auth.provided? && auth.basic? && auth.credentials
end
def authenticate!
user = User.find_by_username(auth.credentials[0])
if user && user.authenticate(auth.credentials[1])
success!(user)
else
fail!('strategies.basic_auth.failed')
end
end
end
# config/initializers/warden.rb
require Rails.root.join('lib/strategies/authentication_token_strategy')
require Rails.root.join('lib/strategies/basic_auth_strategy')
Warden::Strategies.add(:authentication_token, AuthenticationTokenStrategy)
Warden::Strategies.add(:basic_auth, BasicAuthStrategy)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment