Module: InvitationCodeService

Defined in:
app/services/invitation_code_service.rb

Class Method Summary collapse

Class Method Details

.generate(email) ⇒ Object


3
4
5
6
7
# File 'app/services/invitation_code_service.rb', line 3

def generate(email)
  email_base64 = Base64.encode64(email)
  key = Digest::SHA256.hexdigest(email + Digest::SHA256.hexdigest(email + secret_key))
  "#{email_base64}.#{key}".gsub(/[^\.a-zA-Z0-9]/, '')
end

.invite(user, code) ⇒ Object


21
22
23
24
25
26
27
28
29
30
# File 'app/services/invitation_code_service.rb', line 21

def invite(user, code)
  email = verify(code)
  return nil unless email
  ActiveRecord::Base.transaction do
    user.confirm! if !user.confirmed? && user.email == email
    user.emails.create(email: email)
    user.unconfirmed_emails.find_by(email: email).confirm!
  end
  user.reload
end

.verify(code) ⇒ Object


9
10
11
12
13
14
15
16
17
18
19
# File 'app/services/invitation_code_service.rb', line 9

def verify(code)
  return nil unless code
  code_split = code.split('.')
  email = Base64.decode64(code_split[0])
  code_gen = generate(email)
  if code_gen == code
    email
  else
    nil
  end
end