Search code examples
facebookhttp-redirectruby-on-rails-3.2open-uri

Rails 3.2.17 Runtime Error Redirection Forbidden facebook


I have this code I use to get avatars from Facebook...

if auth.info.image.present?
      user.update_attribute(:avatar, URI.parse(auth.info.image))
end

When I try to load the code now I get this error:

A RuntimeError occurred in authentications#create:

  redirection forbidden: http://graph.facebook.com/672086173/picture?type=square -> https://fbcdn-profile-a.akamaihd.net/hprofile-ak-prn2/t5.0-1/1086349_672086173_156380036_q.jpg
  /home/ubuntu/.rvm/rubies/ruby-2.1.0/lib/ruby/2.1.0/open-uri.rb:223:in `open_loop'

I understand that this is a problem with Open-URI not allowing HTTP to HTTPS redirections... and I understand that this can be solved with Open-Uri-Redirections plugin https://github.com/jaimeiniesta/open_uri_redirections

But there are two things I don't understand:

  1. This was working just fine YESTERDAY... and I've changed nothing. So why, suddenly, can Paperclip not get the correct URL?
  2. The instructions for Open-Uri-redirections give the following example:

    open('http://github.com', :allow_redirections => :safe)

How would I reconcile this with my code above?


Solution

  • Update

    If you are using omniauth-facebook please follow deivid's answer.

    Another way to solve this issue is to replace http with https. In that way it will redirect from https to https and you won't get a redirection forbidden error.

    Example

    > url = auth.info.image
    => "http://graph.facebook.com/672086173/picture?type=square"
    
    > avatar_url =url.gsub("­http","htt­ps")
    => "https://graph.facebook.com/672086173/picture?type=square"
    

    I had the exact same problem. I solve it with following steps

    First in your gemfile add

    gem 'open_uri_redirections'
    

    and run bundle install to install the gem

    And then in your model

    private
    
      def process_uri(uri)
        require 'open-uri'
        require 'open_uri_redirections'
        open(uri, :allow_redirections => :safe) do |r|
          r.base_uri.to_s
        end
      end
    

    Now process the avatar url with the method like

    if auth.info.image.present?
       avatar_url = process_uri(auth.info.image)
       user.update_attribute(:avatar, URI.parse(avatar_url))
    end
    

    Hope this helps anyone else that may be having this issue.