Advertisement
Help Keep Boards Alive. Support us by going ad free today. See here: https://subscriptions.boards.ie/.
If we do not hit our goal we will be forced to close the site.

Current status: https://keepboardsalive.com/

Annual subs are best for most impact. If you are still undecided on going Ad Free - you can also donate using the Paypal Donate option. All contribution helps. Thank you.
https://www.boards.ie/group/1878-subscribers-forum

Private Group for paid up members of Boards.ie. Join the club.

Ruby on Rails Help Needed

  • 16-06-2011 08:44AM
    #1
    Registered Users, Registered Users 2 Posts: 357 ✭✭


    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


Advertisement