add credentials_for

master
Kanezoh 2022-01-01 13:27:20 +09:00
parent c3e8c15c6b
commit 67051da876
2 changed files with 26 additions and 10 deletions

View File

@ -6,8 +6,19 @@ describe "Mechanize AuthStore test" do
url = URI.parse("http://example.com/") url = URI.parse("http://example.com/")
user = "kanezoh" user = "kanezoh"
password = "password" password = "password"
realm = ""
auth_store.add_auth(url, user, password) auth_store.add_auth(url, user, password)
auth_store.auth_accounts.size.should eq 1 auth_store.auth_accounts[url].size.should eq 1
auth_store.auth_accounts[url].should eq({"kanezoh", "password"}) auth_store.auth_accounts[url][realm].should eq(["kanezoh", "password", nil])
end
it "credentials_for" do
auth_store = Mechanize::HTTP::AuthStore.new
url = URI.parse("http://example.com/")
user = "kanezoh"
password = "password"
realm = ""
auth_store.add_auth(url, user, password)
auth_store.credentials_for(url, realm).should eq ["kanezoh", "password", nil]
end end
end end

View File

@ -2,25 +2,28 @@ class Mechanize
module HTTP module HTTP
# This class store info for HTTP Authentication. # This class store info for HTTP Authentication.
class AuthStore class AuthStore
getter auth_accounts : Hash(URI, Tuple(String, String)) getter auth_accounts : Hash(URI, Hash(String, Array(String?)))
def initialize def initialize
@auth_accounts = Hash(URI, Tuple(String, String)).new @auth_accounts = Hash(URI, Hash(String, Array(String?))).new
end end
def add_auth(uri, user, pass) def add_auth(uri : String | URI, user : String, pass : String, realm : String? = nil, domain : String? = nil)
unless uri.is_a?(URI) unless uri.is_a?(URI)
uri = URI.new(uri) uri = URI.new(uri)
end end
# uri += '/' # uri += '/'
uri.user = nil uri.user = nil
uri.password = nil uri.password = nil
if realm.nil?
auth_accounts[uri] = {user, pass} realm = ""
end ## end
realm_hash = {realm => [user, pass, domain]}
auth_accounts[uri] = realm_hash
end
# Retrieves credentials for +realm+ on the server at +uri+. # Retrieves credentials for +realm+ on the server at +uri+.
def credentials_for(uri, realm) : Tuple(String) def credentials_for(uri : String | URI, realm : String) : Array(String?)
unless uri.is_a?(URI) unless uri.is_a?(URI)
uri = URI.new(uri) uri = URI.new(uri)
end end
@ -28,7 +31,9 @@ class Mechanize
uri.user = nil uri.user = nil
uri.password = nil uri.password = nil
auth_accounts[uri] realms = auth_accounts[uri]
realms[realm]
end end
end end
end end