Created
April 5, 2015 09:11
-
-
Save yasaichi/5d95af6c75bcdad42675 to your computer and use it in GitHub Desktop.
パーフェクト Ruby on Rails 10章
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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