Class: Balaclava::Authenticator

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

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(user_email, cache = Rails.cache) ⇒ Authenticator

Returns a new instance of Authenticator.



8
9
10
11
12
# File 'lib/balaclava/authenticator.rb', line 8

def initialize(user_email, cache = Rails.cache)
  validate_email(user_email)
  @user_email = user_email
  @cache = cache
end

Instance Attribute Details

#cacheObject (readonly)

Returns the value of attribute cache.



6
7
8
# File 'lib/balaclava/authenticator.rb', line 6

def cache
  @cache
end

#user_emailObject (readonly)

Returns the value of attribute user_email.



6
7
8
# File 'lib/balaclava/authenticator.rb', line 6

def user_email
  @user_email
end

Instance Method Details

#registrationObject



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

def registration
  user = create_user
  verification_data = { code: generate_code.to_s }
  cache.write("verification_data#{user.id}", verification_data)
  user
rescue StandardError => e
  raise StandardError, "Registration failed: #{e.message}"
end

#validate_code(provided_code) ⇒ Object



23
24
25
26
27
28
29
30
# File 'lib/balaclava/authenticator.rb', line 23

def validate_code(provided_code)
  user = find_user_by_email(user_email)
  cached_code = cache.read("verification_data#{user.id}")
  raise InvalidCodeError, "Invalid code" unless cached_code == provided_code
  true
rescue StandardError => e
  raise InvalidCodeError, "Code validation failed: #{e.message}"
end