Funding for 'IT Lab' Project, Phase 1: Progress of sticker sales. Purchase a sticker to help us reach our target.Updated: 2010-02-28 11:53
10.7%
Make Rails development even easier with rails plugins

by Sameera Gayan

Hi again, If you are following with me for the last 4 sessions, you must know what this column is about. But those who are new to this article, it’s about Ruby and Rails, a new web framework which takes your web development skills to a new level. For previous references please read,

Creating a simple blog application in Rails
http://digit.lk/node/440 (part 1)
http://digit.lk/09_dec_ruby (part 2)
and little bit of theory behind what we did (http://digit.lk/node/613)

Ok, then you might ask, what do I have for today? Today we will add the authorization and authentication functionality to our blog application. Wait... what does that mean, simple, we can see that any user can publish new blog posts in our system. (So that’s bad, we want only the blog owner to publish the posts) of course, others can comment.

Creating an authorization system is a hassle and its a big work, Then you might ask “Does rails have an easy way?” , Ahhh.... Yes of course rails does. And the best part is, it will take 5-10 mins to make your application an authenticated one. Yes, you read it right 5-10 mins, because its out there already developed. We simple want to use it.

Plugins and Gems

What are plugins and gems? Plugins and gems are developed by hundreds and thousand of rails developers out there and they make it freely available for others to use them. So it wraps most of the common functionalities so that others can use the same code as and when required.

Think of plugins / gems like this: You want a simple calculation to be done in your application. (say adding two numbers) . You can do this in two ways.

1 – you can write a function in your code and do it
2 – you can write a plugin or gem which will have a method which expects 2 values and return the sum of those values. The advantage is you can make your plugin/gem freely available on the internet so that if someone else also has the same requirement (Adding 2 numbers),they can download our plugin/gem and get his/her work done without writing code again...

Have a look at this website (http://agilewebdevelopment.com/) and it has so many rails plugins which you can use without finding the wheel again.

Now lets start.....

What we want to do -

Only authorized personals can create posts.

What we need.

We need some kind of user registration process where user needs to login before he/she add a post.

Do we have a plugin for this.. Yes

Restful Authentication is a great rails plugin which will,

  • create user registration process
  • create login
  • allow to check if a user is logged in or not before doing a given action

 

Here we go...

First we need to install the plugin for our application. So from you root in the Blog application, pass

ruby script/plugin install http://svn.techno-weenie.net/projects/plugins/restful_authentication/

This will install the plugin to your application

Then we have 2 options

Either we can allow users to create an account and it will be activated then and there, or else we can send a confirmation link to the user so that, until he/she clicks that link his/her account will not be activated.

So we will go with the hard way (user needs to click the link to activate his/her account)

ruby script/generate authenticated user sessions --include-activation

If you dont want the confirmation link part, then simple ignore –include-activation parameter

then run rake to create the database tables

rake db:migrate

ok this command should create you some tables

then add some routes to config/routes.rb

map.activate '/activate/:activation_code', :controller => 'users', :action => 'activate'
map.signup '/signup', :controller => 'users', :action => 'new'
map.login '/login', :controller => 'sessions', :action => 'new'
map.logout '/logout', :controller => 'sessions', :action => 'destroy'

Lets explore some of these routes

map.activate '/activate/:activation_code', :controller => 'users', :action => 'activate'

this is for the user activation, (remember .. we want our users to click on a link sent by an e-mail). So when they click on that like it will direct to

http://<url>/activate/<activation code>

And we need to add the following code to config/enviroment.rb inside Rails::Initializer.run

config.active_record.observers = :user_observer

... wait what is this... this is for user model, this will keep an eye on the user model and when a user is created , automatically sends an e-mail.

Now we need to configure actionmailer to send e-mails. In config/initializers create a file called mail.rb and paste this code

ActionMailer::Base.delivery_method = :smtp
ActionMailer::Base.smtp_settings = {
:address => "mail.example-domain.com",
:port => 25,
:domain => "www.example-domain.com",
:authentication => :login,
:user_name => "user@example-domain.com",
:password => "secret"
}

 

Note : you may want to change these settings accordingly

and then go to app/models/UserMailer file and change the YOURSITE parameter accordingly

OK.. now we are almost done... want to see it in action ?

Start your server and point to http://localhost:3000/signup, then you should get the following page

and the login page is http://localhost:3000/login

Done... Now we want our application to check if a user is logged in or not for a given action. Before that, copy the 'include AuthenticatedSystem' in users and sessions controllers and include it in application controller.

# Filters added to this controller apply to all controllers in the application.

# Likewise, all the methods added will be available for all controllers.

 

class ApplicationController < ActionController::Base

helper :all # include all helpers, all the time

protect_from_forgery # See ActionController::RequestForgeryProtection for details

include AuthenticatedSystem

# Scrub sensitive parameters from your log

# filter_parameter_logging :password

end

so then you don't want to include it in every controller.

Now we will write a small method to check if the user is logged in or not

def authorize

unless logged_in?

redirect_to login_path

end

end

 

so what we do here is , check if a user is logged in or not and if the user is not logged in the redirect him/her to login or else don't do anything.

So let's call this before page loads, for that rails has a method called before_filter, it will execute a given method before executing the other methods of the rails.

Lets start, goto users controller and paste

before_filter :authorize

after class declaration (class UsersController < ApplicationController)

But wait... Now each and every action of the user controller needs to login. Event the signup (oops...) try http://localhost:3000/signup , it should redirect to login. That makes no sense. So lets except these methods, so modify your filter as

before_filter :authorize, :except => {:new, :create , :activate}

likewise add this filter to all of your controllers and except the actions which doesn't needs to login

Now comes the second part and that is, when a user is successfully logged in he/she should be directed to posts list screen. To do that

go to sessions_controller/create and change the line

redirect_back_or_default('/')

to

redirect_to post_path

Now you should be having a fully functional user authorization system for you blog.

So thats basically it, See how simple it is with rails and their plugins.

Next time also we will see some other useful rails plugins, until then happy programming

 

Previous Article

Share/Save
No votes yet

Post new comment

  • Web page addresses and e-mail addresses turn into links automatically.
  • Allowed HTML tags: <a> <em> <strong> <cite> <code> <ul> <ol> <li> <dl> <dt> <dd>
  • Lines and paragraphs break automatically.

More information about formatting options