Skip to content

Instantly share code, notes, and snippets.

@ck3g
Created December 12, 2012 09:14
Show Gist options
  • Save ck3g/4266304 to your computer and use it in GitHub Desktop.
Save ck3g/4266304 to your computer and use it in GitHub Desktop.
OmniAuth
class Authentication < ActiveRecord::Base
belongs_to :user
attr_accessible :provider, :uid, :user_id
validates :provider, :uid, presence: true
end
-# app/views/devise/registrations/new.html.haml
%h2.offset2= title t(:sign_up)
= simple_form_for(resource, as: resource_name, url: registration_path(resource_name), html: { class: "form-horizontal" }) do |f|
= f.error_notification
.form-inputs
= f.input :username, required: true, autofocus: true
= f.input :email, required: true
- if f.object.password_required?
= f.input :password, required: true
= f.input :password_confirmation, required: true
.control-group
.controls
.input
= f.button :submit, t(:do_sign_up), class: "width220"
.strikethrough_divider
.strike
%p= t(:or)
.control-group
.controls
.input
= render 'devise/shared/social_links'
= render "devise/shared/links"
class OmniauthCallbacksController < Devise::OmniauthCallbacksController
def all
user = User.from_omniauth(request.env["omniauth.auth"])
if user.persisted?
flash.notice = I18n.t("devise.sessions.signed_in")
sign_in_and_redirect user
else
session["devise.user_attributes"] = user.attributes
session["devise.user_auth_attributes"] = user.authentications.first.attributes
redirect_to new_user_registration_url
end
end
alias_method :twitter, :all
alias_method :facebook, :all
alias_method :vkontakte, :all
alias_method :google_oauth2, :all
end
class User < ActiveRecord::Base
has_many :authentications, dependent: :destroy
# ...
def self.from_omniauth(auth)
authentication = Authentication.where(provider: auth.provider, uid: auth.uid.to_s).first
if authentication.present?
user = authentication.user
else
user = self.find_or_create_by_email(auth.info.email)
user.authentications.build provider: auth.provider, uid: auth.uid.to_s
user.username = auth.info.nickname
user.firstname = auth.info.first_name
user.lastname = auth.info.last_name
end
user
end
def self.new_with_session(params, session)
if session["devise.user_attributes"]
new(session["devise.user_attributes"], without_protection: true) do |user|
user.attributes = params
user.authentications.build session["devise.user_auth_attributes"].slice("provider", "uid")
user.valid?
end
else
super
end
end
def password_required?
super && authentications.blank?
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment