Skip to content

Instantly share code, notes, and snippets.

@datapimp
Created July 1, 2011 21:34
Show Gist options
  • Select an option

  • Save datapimp/1059443 to your computer and use it in GitHub Desktop.

Select an option

Save datapimp/1059443 to your computer and use it in GitHub Desktop.
# add to user model
has_many :authentications, :dependent => :destroy
# config/routes.rb
match '/auth/:provider/callback' => 'authentications#create'
match '/auth/failure' => redirect('/users/sign_in')
# config/initializers/omniauth.rb
require 'openid/store/filesystem'
Rails.application.config.middleware.use OmniAuth::Builder do
if Rails.env == "development" || Rails.env == "test"
provider :facebook, 'YOURSHITHERE'
provider :twitter, 'YOURSHITHERE'
end
if Rails.env == "staging"
provider :facebook, 'YOURSHITHERE'
provider :twitter, 'YOURSHITHERE'
end
if Rails.env == "production"
provider :facebook, 'YOURSHITHERE'
provider :twitter, 'YOURSHITHERE'
end
end
# app/models/authentication.rb
class Authentication < ActiveRecord::Base
belongs_to :user
scope :facebook, where(:provider=>"facebook")
scope :twitter, where(:provider=>"twitter")
def provider_name
if provider == 'open_id'
"OpenID"
else
provider.titleize
end
end
end
#
# Table name: authentications
#
# id :integer(4) not null, primary key
# user_id :integer(4)
# provider :string(255)
# uid :string(255)
# created_at :datetime
# updated_at :datetime
# app/controllers/authentications_controller.rb
class AuthenticationsController < ApplicationController
def create
omniauth = request.env["omniauth.auth"]
if !omniauth
redirect_to new_user_registration_url
elsif authentication = Authentication.find_by_provider_and_uid(omniauth['provider'], omniauth['uid'])
# we already have an authentication
# sign the user in that it belongs to
flash[:notice] = "Signed in successfully."
sign_in_and_redirect(:user, authentication.user)
elsif current_user
# we are adding a 3rd party solution to an existing user
current_user.authentications.create!(:provider => omniauth['provider'], :uid => omniauth['uid'])
flash[:notice] = "Authentication successful."
redirect_to profile_url
else
@user = User.new
@user.apply_omniauth(omniauth)
if @user.save
flash[:notice] = "Signed in successfully."
sign_in_and_redirect(:user, @user)
else
session[:omniauth] = omniauth.except('extra')
redirect_to new_user_registration_url
end
end
end
def destroy
@authentication = current_user.authentications.find( params[:id] )
if @authentication.destroy
redirect_to profile_path, :notice => "You have disabled #{ @authentication.provider_name } authentication."
else
redirect_to profile_path, :notice => "You can not delete this authentication."
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment