Image invalid on facebook/twitter user image uploading to S3 - amazon-s3

I'm trying to upload to amazon s3 an existing image on facebook or twitter from an user that has just signed up in my application, but some validation don't let me save the user object, throws: Image is invalid. I thought that was for my extension_white_list but I removed it and it's keeping saying Image is invalid.
This it's not an error, it's just a message from a validation on carrierwave I think, even if the image url string is correct.
AvatarUploader
# encoding: utf-8
class AvatarUploader < CarrierWave::Uploader::Base
include CarrierWaveDirect::Uploader
include CarrierWave::RMagick
# Include the Sprockets helpers for Rails 3.1+ asset pipeline compatibility:
include Sprockets::Helpers::RailsHelper
include Sprockets::Helpers::IsolatedHelper
include CarrierWave::MimeTypes
process :set_content_type
def store_dir
"avatar/#{model.id}"
end
version :thumb do
process resize_to_fill: [50, 50]
end
# def extension_white_list
# %w(jpg jpeg gif png bmp)
# end
end
Creating user:
...
new_user = User.create( :name => auth['info']['name'],
:email => User.email_from_auth(auth) )
auth_image_url = Authentication.larger_image(auth) # a string of user image url from social network authentication data. ie: http://a0.twimg.com/profile_images/1255111511/skyline.jpg
unless auth_image_url.blank?
new_user.remote_image_url = auth_image_url
new_user.save
end
...

Fixed! The error has nothing to do with carrierwave, just the fact that the object does not exist on database in the moment where the image is upload, first I save the new user and then:
after_create :upload_image_from_auth
def upload_image_from_auth
auth = self.authentications.first
unless auth.nil?
self.remote_image_url = auth.larger_image
self.save
end
end

Related

ArgumentError (missing required option :name)

I have deployed to Heroku a basic gallery website but the image upload functionality in not working, it gives me 500 Internal Server Error, it all works on the local server. I am using AWS S3 bucket for storage.
My Uploader file
class PortfolioUploader < CarrierWave::Uploader::Base
storage :aws
def store_dir
"uploads/#{model.class.to_s.underscore}/#{mounted_as}/#{model.id}"
end
# Provide a default URL as a default if there hasn't been a file uploaded:
# def default_url(*args)
# # For Rails 3.1+ asset pipeline compatibility:
# # ActionController::Base.helpers.asset_path("fallback/" + [version_name, "default.png"].compact.join('_'))
#
# "/images/fallback/" + [version_name, "default.png"].compact.join('_')
# end
def extension_whitelist
%w(jpg jpeg gif png)
end
end
controller file create method
def create
#portfolio_item = Portfolio.new(portfolio_params)
if #portfolio_item.save
redirect_to portfolios_path
else
render :new
end
end
---------------------------------------------------------------------------------------------------------carrierwave.rb file
CarrierWave.configure do |config|
config.storage = :aws
config.aws_bucket = ENV.fetch('S3_BUCKET_NAME') # for AWS-side bucket access permissions config, see section below
config.aws_acl = 'private'
config.aws_authenticated_url_expiration = 60 * 60 * 24 * 7
config.aws_attributes = -> { {
expires: 1.week.from_now.httpdate,
cache_control: 'max-age=604800'
} }
config.aws_credentials = {
access_key_id: ENV.fetch('AWS_ACCESS_KEY_ID'),
secret_access_key: ENV.fetch('AWS_SECRET_ACCESS_KEY'),
region: ENV.fetch('AWS_REGION'), # Required
stub_responses: Rails.env.test? # Optional, avoid hitting S3 actual during tests
}
end
2020-11-05T10:35:32.467646+00:00 app[web.1]: F, [2020-11-05T10:35:32.467563 #4] FATAL -- : [421e9f92-f540-4552-aa31-be18534786e4]
2020-11-05T10:35:32.467647+00:00 app[web.1]: [421e9f92-f540-4552-aa31-be18534786e4] ArgumentError (missing required option :name):
2020-11-05T10:35:32.467648+00:00 app[web.1]: [421e9f92-f540-4552-aa31-be18534786e4]
2020-11-05T10:35:32.467648+00:00 app[web.1]: [421e9f92-f540-4552-aa31-be18534786e4] app/controllers/portfolios_controller.rb:26:in `create'```
It seems like when you call portfolio_params you are not passing in name which is a required field to create a portfolio.
Can you share a params example when entering the create method as well as your portfolio_params method from the controller?

issues setting up S3 with carrierwave and fog in Heroku

I've been trying to upload files to Amazon S3 through a form, but I'm getting some errors I do not know how to fix.
Does somebody have experience this type of errors?
Heroku log errors:
response => #<Excon::Response:0x00000007294a30 #body="<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<Error><Code>SignatureDoesNotMatch</Code><Message>The request signature we calculated does not match the signature you provided. Check your key and signing method.</Message>
Excon::Errors::Forbidden (Expected(200) <=> Actual(403 Forbidden)
config/initializers/carrierwage.rb
CarrierWave.configure do |config|
config.fog_credentials = {
:provider => "AWS",
:aws_access_key_id => ENV['AWS_ACCESS_KEY_ID'],
:aws_secret_access_key => ENV['AWS_SECRET_ACCESS_KEY']
}
config.fog_directory = ENV['AWS_S3_BUCKET']
end
app/uploaders/file_uploader.rb
storage :fog
include CarrierWave::MimeTypes
process :set_content_type
def extension_white_list
%w(jpg jpeg gif png pdf)
end
# Override the directory where uploaded files will be stored.
# This is a sensible default for uploaders that are meant to be mounted:
def store_dir
"uploads/#{model.class.to_s.underscore}/#{mounted_as}/#{model.id}"
end
I have set
the env. variables on Heroku.
I'm using the US standard for the bucket.

rails carrierwave / s3 signature doesn't match. Wrong private key

I'm trying to get carrierwave working with S3, and I am getting a signature doesn't match error. The weird thing is that it doesn't look like carrierwave is sending the right secret key. In the error, the post is given as:
"Authorization"=>"AWS AKIAIOLWQKSJFH6E3I5Q:vKgyAw2z4c8zzqGWoxLUbw7I5oI="
Which I assume is supposed to be my publickey:privatekey. The thing is that vKgyAw2z4c8zzqGWoxLUbw7I5oI= is not the private key I have stored in fog.rb. Is that right?
Any help is appreciated.
Request/Response:
request => {:chunk_size=>1048576, :connect_timeout=>60, :headers=>{"Content-Length"=>1557, "Content-Type"=>"image/
gif", "x-amz-acl"=>"public-read", "Date"=>"Wed, 24 Oct 2012 12:45:17 +0000", "Authorization"=>"AWS AKIAIOLWQKSJFH6E3
I5Q:vKgyAw2z4c8zzqGWoxLUbw7I5oI=", "Host"=>"s3.amazonaws.com:443"}, :instrumentor_name=>"excon", :mock=>false, :nonb
lock=>true, :read_timeout=>60, :retry_limit=>4, :ssl_ca_file=>"/home/tim/.rvm/gems/ruby-1.9.3-p194/gems/excon-0.16.5
/data/cacert.pem", :ssl_verify_peer=>true, :write_timeout=>60, :host=>"myeasybnb.s3.amazonaws.com", :host_port=>"s3.
amazonaws.com:443", :path=>"/images%2Fb1bb6639-dc08-4981-9a9b-7175093ac970.gif", :port=>"443", :query=>nil, :scheme=
>"https", :body=>#<File:/home/tim/Dropbox/myeasybnb/tmp/uploads/20121024-0845-20225-1170/240x240.gif>, :expects=>200
, :idempotent=>true, :method=>"PUT"}
response => #<Excon::Response:0xa7a1098 #body="<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<Error><Code>SignatureD
oesNotMatch</Code><Message>The request signature we calculated does not match the signature you provided. Check your
key and signing method.</Message>
fog.rb:
CarrierWave.configure do |config|
config.fog_credentials = {
:provider => 'AWS', # required
:aws_access_key_id => 'AKIAIOLWQKSJFH6E3I5Q', # required
:aws_secret_access_key => '[my secret key]' # required
}
config.fog_directory = 'myeasybnb' # required
config.fog_public = true # optional, defaults to true
end
Uploader.rb:
# encoding: utf-8
class PhotoUploader < CarrierWave::Uploader::Base
# Include RMagick or MiniMagick support:
# include CarrierWave::RMagick
include CarrierWave::MiniMagick
# Include the Sprockets helpers for Rails 3.1+ asset pipeline compatibility:
include Sprockets::Helpers::RailsHelper
include Sprockets::Helpers::IsolatedHelper
# Choose what kind of storage to use for this uploader:
# storage :file
storage :fog
# Override the directory where uploaded files will be stored.
# This is a sensible default for uploaders that are meant to be mounted:
def store_dir
"images"
end
# Provide a default URL as a default if there hasn't been a file uploaded:
class MyUploader < CarrierWave::Uploader::Base
def default_url
asset_path("seeds/" + [version_name, "default.png"].compact.join('_'))
end
end
# Process files as they are uploaded:
# process :scale => [200, 300]
#
# Create different versions of your uploaded files:
process :convert => 'jpg'
version :sidecarousel, :if => :is_side_carousel? do
process :resize_to_fit => [2000,1000]
end
version :thumbnail, :if => :is_thumbnail? do
process :resize_to_fill => [240,240]
end
version :linetext, :if => :is_line? do
process :resize_to_fill => [400,200]
end
version :carousel, :if => :is_carousel? do
process :resize_to_fit => [2200, 1000]
end
version :phone do
process :resize_to_fit => [900,900]
end
# def scale(width, height)
# # do something
# end
def is_side_carousel? photo
model.location == 1
end
def is_thumbnail? photo
model.location == 2
end
def is_line? photo
model.location == 3
end
def is_carousel? photo
model.location == 4
end
# Add a white list of extensions which are allowed to be uploaded.
# For images you might use something like this:
def extension_white_list
%w(jpg jpeg gif png)
end
# Override the filename of the uploaded files:
# Avoid using model.id or version_name here, see uploader/store.rb for details.
def filename
file.nil? ? #filename = nil : #filename = "#{secure_token}.#{file.extension}"
end
def secure_token
var = :"##{mounted_as}_secure_token"
model.instance_variable_get(var) or model.instance_variable_set(var, SecureRandom.uuid)
end
def cache_dir
"#{Rails.root}/tmp/uploads"
end
end
I managed to fix this. I'm not exactly sure what I did, but there was a couple issues. (1) I think I was getting the auth error because I was specifying a folder in my uploader. Now, I set my directory in the uploader to "" and specify the folder through the fog configuration.
(2) Another error I was getting was a time mismatch. I run mint in a virtual machine for development, and the time was different from reality. Amazon threw an error at that. Once I set the correct time, that went away.

Carrierwave resize is not working (Rails 3 and MiniMagick)

what I want to do is to save a website url with a full-size snapshot via IMGKit. In one of the views I also want to have a thumbnail version of the snapshot. I'm using carrierwave in order to associate the snapshot with the object an MiniMagick to manipulate it, the problem is that it generates the 'thumbnail' image but doesn't resize it so as a result, I have two full-size snapshots, one of then with 'thumb' as prefix.
I have this model in rails
class Webpage
mount_uploader :snapshot, SnapshotUploader
field :url, type: String
field :title, type: String
after_create :get_snapshot
private
def get_snapshot
file = Tempfile.new(["#{id}#{title}".downcase, '.jpg'], 'tmp', :encoding => 'ascii-8bit')
image = IMGKit.new(url, quality: 90).to_jpg
file.write(image)
file.flush
self.snapshot= file
self.save
file.unlink
end
end
And I have this in the Uploader in order to create the thumbnail version:
class SnapshotUploader < CarrierWave::Uploader::Base
include CarrierWave::MiniMagick
version :thumb do
process resize_to_fill: [180, 180]
end
end
Using the console I tried MiniMagick for resizing an image and it works fine son I don't know what is happening.
I'm not sure if I'm doing it right so any help would be appreciated. Thanks.
OK, I'm stupid. I had an initializer with
config.enable_processing = false
so it will never process the image. Just setting it to true or deleting the line solved my problem.

encoding error with ajax upload (qqfile) and paperclip

I'm trying to get an ajax upload working with rails 3.1.3 and paperclip.
I found this solution to my problem Rails 3 get raw post data and write it to tmp file, but using this, I get an 'encoding undefined conversion error "\xFF" from ASCII-8BIT to UTF-8.
The error occurs at the line #user.photo = #user.photo = QqFile.parse(params[:qqfile], request)
I have not edited the code supplied in the previous answer, but I'll include it here so you don't have to switch back and forth.
the gem list paperclip, returns 2.5.2, 2.4.5, 2.3.8
my controller
def create
#user = User.new(params[:user])
#user.photo = QqFile.parse(params[:qqfile], request)
if #user.save
return render :json => #user
else
return render :json => #user.errors
end
end
qq_file.rb
# encoding: utf-8
require 'digest/sha1'
require 'mime/types'
# Usage (paperclip example)
# #asset.data = QqFile.new(params[:qqfile], request)
class QqFile < ::Tempfile
def initialize(filename, request, tmpdir = Dir::tmpdir)
#original_filename = filename
#request = request
super Digest::SHA1.hexdigest(filename), tmpdir
fetch
end
def self.parse(*args)
return args.first unless args.first.is_a?(String)
new(*args)
end
def fetch
self.write #request.raw_post
self.rewind
self
end
def original_filename
#original_filename
end
def content_type
types = MIME::Types.type_for(#request.content_type)
types.empty? ? #request.content_type : types.first.to_s
end
end
This was an encoding error related to Ruby 1.9.2 (or I believe Ruby 1.9+).
this github post lead to the answer
https://github.com/lassebunk/webcam_app/issues/1
You must specify raw_post.force_encoding("UTF-8") when reading an upload as far as I could tell (I'm not a great programmer).