Module: Spree::Api::V3::JwtAuthentication

Extended by:
ActiveSupport::Concern
Includes:
ErrorHandler
Included in:
BaseController
Defined in:
app/controllers/concerns/spree/api/v3/jwt_authentication.rb

Constant Summary collapse

USER_TYPE_CUSTOMER =
'customer'.freeze
USER_TYPE_ADMIN =
'admin'.freeze
JWT_AUDIENCE_STORE =
'store_api'.freeze
JWT_AUDIENCE_ADMIN =
'admin_api'.freeze
JWT_ISSUER =
'spree'.freeze

Constants included from ErrorHandler

ErrorHandler::ERROR_CODES

Instance Method Summary collapse

Instance Method Details

#authenticate_userObject

Optional authentication - doesn’t fail if no token



21
22
23
24
25
26
27
28
29
30
31
# File 'app/controllers/concerns/spree/api/v3/jwt_authentication.rb', line 21

def authenticate_user
  token = extract_token
  return unless token.present?

  payload = decode_jwt(token)
  @current_user = find_user_from_payload(payload)
rescue JWT::DecodeError, JWT::ExpiredSignature, JWT::InvalidIssuerError,
       JWT::InvalidAudError, ActiveRecord::RecordNotFound => e
  Rails.logger.debug { "JWT authentication failed: #{e.message}" }
  @current_user = nil
end

#require_authentication!Object

Required authentication - fails if no valid token Returns true if authenticated, false otherwise (also renders error and halts)



35
36
37
38
39
40
41
42
# File 'app/controllers/concerns/spree/api/v3/jwt_authentication.rb', line 35

def require_authentication!
  authenticate_user

  return true if current_user

  render_error(code: ErrorHandler::ERROR_CODES[:authentication_required], message: 'Authentication required', status: :unauthorized)
  false
end