Skip to content

Instantly share code, notes, and snippets.

@wesmaldonado
Created November 29, 2010 22:43
Show Gist options
  • Save wesmaldonado/720787 to your computer and use it in GitHub Desktop.
Save wesmaldonado/720787 to your computer and use it in GitHub Desktop.
class User < ActiveRecord::Base
# Include default devise modules. Others available are:
# :token_authenticatable, :confirmable, :lockable and :timeoutable
devise :database_authenticatable , :registerable, :recoverable, :rememberable, :trackable, :validatable
devise :omniauthable#, :omniauth_providers => [:facebook]
devise :encryptable, :encryptor => :custom_encryptor
# Devise: Setup accessible (or protected) attributes for your model
attr_accessible :email, :password, :password_confirmation, :remember_me
# Called by user/omniauth_devise_controller#facebook to lookup an existing user for facebook.
#
# @omniauth [Hash] Omniauth provider hash @see https://github.com/intridea/omniauth/wiki/Auth-Hash-Schema
# @user [User] The current logged in user.
def self.find_for_facebook_oauth(omniauth, user)
user = User.find_or_initialize_by_fb_uid(omniauth["uid"])
end
# Called via devise when new user registration flow begins.
#
# @params [Hash] Standard params via rails.
# @session [Hash] Session containing Oauth hash from devise containing keys for devise.{provider}_data. e.g. "devise.facebook_data".
def self.new_with_session(params, session)
super.tap do |user|
if data = session["devise.facebook_data"]
user.email = data["extra"]["user_hash"]["email"]
user.fb_uid = data["uid"].to_i
user.name = data["extra"]["user_hash"]["name"]
end
end
end
# Overwritten from Devise to turn off password validations for Oauth'd users.
def password_required?
return false if oauth?
# standard validation requirements from Devise
!persisted? || !password.nil? || !password_confirmation.nil?
end
def oauth?
(!fb_uid.blank?)
end
end
class UsersDeviseController < Devise::RegistrationsController
def facebook
@user = User.find_for_facebook_oauth(env["omniauth.auth"], current_user)
if @user.persisted?
flash[:notice] = I18n.t "devise.omniauth_callbacks.success", :kind => "Facebook"
sign_in_and_redirect @user, :event => :authentication
else
session["devise.facebook_data"] = env["omniauth.auth"]
# No existing user create them and redirect to home page.
data = env["omniauth.auth"]
user = User.new
user.email = data["extra"]["user_hash"]["email"]
user.fb_uid = data["uid"].to_i
user.name = data["extra"]["user_hash"]["name"]
user.save!
set_flash_message :notice, :signed_up
sign_in_and_redirect user, :event => :signed_up
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment