Topic: Help Needed Login Code

I am having trouble writing a login in Ruby on Rails.   

This is the error I am getting  TypeError (can't convert nil into String):   app/models/user.rb:14:in `+'   app/models/user.rb:14:in `hash_password'   app/models/user.rb:28:in `authenticate'   app/controllers/user_controller.rb:24:in `login' 

My code in the .rb files is as follows  user_controller.rb 
def login
    if request.post?
      user = User.authenticate(params[:user][:login], params[:user][:password])

      if user
        session[:user] = user.id
        flash[:notice] = "Login Successful"
        redirect_to :controller=>'user',:action=>'home'
      else
        flash[:error] = "Login Unsuccessful"
        redirect_to :controller=>'home'
      end
    end
  end

user.rb


def password=(pass)
    @password=pass
    self.password_salt = User.random_string(10) if !self.password_salt?
    self.password_hash = User.hash_password(@password, self.password_salt)
  end

  protected

  def self.hash_password(pass,password_salt)
    Digest::SHA1.hexdigest(pass + password_salt)
  end

  def self.random_string(len)
    #generate a random password consisting of strings and digits
    chars = ("a".."z").to_a + ("A".."Z").to_a + ("0".."9").to_a
    newpass = ""
    1.upto(len) { |i| newpass << chars[rand(chars.size-1)]}
    return newpass
  end

  def self.authenticate(login,pass)
    u=find(:first, :conditions=>["login = ?", login])
    return nil if u.nil?
    return u if User.hash_password(pass,u.password_salt) == u.password_hash
    nil
  end

I am working through an example in a book so I am just getting to grips with Ruby on Rails
Cheers for any help

Last edited by apoch632 (2011-06-16 04:42:22)

Re: Help Needed Login Code

Hi,

to me it seems that the issue is within app/models/user.rb.  Typically this error is thrown when you try to concat two strings, one of which happens to be nil.  I sometimes come across this when trying to convert an attribute to string that has not had a value.

However, writing authentication code for rails is not necessarily a very good idea as a starting project.  For one, rails has excellent plugins/gems to this end (devise, for example), on the other hand, it can become quite tricky...

Post your model and let's see if it gets us anywhere.

boom

PS: This is not the right forum section for this, though.  You may get more help if you post to either Models and/or Controllers