ruby sinatra admin login rack--two way
http://www.sinatrarb.com/faq.html
require 'sinatra'
helpers do
def protected!
return if authorized?
headers['WWW-Authenticate'] = 'Basic realm="Restricted Area"'
halt 401, "Not authorized\n"
end
def authorized?
@auth ||= Rack::Auth::Basic::Request.new(request.env)
@auth.provided? and @auth.basic? and @auth.credentials and @auth.credentials == ['admin', 'admin']
end
end
get '/' do
"Everybody can see this page"
end
get '/protected' do
protected!
"Welcome, authenticated client"
end
LOGIN FORM (GET LOGIN METHOD)
<form method="post" action="/login">
<p><label>Username</label><input name="post[username]" /></p>
<p><label>Password</label><input name="post[password]"
type="password"/></p>
<p><button type="submit">Login</button></p>
</form>
POST LOGIN METHOD
post '/login' do
if authenticate(params["post"]["username"], Digest::MD5.hexdigest(params["post"]["password"]))
session[:user] = params["post"]["username"]
flash[:notice] = "Login succeeded!"
redirect '/admin'
else
flash[:error] = "Login failed!"
redirect '/login'
end
end
HELPER METHODS
# Authentication is hard-coded as there will only 1-3 users
def authenticate(username, password)
if username == 'admin' and password == '[admin_password_in_MD5]'
return true
else
return false
end
end
# Protect pages
def login_required
if session[:user]
return true
else
redirect '/login'
return false
end
end
# Get the username of the logged in user
def current_user
if session[:user]
session[:user]
end
end
# Verify if a user is logged in
def logged_in?
!!session[:user]
end