Protect users’ upload files with the example of a website for selling pictures

Tram Ho

Today, people buy electronic products online very often such as images, audio, software, …. And of course, not everyone wants to upload something, others can freely download the file without any obligation. For example, websites that buy and sell images, sounds, etc.

For example, we have a website that sells paintings, for example, with the following basic requirements:

  • Users can upload photos for sale
  • Users can purchase photos from others
  • Users can review and download photos they have purchased

We will build the database with the following relationship:

In this example we will use paperclip for file upload:

Then run bundle install .

We will take a quick look at migration creation parts, and model:

Migration

Don’t forget to run the rails db:migrate command

Model

Upload Photos

Before users can sell, of course they must upload photos

List of photos uploaded by the user

Purchase

We need to create a new PurchasedImage record

Purchases Link

We want to see which purchases have been made by users

So we have built the frame of the website. And now users can access the images they have purchased. It’s time we add the download function enabled by that link. By default, Paperclip will store your attachment in the public/system directory in the application’s file structure. That means just clicking the download link. Of course, we want to secure our files, so they can only be downloaded by people who have access to them after purchase.

Confidential and download

With paperclip , when declaring attachments, we do the following:

The default path for saving files is as follows:: :rails_root/public/system/:class/:attachment/:id_partition/:style/:filename . The public folder we usually share and everyone can use, of course we don’t want that, so we need a little configuration in the model:

Now we have a new address to save the uploaded file

Serving the secure images

The problem is that we will show thumbnails instead of full size images

Downloading Purchases

Last but not least is the download

Quite similar to the above display function except that the downloaded image will be full size as it was originally uploaded

References

https://chrisherring.co/posts/how-can-i-protect-a-user-s-file-uploads-in-rails

Share the news now

Source : Viblo