2013-01-06 74 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

相關問題