#270 Authentication in Rails 3.1
Jun 13, 2011 | 7 minutes | Rails 3.1, Authentication
Here I show off three new features in Rails 3.1 that will help with authentication: easier HTTP Basic, SecurePassword in the database, and forcing SSL.
- Download:
- source codeProject Files in Zip (185 KB)
- mp4Full Size H.264 Video (8.86 MB)
- m4vSmaller H.264 Video (6.56 MB)
- webmFull Size VP8 Video (7.63 MB)
- ogvFull Size Theora Video (13.2 MB)
Resources
bash
rails g model user email:string password_digest:string
rails s -e production
rails g model user email:string password_digest:string rails s -e production
secret_controller.rb
http_basic_authenticate_with :name => "frodo", :password => "thering"
http_basic_authenticate_with :name => "frodo", :password => "thering"
models/user.rb
class User < ActiveRecord::Base
attr_accessible :email, :password, :password_confirmation
has_secure_password
validates_presence_of :password, :on => :create
end
class User < ActiveRecord::Base attr_accessible :email, :password, :password_confirmation has_secure_password validates_presence_of :password, :on => :create end
sessions_controller.rb
def create
user = User.find_by_email(params[:email])
if user && user.authenticate(params[:password])
session[:user_id] = user.id
redirect_to root_url, :notice => "Logged in!"
else
flash.now.alert = "Invalid email or password"
render "new"
end
end
def destroy
session[:user_id] = nil
redirect_to root_url, :notice => "Logged out!"
end
def create user = User.find_by_email(params[:email]) if user && user.authenticate(params[:password]) session[:user_id] = user.id redirect_to root_url, :notice => "Logged in!" else flash.now.alert = "Invalid email or password" render "new" end end def destroy session[:user_id] = nil redirect_to root_url, :notice => "Logged out!" end
application_controller.rb
force_ssl
private
def current_user
@current_user ||= User.find(session[:user_id]) if session[:user_id]
end
helper_method :current_user
force_ssl private def current_user @current_user ||= User.find(session[:user_id]) if session[:user_id] end helper_method :current_user

