On the WEB is particularly important to have a way of authentication for users, and the safety of transporting the data (web safety won´t be dealt with in this article, see: ssl, key public, private)
We will create here a basic system that contains an auth system, that is, there are different ways of making it, but here we use the session and before_filter and authenticate_or_request_with_http_basic functions to make it as simples as possible !
Let’s use a very simple scaffold, despite this not be the best way of creating login I know this, but serves the purpose to register and view the passwords as they are encrypted thing and such, which already is cool…
Just take a test project that already exists and we will make a scaffold with the following parameters: user login:String password:String while in our BD table users create a very basic way:
CREATE TABLE user(
`id` int(10) unsigned NOT NULL auto_increment,
`login` char(22) NOT NULL default ”,
`senha` char(41) NOT NULL default ”,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;
Run this in SQL BD or easier yet, run a rake db:migrate
Okay, let’s limit the size of inputs by adding the model recently created:
class User< ActiveRecord::Base
validates_length_of :login, :in => 4..20, :allow_nil => false
validates_length_of :senha, :in => 4..40, :allow_nil => false
It would be worth to make something with some additional checks, for example passwords that are made of only one character should not be accepted, nor login == password.
Now the coolest.. at the Controller / application.rb enter the code:
class ApplicationController < ActionController::Base
authenticate_or_request_with_http_basic do |usuario, senha|
if Usuario.find (:first, :conditions=>[“login = ? and senha = ?”,
usuario, Digest::SHA1.hexdigest(senha)] )
session[:login] = usuario
Wow ! Easy and safe !!
It noted that my choice of :login as a field of the session was arbitrary, it could be any other name or other data stored, since that was not a false or nil.
Done! You just created a scheme that requires password for your entire application! Not a view remain unprotected now!
If your screen index after inserting some entries is looking like this:
it is because everything worked just fine.
Now, if we wanted to leave a page to login into the classic format would be entirely possible also in the following way inserting in your controller :
skip_filter :autentic, :except => :admin *this :except is optional for some action we want to aply the filter
Our login would have to implement the same search for user made in the above action and set a session [:login] = name of the user or true