lib/panoptes/client/authentication.rb in panoptes-client-0.4.0 vs lib/panoptes/client/authentication.rb in panoptes-client-1.0.0.pre
- old
+ new
@@ -3,68 +3,82 @@
module Panoptes
class Client
module Authentication
extend Gem::Deprecate
+ attr_reader :payload
+
def jwt_payload
raise NotLoggedIn unless @auth[:token]
- payload, = decode_token(@auth[:token])
- payload
+ @payload = decode_token(@auth[:token])
rescue JWT::ExpiredSignature
raise AuthenticationExpired
end
def token_contents
- if !@payload.nil? && expiry_from_payload(@payload) > Time.now.utc
- @payload.fetch('data', {})
- elsif @payload.nil?
- @payload = jwt_payload
- @expires_at = expiry_from_payload(@payload)
- @payload.fetch('data', ())
+ if payload_exists? && !payload_expired?
+ # use the cached version of the payload while not expired
+ payload['data']
else
- raise AuthenticationExpired
+ # decode the payload from the JWT token
+ jwt_payload['data']
end
end
def token_expiry
- @expires_at || expiry_from_payload(jwt_payload)
+ # always decode and fetch the expiry time from the JWT token
+ Time.at(jwt_payload.fetch('exp',0)).utc
end
def authenticated?
!!token_contents['id']
end
def authenticated_user_login
- raise NotLoggedIn unless authenticated?
+ ensure_authenticated
token_contents.fetch('login', nil)
end
def authenticated_user_display_name
- raise NotLoggedIn unless authenticated?
+ ensure_authenticated
token_contents.fetch('dname', nil)
end
def authenticated_user_id
- raise NotLoggedIn unless authenticated?
+ ensure_authenticated
token_contents.fetch('id')
end
def authenticated_admin?
- raise NotLoggedIn unless authenticated?
+ ensure_authenticated
token_contents.fetch('admin', false)
end
def current_user
token_contents
end
deprecate :current_user, :token_contents, 2019, 7
- def jwt_signing_public_key
- @jwt_signing_public_key ||= OpenSSL::PKey::RSA.new(File.read(@public_key_path))
+ private
+
+ def ensure_authenticated
+ raise NotLoggedIn unless authenticated?
end
- def expiry_from_payload(payload)
- Time.at(payload.fetch('exp',0)).utc
+ def payload_exists?
+ !!@payload
+ end
+
+ def payload_expiry_time
+ @payload_expiry_time ||= Time.at(payload.fetch('exp',0)).utc
+ end
+
+ def payload_expired?
+ payload_expiry_time < Time.now.utc
+ end
+
+ def jwt_signing_public_key
+ @jwt_signing_public_key ||= OpenSSL::PKey::RSA.new(File.read(@public_key_path))
end
def decode_token(token)
payload, = JWT.decode token, jwt_signing_public_key, algorithm: 'RS512'
payload