, , has_many . Identity ( omniauth):
class Identity < ActiveRecord::Base
belongs_to :user
attr_accessible :provider, :uid,
:description, :email, :first_name, :image,
:last_name, :location, :name, :nickname,
:phone, :raw_info, :urls
validates_presence_of :provider, :uid
validates_uniqueness_of :uid, scope: :provider
def self.find_with_omniauth(auth)
find_by_provider_and_uid(auth['provider'], auth['uid'])
end
def self.create_with_omniauth(auth)
create(provider: auth['provider'],
uid: auth['uid'],
name: auth['info']['name'],
email: auth['info']['email'],
nickname: auth['info']['nickname'],
first_name: auth['info']['first_name'],
last_name: auth['info']['last_name'],
location: auth['info']['location'],
description: auth['info']['description'],
image: auth['info']['image'],
phone: auth['info']['phone'],
urls: auth['info']['urls'].to_json,
raw_info: auth['extra']['raw_info'].to_json
)
end
end
, , User :
class User < ActiveRecord::Base
...
has_many :identities, dependent: :destroy
...
, omniauth . , (), - :
class SessionsController < ApplicationController
def create
auth = request.env['omniauth.auth']
origin = request.env['omniauth.origin']
destination = origin.blank? ? root_path : origin
@identity = Identity.find_with_omniauth(auth)
@identity = Identity.create_with_omniauth(auth) if @identity.nil?
if signed_in?
if @identity.user == current_user
redirect_to destination, notice: "Already logged in and linked"
else
@old_user = @identity.user
if @old_user
current_user.posts << @old_user.posts
current_user.galleries << @old_user.galleries
current_user.favorites << @old_user.favorites
end
@identity.user = current_user
@identity.save()
@old_user.destroy if @old_user && @old_user.identities.blank?
redirect_to destination, notice: "Account was successfully linked"
end
else
if @identity.user.present?
self.current_user = @identity.user
redirect_to destination
else
user = User.create_with_omniauth(auth['info'])
@identity.user = user
@identity.save()
self.current_user = @identity.user
redirect_to destination, notice: "Registration successful"
end
end
end
def destroy
self.current_user = nil
redirect_to root_url, notice: "Signed out successfully"
end
def omniauth_failure
origin = request.env['omniauth.origin']
destination = origin.blank? ? root_path : origin
redirect_to destination, alert: "Connection failed"
end
end
, , , . . https://github.com/intridea/omniauth/wiki/Managing-Multiple-Providers .