Class: Truefactor::User

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

Instance Method Summary collapse

Instance Method Details

#to_digits(s) ⇒ Object



39
40
41
42
43
44
45
46
# File 'lib/truefactor.rb', line 39

def to_digits(s)
  s = s.to_s
  if s.length == 8
    s.to_i(32).to_s.rjust(12,'0')
  else
    s
  end
end

#to_otp(m, secret = false) ⇒ Object



27
28
29
30
31
32
33
34
35
36
37
# File 'lib/truefactor.rb', line 27

def to_otp(m, secret = false)
  hex = if secret
    OpenSSL::HMAC.hexdigest('sha256', secret, m)
  else
    OpenSSL::Digest::SHA256.hexdigest(m)
  end

  code = (hex.to_i(16) % 10**12).to_s

  '0'*(12-code.length) + code
end

#truefactor_signatures(challenge, raw = false) ⇒ Object



3
4
5
6
7
8
9
10
# File 'lib/truefactor.rb', line 3

def truefactor_signatures(challenge, raw = false)
  prefix, seed1, seed2 = self.encrypted_password.split(':')
  unless raw
    stamp = Time.now.to_i / 120
    challenge = "#{challenge}:#{stamp}" 
  end
  [to_otp(challenge, seed1), to_otp(challenge, seed2)]
end

#valid_truefactor?(challenge, str) ⇒ Boolean

Returns:

  • (Boolean)


12
13
14
15
16
17
18
19
20
21
22
23
# File 'lib/truefactor.rb', line 12

def valid_truefactor?(challenge, str)
  sig1, sig2 = str.gsub(/\s/,'').split(':')

  real_sig = to_otp(truefactor_signatures(challenge).join)

  sig1 = to_digits(sig1)
  sig2 = to_digits(sig2)

  sig1 = to_otp(sig1 + sig2) if !sig2.blank?

  real_sig == sig1
end