omniauth-google-oauth2を使用して認証済みルート/me
を作成しようとしています。これまでのところ、私はライブラリをログインしてログアウトするように設定しました。うまくいきました。しかし、特定のルートにユーザーがログインしているときにのみアクセスできるようにしたいのですが、this snippetが見つかり、設定に合わせていくつかの小さな変更が加えられました。Omniauth Googleで認証されたルート
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
それは私が私のSessionsController
で使用される認証ハッシュですので、私はenv["omniauth"]
を使用。
しかし、今私が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
:
'from_omniauth'クラスのメソッドは、あなたの' user.rb'ファイルの中でどのように見えますか? –
@JustinLicataはちょうど元の投稿を更新しました – Carpetfizz
"localhost:3000"にアクセスすると、 'env [" omniauth.auth "]'は 'nil'を返しています。私が信じる理由は、このenv変数がソーシャル・ログイン後のコールバック要求でのみ設定されるということです。それ以外のリクエストの場合、これは 'nil'になります。 –