Class: JWTSessions::CSRFToken

Inherits:
Object
  • Object
show all
Defined in:
lib/jwt_sessions/csrf_token.rb

Constant Summary collapse

CSRF_LENGTH =
32

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(csrf_token = nil) ⇒ CSRFToken

Returns a new instance of CSRFToken.



9
10
11
12
# File 'lib/jwt_sessions/csrf_token.rb', line 9

def initialize(csrf_token = nil)
  @encoded = csrf_token || SecureRandom.base64(CSRF_LENGTH)
  @token   = masked_token
end

Instance Attribute Details

#encodedObject (readonly)

Returns the value of attribute encoded.



7
8
9
# File 'lib/jwt_sessions/csrf_token.rb', line 7

def encoded
  @encoded
end

#tokenObject (readonly)

Returns the value of attribute token.



7
8
9
# File 'lib/jwt_sessions/csrf_token.rb', line 7

def token
  @token
end

Instance Method Details

#valid_authenticity_token?(encoded_masked_token) ⇒ Boolean

Returns:

  • (Boolean)


14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
# File 'lib/jwt_sessions/csrf_token.rb', line 14

def valid_authenticity_token?(encoded_masked_token)
  if !encoded_masked_token.is_a?(String) || encoded_masked_token.empty?
    return false
  end

  begin
    masked_token = Base64.strict_decode64(encoded_masked_token)
  rescue ArgumentError
    return false
  end

  if masked_token.length == CSRF_LENGTH
    secure_compare(masked_token, raw_token)
  elsif masked_token.length == CSRF_LENGTH * 2
    csrf_token = unmask_token(masked_token)
    secure_compare(csrf_token, raw_token)
  else
    false
  end
end