#360 Facebook Authentication
Jun 25, 2012 | 12 minutes | Plugins, Authentication
This will show how to create a new facebook application and configure it. Then add some authentication with the omniauth-facebook gem and top it off with a client-side authentication using the JavaScript SDK.
- Download:
- source codeProject Files in Zip (191 KB)
- mp4Full Size H.264 Video (29.8 MB)
- m4vSmaller H.264 Video (15.9 MB)
- webmFull Size VP8 Video (17.6 MB)
- ogvFull Size Theora Video (40 MB)
Resources
- Facebook Developers
- Facebook Social Plugins
- omniauth-facebook
- Facebook Client-Side Authentication
- Koala
Gemfile
gem 'omniauth-facebook'
config/initializers/omniauth.rb
OmniAuth.config.logger = Rails.logger Rails.application.config.middleware.use OmniAuth::Builder do provider :facebook, ENV['FACEBOOK_APP_ID'], ENV['FACEBOOK_SECRET'] end
terminal
rails g model user provider uid name oauth_token oauth_expires_at:datetime rake db:migrate
models/user.rb
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
config/routes.rb
match 'auth/:provider/callback', to: 'sessions#create' match 'auth/failure', to: redirect('/') match 'signout', to: 'sessions#destroy', as: 'signout'
sessions_controller.rb
class SessionsController < ApplicationController def create user = User.from_omniauth(env["omniauth.auth"]) session[:user_id] = user.id redirect_to root_url end def destroy session[:user_id] = nil redirect_to root_url end end
application_controller.rb
private def current_user @current_user ||= User.find(session[:user_id]) if session[:user_id] end helper_method :current_user
layouts/application.html.erb
<div id="user_nav"> <% 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 Facebook", "/auth/facebook", id: "sign_in" %> <% end %> </div>
app/assets/javascripts/facebook.js.coffee.erb
jQuery -> $('body').prepend('<div id="fb-root"></div>') $.ajax url: "#{window.location.protocol}//connect.facebook.net/en_US/all.js" dataType: 'script' cache: true window.fbAsyncInit = -> FB.init(appId: '<%= ENV["FACEBOOK_APP_ID"] %>', cookie: true) $('#sign_in').click (e) -> e.preventDefault() FB.login (response) -> window.location = '/auth/facebook/callback' if response.authResponse $('#sign_out').click (e) -> FB.getLoginStatus (response) -> FB.logout() if response.authResponse true