Class: JWT::Auth::Token

Inherits:
Object
  • Object
show all
Defined in:
lib/jwt/auth/token.rb

Overview

In-memory representation of JWT

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Instance Attribute Details

#expirationObject

Returns the value of attribute expiration.



13
14
15
# File 'lib/jwt/auth/token.rb', line 13

def expiration
  @expiration
end

#subjectObject

Returns the value of attribute subject.



13
14
15
# File 'lib/jwt/auth/token.rb', line 13

def subject
  @subject
end

#token_versionObject

Returns the value of attribute token_version.



13
14
15
# File 'lib/jwt/auth/token.rb', line 13

def token_version
  @token_version
end

Class Method Details

.from_token(token) ⇒ Object



49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
# File 'lib/jwt/auth/token.rb', line 49

def self.from_token(token)
  begin
    payload = JWT.decode(token, JWT::Auth.secret).first
  rescue JWT::ExpiredSignature
    payload = {}
  end

  token = JWT::Auth::Token.new
  token.expiration = payload['exp']
  token.token_version = payload['ver']

  if payload['sub']
    find_method = JWT::Auth.model.respond_to?(:find_by_token) ? :find_by_token : :find_by
    token.subject = JWT::Auth.model.send find_method, :id => payload['sub'], :token_version => payload['ver']
  end

  token
end

.from_user(subject) ⇒ Object



42
43
44
45
46
47
# File 'lib/jwt/auth/token.rb', line 42

def self.from_user(subject)
  token = JWT::Auth::Token.new
  token.subject = subject

  token
end

Instance Method Details

#renew!Object



28
29
30
31
# File 'lib/jwt/auth/token.rb', line 28

def renew!
  self.expiration = nil
  self.token_version = nil
end

#to_jwtObject



33
34
35
36
37
38
39
40
# File 'lib/jwt/auth/token.rb', line 33

def to_jwt
  payload = {
    :exp => expiration || JWT::Auth.token_lifetime.from_now.to_i,
    :sub => subject.id,
    :ver => token_version || subject.token_version
  }
  JWT.encode payload, JWT::Auth.secret
end

#valid?Boolean

Returns:

  • (Boolean)


15
16
17
18
19
20
21
22
23
24
25
26
# File 'lib/jwt/auth/token.rb', line 15

def valid?
  # Reload subject to prevent caching the old token_version
  subject && subject.reload

  return false if subject.nil? || expiration.nil? || token_version.nil?
  return false if Time.at(expiration).past?
  return false if token_version != subject.token_version

  true
rescue ActiveRecord::RecordNotFound
  false
end