Module: RubyMagicLink::Token

Defined in:
lib/ruby_magic_link/token.rb

Constant Summary collapse

DELIMITER =
'|'
ALGORITHM =
'AES-256-CBC'

Class Method Summary collapse

Class Method Details

.create(payload, expires_in: nil) ⇒ Object



14
15
16
17
18
19
20
21
22
23
24
# File 'lib/ruby_magic_link/token.rb', line 14

def create(payload, expires_in: nil)
  data = { payload: payload }
  if expires_in
    raise(StandardError, '`expires_at` must be an Integer') unless expires_in.is_a? Integer

    data[:expires_in] = Time.now.to_i + expires_in
  end
  iv = OpenSSL::Random.random_bytes(16)
  encrypted_data = encrypt(JSON.generate(data), RubyMagicLink.config.secret_key, iv)
  Base64.urlsafe_encode64(Base64.urlsafe_encode64(iv) + DELIMITER + encrypted_data)
end

.decode(data) ⇒ Object



26
27
28
# File 'lib/ruby_magic_link/token.rb', line 26

def decode(data)
  RubyMagicLink::TokenObject.new(data)
end

.decode_token(token) ⇒ Object



30
31
32
33
# File 'lib/ruby_magic_link/token.rb', line 30

def decode_token(token)
  raw_iv, data = Base64.urlsafe_decode64(token).split(DELIMITER, 2)
  JSON.parse(decrypt(data, RubyMagicLink.config.secret_key, Base64.urlsafe_decode64(raw_iv)))
end

.decrypt(encrypted_data, key, iv) ⇒ Object



43
44
45
46
47
48
49
# File 'lib/ruby_magic_link/token.rb', line 43

def decrypt(encrypted_data, key, iv)
  cipher = OpenSSL::Cipher.new(ALGORITHM)
  cipher.decrypt
  cipher.key = key
  cipher.iv = iv
  cipher.update(encrypted_data) + cipher.final
end

.encrypt(data, key, iv) ⇒ Object



35
36
37
38
39
40
41
# File 'lib/ruby_magic_link/token.rb', line 35

def encrypt(data, key, iv)
  cipher = OpenSSL::Cipher.new(ALGORITHM)
  cipher.encrypt
  cipher.key = key
  cipher.iv = iv
  cipher.update(data) + cipher.final
end