2 quick questions regarding authentication …
- the flash[:notice] on successful login looks completely wrong to me.
How should it be done?
def index
if request.post?
@user = User.new(params[:user])
authentic_user = @user.attempt_login
if authentic_user
session[:user_id] = authentic_user.id
flash[:notice] =
'Login successful! Welcome ’ + authentic_user.first_name + ’ ’ +
authentic_user.last_name + ‘!’
redirect_to(:controller => ‘user’)
else
flash[:notice] = ‘Invalid username or password.’
end
end
end
- can someone explain why the first of these two techniques works (ie,
login is successful) but the second doesn’t:
@user = User.new(params[:user])
@user = User.new(params[:user => ‘username’, :user => ‘password’])
… given this model:
class User < ActiveRecord::Base
attr_accessor :password
attr_accessible :username, :password
def before_create
self.hashed_password = User.encrypt_password(self.password)
end
def after_create
@password = nil
end
def self.login(username, password)
hashed_password = encrypt_password(password || ‘’)
find(:first,
:conditions => [‘username = ? and hashed_password =?’,
username, hashed_password])
end
def attempt_login
User.login(self.username, self.password)
end
private
def self.encrypt_password(password)
Digest::SHA1.hexdigest(password)
end
end
… and assuming a form with fields ‘name=user[username]’ &
‘name=user[password]’. Thanks for the help. Kindly appreciated.
Greg