1

就这么简单,我想使用omniauth和devise在我的rails应用程序中链接到现有用户帐户他的facebook个人资料(优先考虑最初注册的电子邮件)。

我已阅读内容,但对我没有多大帮助。

我目前的结构是这样的

4

1 回答 1

3

下面是我如何实现这一点的示例。如果用户已经登录,那么我调用一个将他们的帐户与 Facebook 关联的方法。否则,我将执行Devise-Omniauth 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
于 2016-05-10T19:29:18.550 回答