首页 > 解决方案 > 使用 Rails Rails 实现 Linkedin Oauth 注册

问题描述

这是我处理回调的控制器:

class OauthController < ApplicationController
  def callback
    begin
      oauth = OauthService.new(request.env['omniauth.auth'])
      if oauth_account = oauth.create_oauth_account!
          @user = User.from_omniauth(oauth)
          sign_in_as(@user)
          redirect_to root
      else
        redirect_to new_user_registration_path
      end
    rescue => e
      flash[:alert] = "There was an error while trying to authenticate your account."
      redirect_to new_user_registration_path
    end
  end

  def failure
    flash[:alert] = "There was an error while trying to authenticate your account."
    redirect_to new_user_registration_path
  end

  protected

  private
  def user_params
    params.permit(:email, :password)
  end
end

以及它运行的服务:

class OauthService
  attr_reader :auth_hash

  def initialize(auth_hash)
    @auth_hash = auth_hash
  end

  def create_oauth_account!
    unless oauth_account = OauthAccount.where(uid: @auth_hash[:uid]).first
      oauth_account = OauthAccount.create!(oauth_account_params)
    end
  end

private

  def oauth_account_params
    { uid: @auth_hash[:uid],
      provider: @auth_hash[:provider],
      image_url: @auth_hash[:info][:image],
      profile_url: @auth_hash[:info][:urls][:public_profile],
      raw_data: @auth_hash[:extra][:raw_info].to_json }
  end

end

我似乎无法弄清楚为什么浏览器设法重定向到linkedin,在那里工作并返回只转发到我的sign_up_page。

一定有什么。错误的if oauth_account = oath.create_oauth_account!or 之前的行。

我正在关注一些教程,这是我从他们中的任何一个使用 Omni Oauth 2 对 LinkedIn 进行身份验证所获得的。

如果我将第二个 redirect_to new_user_registration_path 更改为 redirect_to root,它会显示 .from_omniauth(oauth) 错误,没有定义方法。

但在我的 user.rb 中:

def from_omniauth(auth_hash)
    user = find_or_create_by(uid: auth_hash['uid'], provider: auth_hash['provider'])
    user.user_id = auth_hash['uid']
    user.username = auth_hash['info']['name']
    user.location = get_social_location_for user.provider, auth_hash['info']['location']
    user.image_url = auth_hash['info']['image']
    user.url = get_social_url_for user.provider, auth_hash['info']['urls']
    user.save!

    filename =user.user_id + user.username
    File.open(filename, "w+") do |f|
      f.write(oauth['extra']['raw_info'])
    end
    user
  end

您可以看到它已正确定义,并且有一个额外的尝试找出 order 或额外的 raw_info json 块。

标签: ruby-on-railslinkedin

解决方案


推荐阅读