Skip to content

Instantly share code, notes, and snippets.

@tgoldenberg
Last active August 29, 2015 14:19
Show Gist options
  • Save tgoldenberg/b5b2bd6ea0495d610651 to your computer and use it in GitHub Desktop.
Save tgoldenberg/b5b2bd6ea0495d610651 to your computer and use it in GitHub Desktop.
##routes.rb
Rails.application.routes.draw do
resources :authentications
root to: "static_pages#home"
get 'static_pages/books'
devise_for :users, controllers: {omniauth_callbacks: "authentications", registrations: "registrations"}
end
#initializers/devise.rb
require "omniauth-facebook"
config.omniauth :facebook, 'my-app-key', 'my-secret-key', :scope => 'public_profile', :display => 'popup'
##user.rb
class User < ActiveRecord::Base
has_many :authentications
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable and :omniauthable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable, :omniauthable, omniauth_providers: [:facebook]
def self.from_omniauth(auth, signed_in_resource=nil)
user = User.where(provider: auth.provider, uid: auth.uid).first
if user
return user
else
registered_user = User.where(:email => auth.info.email).first
if registered_user
return registered_user
else
user = User.create(name:auth.extra.raw_info.name,
provider: auth.provider,
uid: auth.uid,
email: auth.info.email,
password: Devise.friendly_token[0,20]
)
end
end
end
end
##authentication.rb
class Authentication < ActiveRecord::Base
belongs_to :user
end
##omniauth_callbacks_controller.rb
class OmniauthCallbacksController < Devise::OmniauthCallbacksController
def facebook
@user = User.from_omniauth(request.env["omniauth.auth"], current_user)
if @user.persisted?
sign_in @user
redirect_to root_path
set_flash_message(:notice, :success, :kind => 'Facebook') if is_navigational_format?
else
session["devise.facebook_data"] = request.env["omniauth.auth"]
redirect_to root_path
end
end
def destroy
reset_session
redirect_to root_url, :notice => 'Signed out!'
end
def failure
reset_session
redirect_to root_url, :alert => 'Authentication error: #{params[:message]}'
end
end
##authentications_controller.rb
def facebook
raise omni = request.env["omniauth.auth"].to_yaml
end
##index.html.erb
<h1>StaticPages#books</h1>
<p>Find me in app/views/static_pages/books.html.erb</p>
<li> <%= link_to 'Sign in with FACEBOOK', user_omniauth_authorize_path(:facebook) %></li>
<html>
<head data-user="<%= current_user ? current_user.uid : nil %>">
<title>Client-side Flow Example</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.0/jquery.min.js" type="text/javascript"></script>
</head>
<body>
<div id="fb-root"></div>
<script type="text/javascript">
window.fbAsyncInit = function() {
FB.init({
appId : '370236446503733',
status : true, // check login status
cookie : true, // enable cookies to allow the server to access the session
xfbml : true // parse XFBML
});
};
(function(d) {
var js, id = 'facebook-jssdk'; if (d.getElementById(id)) {return;}
js = d.createElement('script'); js.id = id; js.async = true;
js.src = "//connect.facebook.net/en_US/all.js";
d.getElementsByTagName('head')[0].appendChild(js);
}(document));
$(function() {
$('a').click(function(e) {
e.preventDefault();
FB.login(function(response) {
if (response.authResponse) {
$('#connect').html('Connected! Hitting OmniAuth callback (GET /auth/facebook/callback)...');
// since we have cookies enabled, this request will allow omniauth to parse
// out the auth code from the signed request in the fbsr_XXX cookie
$.getJSON('/auth/facebook/callback', function(json) {
$('#connect').html('Connected! Callback complete.');
$('#results').html(JSON.stringify(json));
});
}
}, { scope: 'email,read_stream', state: 'abc123' });
});
});
</script>
<p id="connect">
<a href="#">Connect to FB!</a>
</p>
<p id="results" />
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment