使用 Omniauth Google 的经过身份验证的路由

Authenticated routes with Omniauth Google

我正在尝试使用 omniauth-google-oauth2. So far, I have the library set up to login and logout and it's working fine. However, I want to have certain routes be accessible only when a user is logged in. I found this snippet 创建经过身份验证的路由 /me 并进行了一些小的更改以适合我的设置。

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"],因为那是我在 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 来找到当前用户。