Devise + Omniauth + Carrierwave不保存facebook / github个人资料图片

时间:2017-04-05 11:08:40

标签: ruby-on-rails ruby devise carrierwave omniauth

之前我只使用Omni auth + devise让用户注册。一切都很好。后来我决定使用简单的注册形式的设计。我配置它,它也工作正常,但问题出现在用户想要使用Omni auth注册时。即使facebook / Github返回到个人资料图片的链接,头像总是设置为零。我试过这个solution,但仍然无法正常工作,我知道了carrierwave远程位置上传方法。我用于Omni auth的宝石是omniauth-facebook和omniauth-github。

(1)

$config['permitted_uri_chars'] = 'a-z 0-9~%.:_\-@';

代码:

User.rb

(2)

class User < ApplicationRecord
  include Storext.model
  devise :database_authenticatable, :registerable, :omniauthable,
     :recoverable, :rememberable, :trackable, :validatable
  validates :first_name, :last_name, :email, :experience_level,
        :goal_level, :theoretical_learner_level, presence: true
  mount_uploader :avatar, AvatarUploader

  # Override devise method for Oauth
  def self.new_with_session(params, session)
    if session['devise.user_attributes']
      new(session['devise.user_attributes'].merge(session[:user_attributes])) do |user|
        user.attributes = params
        user.valid?
      end
    else
      super
    end
  end

  def self.from_omniauth(auth)
    where(auth.slice(:provider, :uid).to_hash).first_or_create do |user|
      OauthUserGenerator.new(user: user, auth: auth).generate
    end
  end

  # If sign in through Oauth, don't require password
  def password_required?
    super && provider.blank?
  end

  # Don't require update with password if Oauth
  def update_with_password(params, *options)
    if encrypted_password.blank?
      update_attributes(params, *options)
    else
      super
    end
  end
end

代码:

oauth_user_generator.rb

(3)

class OauthUserGenerator
  def initialize(user:, auth:)
    @user = user
    @auth = auth
  end

  def generate
    @user.provider = @auth.provider
    @user.uid = @auth.uid
    @user.email = @auth.info.email
    @user.password = Devise.friendly_token[0, 20]
    @user.first_name = @auth.info.name.split[0]
    @user.last_name = @auth.info.name.split[1]
    @user.remote_avatar_url = @auth.info.image
  end
end

代码:

omniauth_callbacks_controller.rb

谢谢。

1 个答案:

答案 0 :(得分:1)

前一段时间我遇到过类似的问题。 显然,carrierwave不允许remote_url从协议重定向到另一个协议。您使用auth.info.image获取的网址是http网址,会重定向到https网址。因此,在OauthUserGenerator课程中,使用generate方法。尝试执行以下操作:

@user.remote_avatar_url = @auth.info.image.gsub('http', 'https')

这样重定向将来自https -> https。这对我有用。希望你能解决同样的问题。