Two quick newbie questions


#1

2 quick questions regarding authentication …

  1. 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

  1. 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


#2

irb(main):001:0> “XXX” + “123”
=> “XXX123”


#3

for the 1st question:

I’m fairly new to rails too, but i dont think thats how you concatenate
strings in ruby. I think you need “<<” where the “+” is.

for the 2nd question:

params is a hash, and you are referencing the values to the key “user”.
The
second one looks wrong because it seems to be redefining the key “user”
to
two different things, username and password.

When you do User.new(params[:user]), you are passing the hash to the
model
to build a new user object. This would be the same as
User.new(:username =>
“foo”, :password => “secret”, …)

the call to new is also given a hash.


#4

this is what you want:

user = User.new(:username => “the username”, :password => “the
password”)


#5

try that instead:

flash[:notice] = ‘Login successful! Welcome
#{authentic_user.first_name}
#{authentic_user.last_name}!’

one of the things why I love ruby…