#This is a complete RESTful login system for use with Rails. I pastied it to show
#how incredibly SIMPLE the concept is. You should UNDERSTAND what's going on
#when a user logs in to your application.
#
#Of course, you shouldn't even have to think about authentication, because you
#should be using OpenID! :)
Logging in & out
class LoginsController < ApplicationController
#Show information about the current login (user)
#HTTP: GET /login
def show
redirect_to new_login_url unless logged_in?
end
#Display the login form, which POSTs your credentials
#HTTP: GET /login/new
def new
redirect_to login_url if logged_in?
end
#Create a login (aka just "log in")
#HTTP: POST /login
def create
if self.current_user = User.authenticate(params[:user][:username], params[:user][:password])
flash[:notice] = 'Logged in'
redirect_to login_url
else
flash[:error] = 'Authentication failed'
render :action => 'new'
end
end
#Destroy the login (aka just "log out")
#HTTP: DELETE /login
def destroy
self.current_user = nil
flash[:notice] = 'Logged out'
redirect_to new_login_url
end
end
Application
class ApplicationController < ActionController::Base
helper_method :logged_in?
def logged_in?
!!current_user
end
helper_method :current_user
def current_user
@_current_user ||= User.find_by_id(session[:current_user_id])
end
private
def current_user=(user)
session[:current_user_id] = user && user.id #When user.nil? => log out
@_current_user = user
end
end
Model
class User < ActiveRecord::Base
def password=(pw)
write_attribute(:password, self.class.hash_password(pw))
end
private
def self.authenticate(username, password)
find(:first, :conditions => {:username => username, :password => hash_password(password)})
end
#Should be salted for added security
def self.hash_password(password)
Digest::SHA1.hexdigest(password)
end
end