Class: RailsMFA::TokenManager

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

Instance Method Summary collapse

Constructor Details

#initialize(store: RailsMFA.configuration.token_store) ⇒ TokenManager

Returns a new instance of TokenManager.



8
9
10
# File 'lib/rails_mfa/token_manager.rb', line 8

def initialize(store: RailsMFA.configuration.token_store)
  @store = store
end

Instance Method Details

#generate_numeric_code(user_id, length: RailsMFA.configuration.code_length, expiry: RailsMFA.configuration.code_expiry_seconds) ⇒ Object



12
13
14
15
16
17
18
19
# File 'lib/rails_mfa/token_manager.rb', line 12

def generate_numeric_code(user_id, length: RailsMFA.configuration.code_length,
                          expiry: RailsMFA.configuration.code_expiry_seconds)
  min = 10**(length - 1)
  max = (10**length) - 1
  code = rand(min..max).to_s
  @store.write(cache_key(user_id), code, expires_in: expiry)
  code
end

#verify_numeric_code(user_id, code) ⇒ Object



21
22
23
24
25
26
27
28
# File 'lib/rails_mfa/token_manager.rb', line 21

def verify_numeric_code(user_id, code)
  stored = @store.read(cache_key(user_id))
  return false unless stored

  valid = ActiveSupport::SecurityUtils.secure_compare(stored.to_s, code.to_s)
  @store.delete(cache_key(user_id)) if valid # one-time use
  valid
end