Module: Truefactor::Model::TruefactorizedMethods

Defined in:
lib/truefactor/model.rb

Instance Method Summary collapse

Instance Method Details

#to_digits(s) ⇒ Object



49
50
51
52
53
54
55
56
# File 'lib/truefactor/model.rb', line 49

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



36
37
38
39
40
41
42
43
44
45
46
47
# File 'lib/truefactor/model.rb', line 36

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



14
15
16
17
18
19
20
21
# File 'lib/truefactor/model.rb', line 14

def truefactor_signatures(challenge, raw = false)
  seed1, seed2 = self.truefactor.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)


23
24
25
26
27
28
29
30
31
32
33
34
# File 'lib/truefactor/model.rb', line 23

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.present?

  real_sig == sig1
end