我用omniauth实现了Facebook Button,它有效。我找不到实施Google Button的教程。你可以指导我或分享一些步骤来整合它。非常感谢你。
答案 0 :(得分:1)
Here你可以找到一个教程:
<强>的Gemfile:强>
gem "omniauth-google-oauth2", "~> 0.2.1"
<强>配置/初始化/ omniauth.rb:强>
OmniAuth.config.logger = Rails.logger
Rails.application.config.middleware.use OmniAuth::Builder do
provider :google_oauth2, 'my Google client id', 'my Google client secret', {client_options: {ssl: {ca_file: Rails.root.join("cacert.pem").to_s}}}
end
终端命令:
rails g model user provider uid name oauth_token oauth_expires_at:datetime
rake db:migrate
终端命令:
rails g controller home show
rails g controller Sessions create destroy
<强>配置/ routes.rb中:强>
GoogleAuthExample::Application.routes.draw do
get 'auth/:provider/callback', to: 'sessions#create'
get 'auth/failure', to: redirect('/')
get 'signout', to: 'sessions#destroy', as: 'signout'
resources :sessions, only: [:create, :destroy]
resource :home, only: [:show]
root to: "home#show"
end
应用/模型/ user.rb:强>
class User < ActiveRecord::Base
def self.from_omniauth(auth)
where(auth.slice(:provider, :uid)).first_or_initialize.tap do |user|
user.provider = auth.provider
user.uid = auth.uid
user.name = auth.info.name
user.oauth_token = auth.credentials.token
user.oauth_expires_at = Time.at(auth.credentials.expires_at)
user.save!
end
end
end
应用/控制器/ application_controller.rb:强>
class ApplicationController < ActionController::Base
protect_from_forgery with: :exception
helper_method :current_user
def current_user
@current_user ||= User.find(session[:user_id]) if session[:user_id]
end
end
应用/控制器/ sessions_controller.rb:强>
class SessionsController < ApplicationController
def create
user = User.from_omniauth(env["omniauth.auth"])
session[:user_id] = user.id
redirect_to root_path
end
def destroy
session[:user_id] = nil
redirect_to root_path
end
end
应用/视图/布局/ application.html.erb:强>
<!DOCTYPE html>
<html>
<head>
<title>Google Auth Example App</title>
<%= stylesheet_link_tag "application", media: "all", "data-turbolinks-track" => true %>
<%= javascript_include_tag "application", "data-turbolinks-track" => true %>
<%= csrf_meta_tags %>
</head>
<body>
<div>
<% if current_user %>
Signed in as <strong><%= current_user.name %></strong>!
<%= link_to "Sign out", signout_path, id: "sign_out" %>
<% else %>
<%= link_to "Sign in with Google", "/auth/google_oauth2", id: "sign_in" %>
<% end %>
</div>
<div>
<%= yield %>
</div>
</body>
</html>