-
-
Save emilsoman/5604254 to your computer and use it in GitHub Desktop.
class CustomAuthFailure < Devise::FailureApp | |
def respond | |
self.status = 401 | |
self.content_type = 'json' | |
self.response_body = {"errors" => ["Invalid login credentials"]}.to_json | |
end | |
end |
thx very good
Alternative approach which I opted for after seeing this and reading Devise::FailureApp was to override the http_auth_body method instead of the respond
method. I also used the inbuilt i18n_message
method to populate the error field.
class FailureApp < Devise::FailureApp
def http_auth_body
{
errors: [
{
id: :unauthorized,
status: 401,
title: i18n_message
}
]
}.to_json
end
end
The reason I wanted to customize the failure handling in the first place was to make the error messages comply with the JSON API standard. so that is what you are seeing here.
Or see https://stackoverflow.com/questions/7297183/custom-devise-401-unauthorized-response/35299936#35299936 for a failure app that handles json and fall back to normal use otherwise
I've used this implementation and it works almost every time. The problem appears when I try to register a user with an existing email address. Rails will skip right to a PG exception. Any thoughts?
I've used this implementation and it works almost every time. The problem appears when I try to register a user with an existing email address. Rails will skip right to a PG exception. Any thoughts?
You're getting the PG exception probably because you're missing the validations on the User model.
And tell devise to use the custom failure app by adding the following to
config/initializers/devise.rb
: