Skip to content

Instantly share code, notes, and snippets.

@amscotti
Created November 22, 2011 00:45
Show Gist options
  • Star 25 You must be signed in to star a gist
  • Fork 10 You must be signed in to fork a gist
  • Save amscotti/1384524 to your computer and use it in GitHub Desktop.
Save amscotti/1384524 to your computer and use it in GitHub Desktop.
Sample of Sinatra authentication
require 'rubygems'
require 'bcrypt'
require 'haml'
require 'sinatra'
enable :sessions
userTable = {}
helpers do
def login?
if session[:username].nil?
return false
else
return true
end
end
def username
return session[:username]
end
end
get "/" do
haml :index
end
get "/signup" do
haml :signup
end
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
get "/logout" do
session[:username] = nil
redirect "/"
end
__END__
@@layout
!!! 5
%html
%head
%title Sinatra Authentication
%body
=yield
@@index
-if login?
%h1= "Welcome #{username}!"
%a{:href => "/logout"} Logout
-else
%form(action="/login" method="post")
%div
%label(for="username")Username:
%input#username(type="text" name="username")
%div
%label(for="password")Password:
%input#password(type="password" name="password")
%div
%input(type="submit" value="Login")
%input(type="reset" value="Clear")
%p
%a{:href => "/signup"} Signup
@@signup
%p Enter the username and password!
%form(action="/signup" method="post")
%div
%label(for="username")Username:
%input#username(type="text" name="username")
%div
%label(for="password")Password:
%input#password(type="password" name="password")
%div
%label(for="checkpassword")Password:
%input#password(type="password" name="checkpassword")
%div
%input(type="submit" value="Sign Up")
%input(type="reset" value="Clear")
@@error
%p Wrong username or password
%p Please try again!
Copy link

ghost commented Nov 15, 2013

For lines 12 to 18 you could write something like session[:username].nil? ? false : true instead, right? Also, no need for all the returns.

@femaref
Copy link

femaref commented Nov 24, 2013

@rafalchmiel: You could just use !!session[:username]. nil evaluates to false, so by negating it twice you force it to a bool. If there is a username in there, you will force the value to true.

If you want to use your code, !session[:username].nil? would do the job as well.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment