背景:
專案本身已使用devise來為使用者驗證,如今多加google oauth2
驗證登入一項。
1. 加入omniauth-google-oauth2 Gem
$ subl Gemfile
gem 'omniauth-google-oauth2'
$ bundle install
2. API申請位置
Google:https://cloud.google.com/console
啟用”Contacts API
” and “Google+ API
”
注意:網址沒有 https://
$ rails g migration AddColumnsToUsers provider:string uid:string
因為omniauth 和 devise搭配,所以不需要為users再開欄位,目前夠用。
3. 將剛剛從google api申請的金鑰加進去
“config/initializers/devise.rb”
config.omniauth :google_oauth2, "APP_ID", "APP_SECRET", { }
4. 修改routes.rb,加入callback routes
“config/routes.rb”
devise_for :users, :controllers => { :omniauth_callbacks => "users/omniauth_callbacks" }
5. 為user model加入以下程式碼
“/app/models/user.rb”
devise :omniauthable, :omniauth_providers => [:google_oauth2]
以下為完整版程式碼:
devise :database_authenticatable, :registerable, :recoverable, :rememberable, :trackable, :validatable, :omniauthable, :omniauth_providers => [:google_oauth2]
6. 創建callbacks controller 和新增相關程式碼
$ rails g controller OmniauthCallbacks
def google_oauth2 @user = User.from_omniauth(request.env["omniauth.auth"]) sign_in_and_redirect @user end
7. 去user model 做判斷,舊用戶直接登入,如果是新用戶就新增新帳號
$ subl app/model/user.rb
def self.from_omniauth(auth) user = User.where(email: auth.info.email).first if user.name.blank? user.provider = auth.provider user.uid = auth.uid user.github_link = auth.info.image user.name = auth.info.name user.oauth_token = auth.credentials.token user.password = auth.credentials.token user.oauth_expires_at = Time.at(auth.credentials.expires_at) user.save! user else user.name = auth.info.name user.github_link = auth.info.image user end end
8. 製作一個「登入」按鈕
<%= link_to "Sign in with Google", user_omniauth_authorize_path(:google_oauth2) %>
參考資料:
https://github.com/zquestz/omniauth-google-oauth2
http://deepakrip007.wordpress.com/2013/11/05/google-integration-using-devise-and-omniauth-in-rails-app/