2

我正在使用omniauth,Rails并试图让twitter、facebook和google连接起来进行身份验证,但一直遇到这个错误:

PG::Error: ERROR:  duplicate key value violates unique constraint "index_users_on_email"
DETAIL:  Key (email)=() already exists.

这是我的身份验证控制器:

class AuthorizationsController < ApplicationController


      def create
        authentication = Authorization.find_by_provider_and_uid(auth['provider'], auth['uid'])

        if authentication
          flash[:notice] = "Signed In Successfully"
          sign_in authentication.user, event: :authentication
          redirect_to root_path
        else
          athlete = Athlete.new
          athlete.apply_omniauth(auth)

          debugger

          if athlete.save(validate: false)
            flash[:notice] = "Account created and signed in successfully"
            sign_in athlete, event: :authentication
            redirect_to finalize_profile_path
          else
            flash[:error] = "An error has occurred. Please try again."
            redirect_to root_path
          end
        end
      end

      def failure
        render json: params.to_json
      end

      private

        def auth
          request.env["omniauth.auth"]
        end

        def resource(user_type)
          user_type.downcase.to_sym
        end

    end

我认为正在发生的事情是,当创建运动员时,它正在创建一个带有空白电子邮件地址并且唯一密钥失败......我该如何解决这个问题?我想我知道如何为 Google 集成解决此问题,但由于 Twitter 不返回电子邮件,因此此问题不会自行解决

4

1 回答 1

1

这就是我能够让它工作的方式:

class AuthorizationsController < ApplicationController

  def create
    authentication = Authorization.find_by_provider_and_uid(auth['provider'], auth['uid'])

    if authentication
      flash[:notice] = "Signed In Successfully"
      sign_in authentication.user, event: :authentication
      redirect_to root_path
    else
      athlete = Athlete.new(email: generate_auth_email(params[:provider]) )
      athlete.apply_omniauth(auth)

      debugger

      if athlete.save(validate: false)
        flash[:notice] = "Account created and signed in successfully"
        sign_in athlete, event: :authentication
        redirect_to finalize_profile_path
      else
        flash[:error] = "An error has occurred. Please try again."
        redirect_to root_path
      end
    end
  end

  def failure
    render json: params.to_json
  end

  private

    def auth
      request.env["omniauth.auth"]
    end

    def resource(user_type)
      user_type.downcase.to_sym
    end

    def generate_auth_email(provider)
      return auth.info.try(:email) unless provider == "twitter"
      return "#{auth.uid}@twitter.com" if provider == "twitter"
    end

end

我使用 twitter.com 作为域的 twitter uid 创建了一封电子邮件,因为 twitter 不返回电子邮件地址

希望这对将来的人有所帮助

于 2013-07-10T20:15:38.787 回答