Skip to content

Instantly share code, notes, and snippets.

@zedtux
Created March 12, 2018 07:37
Show Gist options
  • Save zedtux/c0009c6da743c6082062aaec4b0cafa6 to your computer and use it in GitHub Desktop.
Save zedtux/c0009c6da743c6082062aaec4b0cafa6 to your computer and use it in GitHub Desktop.
Google Authenticator OTP calculator (Used in my Cucumber tests)
module DeviseGoogleAuthenticatorHelpers
#
# Returns a valid One Time Password for the Google Authenticator gem.
#
# @param user [User] instance for which a valid OPT is requested.
# @return [Integer] first valid calculated OTP
#
def a_valid_otp_for(user)
calculate_otps_from(user.gauth_secret).first
end
private
def calculate_otps_from(secret)
valid_vals = []
valid_vals << ROTP::TOTP.new(secret).at(Time.now)
(1..User.ga_timedrift).each do |cc|
valid_vals << ROTP::TOTP.new(secret).at(Time.now.ago(30 * cc))
valid_vals << ROTP::TOTP.new(secret).at(Time.now.in(30 * cc))
end
valid_vals
end
end
World(DeviseGoogleAuthenticatorHelpers)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment