Ruby on Rails做Facebook登入機制:使用Omniauth gem

Omniauth是一個ruby gems,使用它可以讓你不需要像php一樣要include facebook.php,也不用寫前端javascript,它已經 幫你全部做好了,妳只需要用它即可,以下是全部步驟,供參考。

一.修改Gemfile

gem 'omniauth'
gem 'omniauth-facebook','1.4.0'
gem 'certified'

gem 'thin'

二.新增必要controller/action

rails g controller signup index
rails g controller login index

三.修改/config/routes.rb

get '/signup'=>'signup#index'
get '/signup/index'=>'signup#index'
get '/auth/:provider/callback'=>'signup#create'

get '/login'=>'login#index'
get '/login/index'=>'login#index'
get '/login/logout'=>'login#logout'

四. 新增/config/initializer/omniauth.rb

Rails.application.config.middleware.use OmniAuth::Builder do
provider :facebook, 'appid', 'app-secret',
    :scope => 'email,read_stream,publish_stream,user_about_me,user_birthday,offline_access,user_relationships,
    user_likes,user_education_history,user_hometown,user_relationship_details,user_location,user_website,
    user_work_history,publish_actions'

    OmniAuth.config.on_failure = SignupController.action(:failure)
end

五.修改views/login/index.html.erb

<a href="/auth/facebook">facebook login</a>
點了後會導向facebook做認證

六.singup_controller新增create/failure action

def index
  //do something
end

def create
  auth_hash = request.env['omniauth.auth']
  if auth_hash
    uid = auth_hash['uid'].to_s
    authUser = UserAuth.where(login_type:1).where(login_id:uid).first
    //上面只是要從db找看看user存不存在,不一定是UserAuth這個table,這裡儲存在UserAuth,所以從這找
    // login_type=>使用者從facebook登入為1 , login_id=>就是facebook的uid
    if authUser
      //更新token
    else
      //無該使用者,新增user
    end
    //存session後倒回首頁
  else
    //使用者按了授權卻找不到資料就導回首頁
  end
end

def failure
  flash[:notice] = '您尚未經過認證'
  redirect_to :controller=>:signup,:action=>:index
end

#修改玩記得重跑thin
  • 使用者認證後的fb資料都從request.env[‘omniauth.auth’]找,=>auth_hash = request.env[‘omniauth.auth’]
  • token從auth_hash[‘credentials’][‘token’]找
  • provider從auth_hash[‘provider’]找
  • uid從auth_hash[‘uid’]找

七.測試看看

  • url連到/login/index,點選facebook登入,這時應該會導到facebook頁面,使用者點取消會跑signup_controller 的failure action,使用者若按確定會跑signup_controller的create action

以上就是全部步驟囉

參考文件