我正在尝试/me
使用omniauth-google-oauth2建立经过身份验证的路由。到目前为止,我已经设置了用于登录和注销的库,并且可以正常工作。但是,我希望只有当用户登录时才能访问某些路由。我找到了该代码段,并做了一些小的更改以适合我的设置。
application_controller.rb
before_filter :authenticate
def authenticate
redirect_to :login unless User.from_omniauth(env["omniauth.auth"])
end
user.rb
def self.from_omniauth(auth)
where(provider: auth.provider, uid: auth.uid).first_or_initialize.tap do |user|
user.provider = auth.provider
user.uid = auth.uid
user.name = auth.info.name
user.first_name = auth.info.first_name
user.last_name = auth.info.last_name
user.email = auth.info.email
user.picture = auth.info.image
user.oauth_token = auth.credentials.token
user.oauth_expires_at = Time.at(auth.credentials.expires_at)
user.save!
end
我用过,env["omniauth"]
因为那是我在中使用的auth哈希SessionsController
。
但是,现在每次去时localhost:3000
,都会出现以下错误:
undefined method `provider' for nil:NilClass
我假设发生这种情况是因为env["omniauth.auth"]
无法从访问application_controller.rb
?如果是这种情况,那么我如何正确访问身份验证哈希?
试试这个:
application_controller.rb
before_filter :authenticate
def authenticate
redirect_to :login unless user_signed_in?
end
def user_signed_in?
!!current_user
end
def current_user
@current_user ||= begin
User.find(session[:current_user_id]) || fetch_user_from_omniauth
end
end
def fetch_user_from_omniauth
user = User.from_omniauth(env['omniauth.auth'])
session[:current_user_id] = user.id
user
end
这将首先尝试获取(从会话中)已登录的用户。如果未找到,它将尝试从omniauth创建用户,然后在会话中设置其ID,以便对于下一个请求,它不需要在env中使用omniauth来查找当前用户。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句