If you were to publish your blog online, anyone would be able to add, edit and delete articles or delete comments.
Rails provides a very simple HTTP authentication system that will work nicely in this situation.
In the ArticlesController we need to have a way to block access to the various actions if the person is not authenticated. Here we can use the Rails http_basic_authenticate_withmethod, which allows access to the requested action if that method allows it.
To use the authentication system, we specify it at the top of our ArticlesController in app/controllers/articles_controller.rb. In our case, we want the user to be authenticated on every action except index and show, so we write that:
class ArticlesController < ApplicationControllerhttp_basic_authenticate_with name: "dhh", password: "secret", except: [:index, :show]def index@articles = Article.allend# snippet for brevity
We also want to allow only authenticated users to delete comments, so in the CommentsController (app/controllers/comments_controller.rb) we write:
class CommentsController < ApplicationControllerhttp_basic_authenticate_with name: "dhh", password: "secret", only: :destroydef create@article = Article.find(params[:article_id])# ...end # snippet for brevity
Now if you try to create a new article, you will be greeted with a basic HTTP Authentication challenge:
Other authentication methods are available for Rails applications. Two popular authentication add-ons for Rails are the Devise rails engine which we will use in the next project, and the Authlogic gem, along with a number of others.
Security, especially in web applications, is a broad and detailed area. Security in your Rails application is covered in more depth in the Ruby on Rails Security Guide