2013-01-08 18 views
0

我使用omniauth youtube和谷歌oauth2寶石通過youtube登錄。這一切都可以正常工作,但條件是用戶已經使用他們嘗試登錄的帳戶創建了YouTube頻道。Ominiauth Youtube登錄 - 重定向創建YouTube頻道401 nolinkedoutubeaccount

當用戶試圖登錄和授權沒有YouTube頻道創造了它的錯誤了以下消息:

OAuth2::Error 

    <HTML> 
    <HEAD> 
    <TITLE>NoLinkedYouTubeAccount</TITLE> 
    </HEAD> 
    <BODY BGCOLOR="#FFFFFF" TEXT="#000000"> 
    <H1>NoLinkedYouTubeAccount</H1> 
    <H2>Error 401</H2> 
    </BODY> 
    </HTML> 

我怎麼能處理此錯誤,使用戶無論是發送到他們的YouTube帳戶他們可以在哪裏創建自己的YouTube頻道,然後通過有效的登錄憑據將其重定向回網站,或者發送回頁面,其中提供有關如何創建YouTube頻道並再次嘗試的說明?

我的代碼如下:

user.rb

def self.from_omniauth(auth) 
    where(auth.slice(:provider, :uid)).first_or_initialize.tap do |user| 
     user.provider = auth.provider 
     user.uid = auth.uid 
     user.name = auth.info.name 
     user.email = auth.info.email 
     user.oauth_token = auth.credentials.token 
     user.oauth_expires_at = Time.at(auth.credentials.expires_at) 
     user.picture = auth.info.image 
     user.save! 
     end 
    end 

session_controller:

def create 
     user = User.from_omniauth(env["omniauth.auth"]) 
     session[:user_id] = user.id 
     redirect_to root_path, notice: "Signed in" 
    end 

    def destroy 
     session[:user_id] = nil 
     redirect_to root_path, notice: "Signed out" 
    end 

    def failure 
    end 

日誌形式

<% if current_user %> 
     Logged in as <b><%= current_user.name %></b> 
      <%= image_tag current_user.picture %><br> 
      <%= link_to "Sign out", signout_path %> 
     <% else %> 
      Sign in with <%= link_to image_tag('youtube.png'), "/auth/youtube" %> 
     <% end %> 

路線

match 'auth/youtube/callback', to: 'sessions#create' 
    match 'auth/failure', to: redirect('/') 
    match 'signout', to: 'sessions#destroy', as: 'signout' 

UPDATE 我得到這個與幫助工作從一個小博客,我將鏈接到地址。此解決方案向auth/failure路由的url添加失敗消息,並使用說明正確重定向到youtube鏈接頁面。

我增加了以下內容omniauth.rb

OmniAuth.config.on_failure do |env| 
    exception = env['omniauth.error'] 
    error_type = env['omniauth.error.type'] 
    strategy = env['omniauth.error.strategy'] 

    Rails.logger.error("OmniAuth Error (#{error_type}): #{exception.inspect}") 
    #ErrorNotifier.exception(exception, :strategy => strategy.inspect, :error_type => error_type) 

    new_path = "#{env['SCRIPT_NAME']}#{OmniAuth.config.path_prefix}/failure?message=#{error_type}" 

    [301, {'Location' => new_path, 'Content-Type'=> 'text/html'}, []] 
end 

其中顯示了授權錯誤的AUTH /失敗URL,並將此向我​​的routes.rb

match 'auth/failure', to: 'static_pages#youtube' 

回答

1

嗯......你們可以設置一個條件,以您的型號功能thr

if user = User.find_by_id(id) 
    user 
else 
    //procceed with your code to link the account to utube 
+0

嗨Nich,這個代碼應該在控制器?所以如果用戶保存返回到主頁,否則去這個說明頁? – dodgerogers747

+1

嗯,你可以把它放在模型中的一個函數中,就像你實際做的一樣,只需在你的邏輯中放置一個條件,然後在控制器中調用這個函數 – Nich