轨道:来自上下文的门卫自定义响应



我们使用门卫宝石通过API对用户进行身份验证。自从我们几年前实施它以来,一切都运行良好,我们使用password赠款流程,如示例中所示:

resource_owner_from_credentials do |_routes|
user = User.active.find_for_database_authentication(email: params[:username])
if user&.valid_password?(params[:password])
sign_in(user, force: true)
user
end
end

门卫与Devise相结合,可以实现reconfirmable策略。正如您在上面的代码中看到的,我们只允许active用户(即具有已确认电子邮件的用户(连接:

User.active.find_.....

问题

我们的规格发生了变化,现在我们希望在登录时返回不同的错误(针对/oauth/token(,具体取决于用户是否已确认其电子邮件。 现在,如果登录失败,门卫将返回以下 JSON:

{
"error": "invalid_grant",
"error_description": "The provided authorization grant is invalid, expired, revoked, does not match the redirection URI used in the authorization request, or was issued to another client."
}

理想情况下,我们希望能够返回自定义描述,当且仅当当前尝试登录的电子邮件unconfirmed

我们已经检查了有关Doorkeeper的文档,但它似乎没有简单的方法(如果有的话(来做到这一点。resource_owner_from_credentials方法位于配置中的事实增加了太多的魔力,而没有足够的灵活性。

有什么想法吗?

好的,所以在挖掘了一点之后,我们找到了一种通过覆盖Doorkeeper::TokensController来解决此问题的简单方法。

# frozen_string_literal: true
class TokensController < Doorkeeper::TokensController
before_action :check_if_account_is_pending, only: :create
private
def check_if_account_is_pending
user = User.find_by(email: params['username'])
render json: unconfirmed_account_error if user && !user.confirmed?
end
def unconfirmed_account_error
{ error: 'invalid', error_description: 'You must validate your email address before login' }
end
end

我们还需要确保路由指向自定义控制器:

use_doorkeeper do
controllers tokens: 'tokens'
end

希望它能在未来帮助某人

最新更新