这很简单,我想在我的rails应用程序中使用omniauth和devise链接到他现有的用户帐户他的facebook个人资料(优先考虑最初注册的电子邮件)。
我已阅读this,但对我没什么帮助。
我目前的结构是like this one。
答案 0 :(得分:2)
以下是我如何实现此功能的示例。如果用户已登录,则我会调用将其帐户与Facebook相关联的方法。否则,我将执行Devise-Omniauth wiki page中列出的相同步骤。
# 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