Facebook Omniauth + Carrierwave个人资料图片

时间:2014-04-06 20:53:09

标签: ruby-on-rails facebook omniauth carrierwave

我有一个应用程序,用户Devise + Omniauth允许用户通过Facebook注册。我还使用Carrierwave允许用户上传他们自己的个人资料图像并处理从Facebook请求的图像。因此,我在控制器和用户模型中具有以下功能:

user.rb

def self.find_for_facebook_oauth( data, signed_in_resource=nil)
user = User.where(:email => data.info.email).first
unless user
  params =
    {  
      :user =>
      {
        :username => data.uid,
        :email => data.info.email,
        :password => Devise.friendly_token[0,20],
        :user_profile_attributes => 
          {
            :first_name => data.info.first_name,
            :last_name => data.info.last_name,
            :remote_image_url => data.info.image
          },
        :user_auths_attributes =>
        [{
          :uid => data.uid,
          :provider => data.provider
        }]
      }
    }
    user = User.create!(params[:user])
end
return user
end

omniauth_callbacks_controller.rb

def facebook
# You need to implement the method below in your model (e.g. app/models/user.rb)
@user = User.find_for_facebook_oauth(request.env["omniauth.auth"])

if @user.persisted?
  sign_in_and_redirect @user, :event => :authentication #this will throw if @user is not activated
  set_flash_message(:notice, :success, :kind => "Facebook") if is_navigational_format?
else
  session["devise.facebook_data"] = request.env["omniauth.auth"]
  redirect_to new_user_registration_url
end
end

不幸的是,我一直遇到这个错误:

ActiveRecord::RecordInvalid (Validation failed: User profile image could not download file: redirection forbidden: http://graph.facebook.com/813865346/picture?type=square -> https://fbcdn-profile-a.akamaihd.net/hprofile-ak-prn2/t5.0-1/1118622_813865346_1465272585_q.jpg):
app/models/user.rb:68:in `find_for_facebook_oauth'
app/controllers/users/omniauth_callbacks_controller.rb:4:in `facebook'

第68行是user = User.create!(params[:user])

记录params[:user]提供以下值:

Params: {:username=>"*", :email=>"*", :password=>"iePVLt7XEWk4YwPjja6n", :user_profile_attributes=>{:first_name=>"*", :last_name=>"*", :remote_image_url=>"http://graph.facebook.com/*/picture?type=square"}, :user_auths_attributes=>{:uid=>"*", :provider=>"facebook"}}

我希望得到一些帮助来解决这个错误。

3 个答案:

答案 0 :(得分:28)

我遇到了同样的问题。问题似乎是http重定向到https。所以我使用gsub替换它们,如下所示:

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

答案 1 :(得分:14)

omniauth-facebook策略可以选择将图片网址更改为安全的 https 网址。

  

secure_image_url:设置为true以使用https作为头像图片网址   在auth哈希中返回。

例如,带有安全URL的图片将以devise.rb或omniauth.rb的方式请求:

provider :facebook, 'secrets', 'secrets', :secure_image_url => true

https://github.com/mkdynamic/omniauth-facebook#configuring

答案 2 :(得分:0)

我同意回答 Sandeep Laxman ,问题是http必须替换为https,因为来自Facebook的安全图片,我们可以使用gsub# ref ruby-doc

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

或使用sub

user.remote_avatar_url = auth.info.image.sub('http:','https:')