How do I allow only logged in users to view images

805 views Asked by At

I have a Ruby on Rails (2.2.2) application where users can upload images and mark them as 'locked'. This will put them in another folder than if you don't mark it. The normal upload folder is /uploads/Image and the locked folder is /uploads/vip/Image. I would like to lock down the VIP folder only, so that you can not send the link to someone and view it without being logged in. I guess the logic would have to be redirected to the app instead of just serving the image blindly. Question is how?

Creating a model in rails is not an option since these images are uploaded by fckeditor and will just be written and linked in without further logic.

2

There are 2 answers

1
Syed Aslam On

Have a before filter, like before_filter :authenticate_user! if you are using devise. This will redirect to the login page if the user is not logged in. The images are served through a controller action.

0
thoughtpunch On

You might have to re-think how your app is designed since there is not going to be any way (as far as this n00b can see) to lock down certain paths without having an image model somewhere. There is a Rails fckeditor (link) gem that will allow you to fully integrate fckeditor with Rails models and controllers in your app.

Here is what I would do.

  1. Create an "image" model and controller with at bare minimum user_id:integer and protected:boolean, :default => false fields in the DB migration. This will make it easier to direct link to certain images and not others and keep track of who uploaded the image. Make sure to set the belongs_to :user relation in the image model.
  2. Setup your user model with a "has_many :images" relation to tie users to the photos they upload.
  3. Use Authlogic authenticate users and require certain pages to have a user logged into access using the before_filter :current_user method provided by Authlogic.
  4. Implement the rails-ckeditor gem with Paperclip to allow users to edit content and upload photos. You can configure PaperClip to save the images in either the "VIP" folder or the normal folder based on the "protected" field specified in your "image" model.
  5. Edit your routes.rb file to include the map.resources :images statement, which will help create full URL's for each photo that is uploaded.

That should be enough to get you on the right path. If you implement this correctly you should have the ability to let users upload photos in the fckeditor, choose wether they are protected or no "VIP", which should save the photos to the folder you specify, and only allow direct linking to the non-VIP photos and otherwise require that the user login/create and account. Good luck!

~Dan