2013-01-06 76 views
1

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

我已阅读this但对我没什么帮助。

我目前的结构是like this one

+0

请仔细看看刚才链接的页面。在Google Oauth 2示例中,'find_for_google_oauth2'方法完全符合您的需求。它首先从'auth.info.email'哈希中获取电子邮件,然后使用'User.where(:email => email).first'搜索具有该电子邮件的用户。 – Ashitaka

+0

最简单的方法是让用户通过他现有的帐户登录,然后让他在Facebook上登录。在Facebook上登录后,您必须将Facebook用户标识添加到当前登录的用户。如果你被困住了,试着解决它并回来寻求帮助。 – Fa11enAngel

回答

1

下面是我如何实现这个的一个例子。如果用户已经登录,那么我会调用一个将他们的帐户与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 
+0

可能会添加到您的link_account_from_omniauth功能中: self.oauth_access_token = auth.credentials.token – MingMan

相关问题