这么简单,我想链接到一个现有的用户帐户他的facebook个人资料(优先考虑最初注册的电子邮件)在我的rails应用程序,使用omniauth和设计。
我读过这本书,但对我没有多大帮助。
我当前的结构是这样的
下面是我如何实现它的一个例子。如果用户已经登录,那么我调用一个方法将他们的帐户与Facebook链接起来。否则,我将执行与"设计-全能"wiki页面中概述的相同过程。
# users/omniauth_callbacks_controller.rb
def facebook
if user_signed_in?
if current_user.link_account_from_omniauth(request.env["omniauth.auth"])
flash[:notice] = "Account successfully linked"
redirect_to user_path(current_user) and return
end
end
@user = User.from_omniauth(request.env["omniauth.auth"])
if @user.persisted?
sign_in_and_redirect @user, event: :authentication #this will throw if @user is not activated
set_flash_message(:notice, :success, kind: "Facebook") if is_navigational_format?
else
session["devise.facebook_data"] = request.env["omniauth.auth"]
redirect_to new_user_registration_url
end
end
# app/models/user.rb
class << self
def from_omniauth(auth)
new_user = where(provider: auth.provider, uid: auth.uid).first_or_initialize
new_user.email = auth.info.email
new_user.password = Devise.friendly_token[0,20]
new_user.skip_confirmation!
new_user.save
new_user
end
end
def link_account_from_omniauth(auth)
self.provider = auth.provider
self.uid = auth.uid
self.save
end