small medium large xlarge

Generic-user-small
13 Jan 2010, 21:57
Nathan (5 posts)

Im having issues with the login section of the book. When using the login form it doesnt seem to work but refresh the page as if the account is invalid. I think I have a problem with getting the user as I have tested the if statement after setting the user variable to output some text to the screen which doesn’t work, but it does outside of the if:

user = User.authenticate(params[:name], params[:password])

I have attached the login controller and the user model. If somebody could help me out It would be much appreciated

Thanks

def login
    if request.post?
      user = User.authenticate(params[:name], params[:password])
      if user
        session[:user_id] = user.id
        redirect_to(:action => "index")
      else
        flash.now[:notice] = "Invalid user/password combination"
      end
    end
  end



require 'digest/sha1'
class User < ActiveRecord::Base
  
  validates_presence_of     :name
  validates_uniqueness_of   :name
 
  attr_accessor :password_confirmation
  validates_confirmation_of :password
  validate :password_non_blank

  def self.authenticate(name,password)
    user = self.find_by_name(name)
    if user
      expected_password = encrypted_password(password, user.salt)
      if user.hashed_password != expected_password
        user = nil
      end
    end
    user
  end
  
  def password
    @password
  end
  
  def password=(pwd)
   @password = pwd
   return if pwd.blank
   create_new_salt
   self.hashed_password = User.encrypted_password(self.password, self.salt)
  end
  
  private
  
  def password_non_blank
    errors.add(:password, "Missing password") if hashed_password.blank?
  end
  
  def create_new_salt
    self.salt =  self.object_id.to_s + rand.to_s
  end
  
  def self.encrypted_password(password, salt)
    string_to_hash = password + "wibble" + salt
    Digest::SHA1.hexdigest(string_to_hash)
  end

end
Generic-user-small
14 Jan 2010, 19:14
Nathan (5 posts)

Okay i feel so stupid for tripping up over this but it’s quite obvious that username nathan is not the same as Nathan :P, so it would help if I was logging in with a valid username

Generic-user-small
24 Mar 2010, 18:08
Jake Rockwell (2 posts)

I was experience the same issue. Does anyone know why my apps flash.now notice is not displaying in the template when an invalid username or password is entered?

Generic-user-small
24 Mar 2010, 19:47
Jake Rockwell (2 posts)

After creating the logout method and adding a link in the sidebar to ‘logout’ I am now seeing the flash message when I try to login with an invalid username and password. Still trying to figure out ‘why’.

You must be logged in to comment