Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
jwt_auth_controller.rb
class JWTAuthController < ActionController::API
attr_reader :current_user
protected
def authenticate_request!
fail StandardError.new('NotAuthenticatedError') unless user_id_included_in_auth_token?
@current_user = User.find(decoded_auth_token['user_id'])
rescue JWT::ExpiredSignature
raise StandardError.new('AuthenticationTimeoutError')
rescue JWT::VerificationError, JWT::DecodeError
raise StandardError.new('NotAuthenticatedError')
end
private
def user_id_included_in_auth_token?
http_auth_token && decoded_auth_token && decoded_auth_token['user_id']
end
def decoded_auth_token
@decoded_auth_token ||= AuthToken.decode(http_auth_token)[0]
end
def http_auth_token
if request.headers['Authorization'].blank? && params[:headers].blank?
raise StandardError.new("NotAuthenticatedError")
end
authorization = request.headers['Authorization'] || params[:headers][:authorization]
@http_auth_token ||= if authorization.present?
authorization.split(' ').last
end
end
def authentication_timeout
render json: { errors: ['Authentication Timeout'] }, status: 419
end
def forbidden_resource
render json: { errors: ['Not Authorized To Access Resource'] }, status: :forbidden
end
def user_not_authenticated
render json: { errors: ['Not Authenticated'] }, status: :unauthorized
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.