Skip to content

Instantly share code, notes, and snippets.

@jaemar
Created February 25, 2014 07:48
Show Gist options
  • Save jaemar/9204643 to your computer and use it in GitHub Desktop.
Save jaemar/9204643 to your computer and use it in GitHub Desktop.
# config/routes.rb
devise_for :users, controllers: { omniauth_callbacks: 'omniauth_callbacks' }
# config/initializer/devise.rb
Devise.setup do |config|
if Rails.env.production?
fb_key = "fb_key"
fb_secret = "fb_secret"
else
fb_key = "fb_key"
fb_secret = "fb_secret"
end
config.omniauth :facebook, fb_key, fb_secret, { scope: "email, user_birthday" }
end
# db/migrate
class DeviseCreateUsers < ActiveRecord::Migration
def change
create_table(:users) do |t|
#...
t.string :provider
t.string :uid
t.string :access_token
end
end
end
# app/controllers/omniauth_callbacks_controller.rb
class OmniauthCallbacksController < Devise::OmniauthCallbacksController
def facebook
@user = User.find_for_facebook_oauth(request.env['omniauth.auth'], current_user)
if @user.valid?
sign_in @user
else
redirect_to sign_in_path(invalid_token: 1)
end
if user_signed_in?
flash[:notice] = "Signed in successfully."
redirect_to '/'
else
redirect_to sign_in_path(invalid_token: 1)
end
end
end
# app/model/user.rb
class User < ActiveRecord::Base
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable and :omniauthable
devise :database_authenticatable, :registerable,
:recoverable, :trackable, :omniauthable
def self.find_for_facebook_oauth(auth, signed_in_resources = nil)
user = User.where(provider: auth.provider, uid: auth.uid).first
unless user
user = User.new(provider: auth.provider,
uid: auth.uid,
email: auth.info.email,
password: Devise.friendly_token[0,20],
#avatar: auth.info.image,
access_token: auth.credentials.token
)
user.save
end
user
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment