Skip to content

Instantly share code, notes, and snippets.

@stujo
Created January 6, 2017 00:28
Show Gist options
  • Save stujo/cae0d80018a21bc97f3097b384b665a5 to your computer and use it in GitHub Desktop.
Save stujo/cae0d80018a21bc97f3097b384b665a5 to your computer and use it in GitHub Desktop.
sinatra session auth example (without database)
require 'sinatra'
enable :sessions
# helpers/session_helper.rb
helpers do
def session_user_id
session[:user_id]
end
def session_logout
session.delete :user_id
end
def session_login(user_id)
session[:user_id] = user_id
end
end
# controllers/home.rb
get '/' do
if session_user_id
"HELLO USER #{session_user_id}" + '<a href="/logout">logout</a>'
else
'Please <a href="/login">login</a>'
end
end
# controllers/session.rb
# POST /session/new
# POST /login
# Should really be a POST
get '/login' do
session_login(55) # you would get this from the user authentication
redirect '/'
end
# DELETE /session
get '/logout' do
session_logout
redirect '/'
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment