Skip to content

Instantly share code, notes, and snippets.

Created December 30, 2021 01:52
Show Gist options
  • Save minghz/d899c7961eb4a6b515cc4e7a571269b2 to your computer and use it in GitHub Desktop.
Save minghz/d899c7961eb4a6b515cc4e7a571269b2 to your computer and use it in GitHub Desktop.
Overriding DeviseTokenAuth render_error()
# Create a module, and put this somewhere your controllers can access.
# In this example, its assumed to be in the same dir as application_controller.rb
module DeviseTokenAuthRenderErrorOverride
# 2. Overrides in application controller calling authenticate_user!
# (or authenticate_[model]! if its a custom model)
def render_authenticate_error
render_error(401, I18n.t('devise.failure.unauthenticated'))
# 1. Overrides in every DeviseTokenAuth controller
# For example, the below method is called from
# DeviseTokenAuth::SessionsController
# DeviseTokenAuth::RegistrationsController
# ... etc
# Here, you can serialize the response whatever way you want.
# As a loose example, we are using our own MyErrorSerializer
def render_error(status, message, data = nil)
response = MyErrorSerializer.hash(status, message)
response = response.merge(data) if data
render status: status, json: response
# In your ApplicationController prepend your override module such that
# the overrides you defined in the above module can apply to all child controllers
# Note that in this example, we are using ActionController::API since
# our application is assumed to be API-only
class ApplicationController < ActionController::API
include DeviseTokenAuth::Concerns::SetUserByToken
prepend DeviseTokenAuthRenderErrorOverride
# remaining code...
# You will also need to create customer DeviseTokenAuth controllers for all the
# controllers in order to prepend the override module.
# Here is the official docs on how to do it:
# Below is an example of one override controller
class Overrides::SessionsController < DeviseTokenAuth::SessionsController
prepend DeviseTokenAuthRenderErrorOverride
# Do this for all the overwritable controllers
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment