你如何从Rails中的Omniauth中检索信息?

时间:2015-06-22 23:52:30

标签: ruby-on-rails ruby devise omniauth

我尝试了很多指南和很多教程,但每当我尝试检索Omniauth应该在用户接受权限后提供的信息时。现在我只想让用户登录谷歌并访问他的日历。

的routes.rb

devise_for :users, path_names: {sign_in: "login", sign_out: "logout"},
:controllers => { :omniauth_callbacks => "callbacks" }

devise_scope :user do
get "/auth/google_oauth2/callback" => 'callbacks#google_oauth2'
end

配置/初始化/ omniauth.rb

module OmniAuth
  module Strategies
    class GoogleAuth < OmniAuth::Strategies::GoogleOauth2
    option :name, 'google_auth'
    option :callback_path, '/callbacks/google'
    end
  end
end

Rails.application.config.middleware.use OmniAuth::Builder do
  provider :google_oauth2, '<my client id in string>', '<my client secret in string>', {
  access_type: 'offline',
  scope: 'https://www.googleapis.com/auth/userinfo.email https://www.googleapis.com/auth/calendar',
  callback_path:'http://localhost:3000/auth/google_oauth2/callback'
  prompt: 'select_account consent'
}

 #provider :devloper unless Rails.env.production?
  provider :twitter, ENV['TWITTER_KEY'], ENV['TWITTER_SECRET']

callbacks_controller.rb

class CallbacksController < Devise::OmniauthCallbacksController
 def google_oauth2
   @user = User.from_omniauth(request.env["omniauth.auth"])
   if user.persisted?
        sign_in_and_redirect @user
   else
        session["devise.google_data"] = request.env["omniauth.auth"]
        redirect_to new_user_registration_url
   end
 end
end

模型/ user.rb:

def self.from_omniauth(auth)
  where(provider: auth.provider, uid: auth.uid).first_or_create do |user|
    user.provider = auth.provider
    user.uid = auth.uid
    user.email = auth.info.email
    user.password = Devise.friendly_token[0,20]
end

env [“omniauth.auth”]和:provider的错误。如何更改我的文件,以便Omniauth正确填充用户的信息,以便我可以为该会话创建设计用户。该项目位于https://github.com/SafaTinaztepe/teemvu.git

1 个答案:

答案 0 :(得分:0)

user.rb上,我认为应该是

user.provider = auth['provider'],
user.uid = auth['uid'],
....