Module: HaveIBeenPwned
- Defined in:
- lib/version.rb,
lib/have-i-been-pwned.rb
Constant Summary collapse
- VERSION =
'1.2.0'.freeze
- DEFAULT_TIMEOUT =
30
Class Method Summary collapse
-
.pwned(password, timeout: DEFAULT_TIMEOUT) ⇒ Boolean
Check to see if a given password has been pwned/compromised by a breach.
-
.pwned_account(email, api_key = nil, user_agent = 'haveibeenpwned-ruby-sdk', timeout: DEFAULT_TIMEOUT) ⇒ [Hash]?
Check to see if the given account was involved in a data breach.
Class Method Details
.pwned(password, timeout: DEFAULT_TIMEOUT) ⇒ Boolean
Check to see if a given password has been pwned/compromised by a breach.
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 |
# File 'lib/have-i-been-pwned.rb', line 13 def pwned password, timeout: DEFAULT_TIMEOUT # if password is not nil if password # get a digest of the password digest = Digest::SHA1.hexdigest password # make sure we nil the password password = nil # get the first 5 characters of the hash first_five = digest[0..4] # make the API call results = HTTParty.get("https://api.pwnedpasswords.com/range/#{first_five}", timeout: timeout) # guard: if we dont get something back return false unless results.code == 200 # split the string based on line breaks into an array res_array = results.split("\n") # interate through the list of hashes res_array.each do |partial_hash| # hashes are formatted hash:count # ex. 0018A45C4D1DEF81644B54AB7F969B88D65:1 # return true if we find a match return true if "#{first_five}#{partial_hash.split(':')[0]}".upcase == digest.upcase end # return false if we dont find anything return false end end |
.pwned_account(email, api_key = nil, user_agent = 'haveibeenpwned-ruby-sdk', timeout: DEFAULT_TIMEOUT) ⇒ [Hash]?
Check to see if the given account was involved in a data breach
49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 |
# File 'lib/have-i-been-pwned.rb', line 49 def pwned_account email, api_key = nil, user_agent = 'haveibeenpwned-ruby-sdk', timeout: DEFAULT_TIMEOUT api_key ||= ENV['HIBP_API_KEY'] # for testing throw 'You must provide a paid API key from haveibeenpwned.com to use this feature.' if api_key.nil? headers = { 'user-agent' => user_agent, 'Hibp-Api-Key' => api_key } results = HTTParty.get("https://haveibeenpwned.com/api/v3/breachedaccount/#{email}", headers: headers, timeout: timeout) return if results.nil? error_check = Hash[results.map { |(k, v)| [k.downcase.to_sym, v] }] rescue nil if !error_check results.map! { |item| Hash[item.map { |(k, v)| [k.downcase.to_sym, v] }] } results else throw error_check[:message] end end |