1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84
|
# frozen-string-literal: true
module Rodauth
Feature.define(:http_basic_auth, :HttpBasicAuth) do
auth_value_method :http_basic_auth_realm, "protected"
auth_value_method :require_http_basic_auth?, false
def logged_in?
ret = super
if !ret && !defined?(@checked_http_basic_auth)
http_basic_auth
ret = super
end
ret
end
def require_login
if require_http_basic_auth?
require_http_basic_auth
end
super
end
def require_http_basic_auth
unless http_basic_auth
set_http_basic_auth_error_response
return_response
end
end
def http_basic_auth
return @checked_http_basic_auth if defined?(@checked_http_basic_auth)
@checked_http_basic_auth = nil
return unless token = ((v = request.env['HTTP_AUTHORIZATION']) && v[/\A *Basic (.*)\Z/, 1])
username, password = token.unpack("m*").first.split(/:/, 2)
return unless username && password
catch_error do
unless account_from_login(username)
throw_basic_auth_error(login_param, no_matching_login_message)
end
before_login_attempt
unless open_account?
throw_basic_auth_error(login_param, no_matching_login_message)
end
unless password_match?(password)
after_login_failure
throw_basic_auth_error(password_param, invalid_password_message)
end
transaction do
before_login
login_session('password')
after_login
end
@checked_http_basic_auth = true
return true
end
nil
end
private
def set_http_basic_auth_error_response
response.status = 401
set_response_header("www-authenticate", "Basic realm=\"#{http_basic_auth_realm}\"")
end
def throw_basic_auth_error(*args)
set_http_basic_auth_error_response
throw_error(*args)
end
end
end
|