Class: Snuffleupagus::AuthToken
- Inherits:
-
Object
- Object
- Snuffleupagus::AuthToken
- Defined in:
- lib/snuffleupagus/auth_token.rb
Overview
Handles basic time-limited authentication token creation / validation
Uses OpenSSL AES with 256 bit CBC encryption
## Basic Usage
### Token creation
snuffy = Snuffleupagus::AuthToken.new('p4ssw0rd')
snuffy.create_token
#=> "53616c7465645f5f25dba4d4a97b238c4560ab46ffdfb77b28ad3e7121ab1917"
### Token validation
snuffy = Snuffleupagus::AuthToken.new('p4ssw0rd')
snuffy.check_token("53616c7465645f5f25dba4d4a97b238c4560ab46ffdfb77b28ad3e7121ab1917")
#=> true
Instance Method Summary collapse
- #create_token(context:) ⇒ Object
-
#initialize(key) ⇒ AuthToken
constructor
A new instance of AuthToken.
- #token_valid?(token:, context:) ⇒ Boolean
Constructor Details
#initialize(key) ⇒ AuthToken
Returns a new instance of AuthToken.
25 26 27 28 |
# File 'lib/snuffleupagus/auth_token.rb', line 25 def initialize(key) @key = key @cipher = OpenSSL::Cipher.new('aes-256-cbc') end |
Instance Method Details
#create_token(context:) ⇒ Object
30 31 32 |
# File 'lib/snuffleupagus/auth_token.rb', line 30 def create_token(context:) encode encrypt "#{CONSTANT}#{context}#{Time.now.to_i}" end |
#token_valid?(token:, context:) ⇒ Boolean
34 35 36 37 38 39 40 41 42 43 44 |
# File 'lib/snuffleupagus/auth_token.rb', line 34 def token_valid?(token:, context:) return false unless token.is_a? String decoded = decrypt decode token match = /\A#{CONSTANT}#{Regexp.escape(context)}([0-9]+)\z/.match decoded return false unless match (match[1].to_i - Time.now.to_i).abs < MAX_VALID_TIME_DIFFERENCE rescue StandardError false end |