-1

http://www.128bitstudios.com/2011/11/21/authentication-with-sinatra/

Simple and nice Sinatra BCrypt authentication system - I would appreciate an explanation =)

I found this very nice article on a very simple authentication system made for Sinatra together using BCrypt and I think it's great and simple, with an nice continues classic code.

However, I have trouble understanding it, and yes I am a noob. I would really appreciate if some of you could explain at least some of the code to me, and the one I am especially interested in is this part

post "/signup" do
  password_salt = BCrypt::Engine.generate_salt
  password_hash = BCrypt::Engine.hash_secret(params[:password], password_salt)

  #ideally this would be saved into a database, hash used just for sample
  userTable[params[:username]] = {
    :salt => password_salt,
    :passwordhash => password_hash 
  }

  session[:username] = params[:username]
  redirect "/"
end

post "/login" do
  if userTable.has_key?(params[:username])
    user = userTable[params[:username]]
    if user[:passwordhash] == BCrypt::Engine.hash_secret(params[:password], user[:salt])
      session[:username] = params[:username]
      redirect "/"
    end
  end
  haml :error
end

I guess there isn't anything wrong with the code considering it's written by someone who is much better than me with that kind of stuff, but it could contain errors, but most likely not. Since I am quite new to both Sinatra and the use of BCrypt I would appreciate if someone could explain the procedure and the way it encrypts the password.

All the rest of the code is there when you visit the link, no point pasting it all here.

Also I think if I have understood correctly that the BCryptEngine creates a salt from the user param :password, but I can't understand how it saves the user to the table and all etceteral stuff. Thanks :)

1 Answers1

1

If you want to implement something like this you should at least understand what you are doing and not simply ask here. There is simple stuff going on like saving the user data in a Hash that is not kept between requests so it doesn't make sense for you to implement unless you have an idea where you store the user data. A database might be the best answer for now.

The salt is not created from the user password, it is generated by BCrypt and stored in the userTable Hash. Along with the hashed password. In the signup routine the userTable gets an entry with the new user in it but unless you save that Hash somewhere, it is lost after the next request.

I'd recommend reading up on basic Ruby usage first. If you want to implement security into your app it makes sense to understand what you're up to. Otherwise it's more or less pure chance if security is secure.

three
  • 8,262
  • 3
  • 35
  • 39