我使用omniauth youtube和google oauth2 gems通过youtube登录。这一切都很好,但前提是用户已经用他们试图登录的帐户创建了一个youtube频道。
当用户在没有创建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'
更新我得到了这个工作的帮助,从一个小博客,地址,我将链接到。此解决方案将失败消息添加到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/failure url中的授权错误,并将其添加到我的routes.rb
match 'auth/failure', to: 'static_pages#youtube'
嗯…你可以为你的模型函数THT设置一个条件
if user = User.find_by_id(id)
user
else
//procceed with your code to link the account to utube