Skip to content

Instantly share code, notes, and snippets.

@yasaichi
Created April 5, 2015 09:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yasaichi/5d95af6c75bcdad42675 to your computer and use it in GitHub Desktop.
Save yasaichi/5d95af6c75bcdad42675 to your computer and use it in GitHub Desktop.
パーフェクト Ruby on Rails 10章
require 'base64'
class BasicAuth
def initialize(app, user_name:, password:)
@app = app
@user_name = user_name
@password = password
end
def call(env)
if valid_credentials?(env['HTTP_AUTHORIZATION'])
@app.call(env)
else
[401, { 'WWW-Authenticate' => 'Basic realm="Application"' }, ['Bad credentials']]
end
end
private
def valid_credentials?(credentials)
return unless credentials.respond_to?(:match)
credentials.match(/Basic\s+(.+)\z/) do |md|
user_name, password = Base64.decode64(md[1]).scan(/\A(.+):(.*?)\z/).first
user_name == @user_name && password == @password
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment