· 1 min read
Screencast: Authentifizierung über Facebook
Downloads in verschiedenen Formaten:
Resourcen:
Gemfile
[ruby] gem ‘omniauth-facebook’ [/ruby]
config/initializers/omniauth.rb
[ruby] OmniAuth.config.logger = Rails.logger
Rails.application.config.middleware.use OmniAuth::Builder do provider :facebook, ENV[‘FACEBOOK_APP_ID’], ENV[‘FACEBOOK_SECRET’] end [/ruby]
terminal
[bash] rails g model user provider uid name oauth_token oauth_expires_at:datetime rake db:migrate [/bash]
models/user.rb
[ruby] 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 [/ruby]
config/routes.rb
[ruby] match ‘auth/:provider/callback’, to: ‘sessions#create’ match ‘auth/failure’, to: redirect(’/’) match ‘signout’, to: ‘sessions#destroy’, as: ‘signout’ [/ruby]
sessions_controller.rb
[ruby] 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 [/ruby]
application_controller.rb
[ruby] private
def current_user @current_user ||= User.find(session[:user_id]) if session[:user_id] end helper_method :current_user [/ruby]
layouts/application.html.erb
[html]
[/html]app/assets/javascripts/facebook.js.coffee.erb
[javascript]
jQuery -> $(‘body’).prepend('
')$.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 [/javascript]