Created
November 15, 2012 18:03
-
-
Save efrenfuentes/4080155 to your computer and use it in GitHub Desktop.
Simple Sinatra Authentication
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'rubygems' | |
require 'sinatra' | |
set :username,'Bond' | |
set :token,'shakenN0tstirr3d' | |
set :password,'007' | |
helpers do | |
def admin? ; request.cookies[settings.username] == settings.token ; end | |
def protected! ; halt [ 401, 'Not Authorized' ] unless admin? ; end | |
end | |
get '/' do | |
haml :index | |
end | |
get('/admin'){ haml :admin } | |
post '/login' do | |
if params['username']==settings.username&¶ms['password']==settings.password | |
response.set_cookie(settings.username,settings.token) | |
redirect '/' | |
else | |
"Username or Password incorrect" | |
end | |
end | |
get('/logout'){ response.set_cookie(settings.username, false) ; redirect '/' } | |
get '/public' do | |
'Anyone can see this' | |
end | |
get '/private' do | |
protected! | |
'For Your Eyes Only!' | |
end | |
__END__ | |
@@layout | |
!!! 5 | |
%html | |
%head | |
%meta(charset="utf-8") | |
%title Really Simple Authentication | |
%body | |
%a(href='/admin')Login | |
%a(href='/logout')Logout | |
%a(href='/public')Public | |
%a(href='/private')Private | |
= yield | |
@@admin | |
%form(action="/login" method="post") | |
%label(for="username")Username: | |
%input#username(type="text" name="username") | |
%label(for="password")Password: | |
%input#password(type="password" name="password") | |
%input(type="submit" value="Login") or <a href="/">Cancel</a> | |
@@index | |
-if admin? | |
%h1 Welcome 007! | |
-else | |
%h1 Welcome! |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
From http://ididitmyway.heroku.com/past/2011/2/22/really_simple_authentication_in_sinatra/