Skip to content

Instantly share code, notes, and snippets.

@vaz
Created May 16, 2016 20:21
Show Gist options
  • Save vaz/c5d6d7c1058cf7ad3ecf5d2360699190 to your computer and use it in GitHub Desktop.
Save vaz/c5d6d7c1058cf7ad3ecf5d2360699190 to your computer and use it in GitHub Desktop.
Sinatra sessions example
# basic sinatra app showing some use of sessions to handle
# some (insecure) authentication
require 'sinatra'
# enable default sessions support
# sessions are "like hashes" and get serialized (stringified) and
# stored directly in a session cookie.
# Sinatra (actually a Rack sessions extension) handles this for you
enable :sessions
helpers do
def current_user
# session['whatever'] will be nil if it's not present in the session
user_id = session['user_id']
user_id.nil? ? nil : User.find(user_id)
end
def logged_in?
!current_user.nil?
end
end
get '/login' do
# show the login form
erb :login
end
post '/login' do
# Process the login form
u = User.find_by(email: params[:email])
if !u.nil? && u.password == params[:password]
session['user_id'] = u.id
else
# not found
session['notice'] = 'could not log you in, check email or password'
redirect to('/')
end
end
get '/logout' do
# doesn't much matter if /logout is GET
session['user_id'] = nil
redirect to('/')
end
before '/admin/*' do
# HTTP Response code 403 Forbidden
halt 403 unless logged_in?
end
# these are protected by the before filter:
get '/admin' do
'this is secret'
end
get '/admin/settings' do
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment