Class: GoogleAuthenticator

Inherits:
Object
  • Object
show all
Defined in:
lib/google_authenticator_auth.rb

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(key = nil) ⇒ GoogleAuthenticator

Load class with the provided secret key. If no key is provided generate a new random secret key



18
19
20
# File 'lib/google_authenticator_auth.rb', line 18

def initialize(key=nil)
  @secret_key = key.nil? ? GoogleAuthenticator.generate_secret_key : key
end

Class Method Details

.generate_secret_keyObject

Generate a unique secret key



23
24
25
# File 'lib/google_authenticator_auth.rb', line 23

def self.generate_secret_key
  Base32.encode( (0...10).map{(rand(255)).chr}.join )
end

Instance Method Details

#get_keysObject

Found at gist.github.com/987839 Returns an array containing the previous, current, and next valid key for the current secret key



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
# File 'lib/google_authenticator_auth.rb', line 52

def get_keys
  keys = []
  int = 30
  now = Time.now.to_i / int
  key = Base32.decode @secret_key
  sha = OpenSSL::Digest::Digest.new('sha1')

  (-1..1).each do |x|
    bytes = [ now + x ].pack('>q').reverse
    hmac = OpenSSL::HMAC.digest(sha, key.to_s, bytes)
    offset = nil
    if RUBY_VERSION > '1.9'
      offset = hmac[-1].ord & 0x0F
    else
      offset = hmac[-1] & 0x0F
    end
    hash = hmac[offset...offset + 4]

    code = hash.reverse.unpack('L')[0]
    code &= 0x7FFFFFFF
    code %= 1000000

    keys << code
  end

  keys
end

#key_valid?(key) ⇒ Boolean

Checks to see if the key is valid for the current secret key

Returns:

  • (Boolean)


45
46
47
# File 'lib/google_authenticator_auth.rb', line 45

def key_valid?(key)
  get_keys.include?(key.to_i)
end

#qrcode_image_url(label, wh = 350) ⇒ Object

Google Charts image URL (resulting image can be scanned by the Google Authenticator app to automaticly import secret key



29
30
31
# File 'lib/google_authenticator_auth.rb', line 29

def qrcode_image_url(label,wh=350)
  "https://chart.googleapis.com/chart?chs=#{wh}x#{wh}&cht=qr&choe=UTF-8&chl=" + uri_parser.escape(qrcode_url(label))
end

#qrcode_url(label) ⇒ Object

QRCode URL used to generate a QRCode that can be scanned into Google Authenticator (see qrcode_image_url)



35
36
37
# File 'lib/google_authenticator_auth.rb', line 35

def qrcode_url(label)
  "otpauth://totp/#{label}?secret=#{@secret_key}"
end

#secret_keyObject

Current secret key



40
41
42
# File 'lib/google_authenticator_auth.rb', line 40

def secret_key
  @secret_key
end