Created
February 25, 2014 07:48
-
-
Save jaemar/9204643 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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