Content Protection with AuthLogic

I know this sounds like a really, very simple use case, and I hope it is, but I swear I searched everywhere and did not find any mention in any way - not even the best way - to do it.

I do branding for Ruby, Rails, and everyone else (which can explain a lot). The dummy application that I use as a training tool requires authentication in order to do almost anything meaningful, so I decided to start by solving this problem. I installed the AuthLogic gem and it works well to the extent described in the intro and Railscast documentation, but now I can register, log in and log out ... I need to do something with it.

As an example, I need to create a page where users can upload images. I plan to have an ImagesController with the upload action method, but I want it to be available only to registered users. I believe that in every limited action I could add code to redirect if there is no current_user , but that seems really verbose.

Is there a better way to do this that allows me to identify or identify limited areas and handle authentication in one place?

+4
source share
4 answers

Make sure you have these methods in your application application_controller.rb

 def current_user_session return @current_user_session if defined?(@current_user_session) @current_user_session = UserSession.find end def current_user return @current_user if defined?(@current_user) @current_user = current_user_session && current_user_session.record end def require_user unless current_user store_location flash[:notice] = "You must be logged in to access this page" redirect_to new_user_session_url return false end end 

Then in your controllers you can use the before filter to restrict access to pages

 class ExamplesController < ActionController::Base before_filter :require_user, :only => :private def public // some public stuff end def private // some protected stuff end end 
+6
source

before_filter is your friend here. You define a require_authentication function that returns false if there is no valid session, and then set it as before_filter in controllers and actions to your liking.

Take a look at the Authlogic Sample application, which defines some filters in application_controller.rb and then uses it where it is needed (for example, where you need to log in to destroy your account and not log in to create a new one.

0
source

You will need to use the before_filter file on your page so that only registered users can see it. If you want to use the Authlogic example (including before_filter stuff), you can check out the Authlogic Exmaple from Github .

0
source

You have all the Gist code available here on Github. Its about 360 lines of code. Including steps.

http://gist.github.com/96556.txt

0
source

All Articles