【发布时间】:2019-02-07 04:34:26
【问题描述】:
我意识到 authenticate_user! 在 gem 文件中是 not explicitly defined,但我想知道对于典型的应用程序(对名为 User 的模型进行身份验证),该方法会是什么样子。我需要知道,以便我可以稍微修改它。
【问题讨论】:
标签: ruby-on-rails devise
我意识到 authenticate_user! 在 gem 文件中是 not explicitly defined,但我想知道对于典型的应用程序(对名为 User 的模型进行身份验证),该方法会是什么样子。我需要知道,以便我可以稍微修改它。
【问题讨论】:
标签: ruby-on-rails devise
我相信你链接到你自己的答案,它定义的方法是
def authenticate_#{mapping}!(opts={})
opts[:scope] = :#{mapping}
warden.authenticate!(opts) if !devise_controller? || opts.delete(:force)
end
如果我们替换了真正的类,在你的情况下是 User,它看起来像:
def authenticate_user!(opts={})
opts[:scope] = :user
warden.authenticate!(opts) if !devise_controller? || opts.delete(:force)
end
所以它确实需要看守,这就是大部分身份验证逻辑所在。
对于典型的 Rails 应用程序,authenticate_user! 方法将定义为 instance_method 上的 ApplicationController。
【讨论】:
Devise 使用Warden 进行身份验证。为了使用它,Devise 提供了自己的身份验证策略,实现了authenticate! 方法。这就是你需要的。您已经有了代码的第一部分(来自您问题中的链接),即:
def authenticate_user!(opts={})
opts[:scope] = :user
warden.authenticate!(opts) if !devise_controller? || opts.delete(:force)
end
在上面的代码中,warden.authenticate! 使用来自Devise 的方法(由Devise 实现),具体取决于所选的Devise 策略。
例如实现DatabaseAuthenticatable策略的方法在这里:https://github.com/plataformatec/devise/blob/master/lib/devise/strategies/database_authenticatable.rb
实现Rememberable策略的方法在这里:https://github.com/plataformatec/devise/blob/master/lib/devise/strategies/rememberable.rb
【讨论】: