Skip to content

Instantly share code, notes, and snippets.

@palkan
Created October 5, 2018 17:06
Show Gist options
  • Save palkan/e00b12651444cf616b31310a211d2cc3 to your computer and use it in GitHub Desktop.
Save palkan/e00b12651444cf616b31310a211d2cc3 to your computer and use it in GitHub Desktop.
jwt_sessions vs. devise
# frozen_string_literal: true
# Adds an ability to use JWT based authentication along
# with a standard devise authentication.
#
# Just include it into your base controller, e.g.:
#
# class ApplicationController < ActionController::Base
# include JWTAuth
# end
module JWTAuth
extend ActiveSupport::Concern
include JWTSessions::RailsAuthorization
included do
# We want to fallback to devise-based authentication in case
# JWT auth failed. So, just ignore for now.
rescue_from JWTSessions::Errors::Unauthorized, with: :jwt_auth_failed
prepend_before_action :authorize_access_request!
skip_before_action :verify_authenticity_token, if: :authorized_by_jwt?
skip_before_action :authenticate_user!, if: :authorized_by_jwt?
end
def current_user
if authorized_by_jwt?
@current_user ||= User.find(payload['user_id'])
else
super
end
end
def authorize_access_request!
return unless request.headers[JWTSessions.access_header].present?
super
@authorized_by_jwt = true
end
def authorized_by_jwt?
@authorized_by_jwt == true
end
def jwt_auth_failed(e)
if e.message =~ /signature has expired/i
render json: { error: "Token has expired" }, status: :unauthorized
else
render json: { error: "Auth failed" }, status: :unauthorized
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment