Created
December 7, 2011 18:42
-
-
Save atduskgreg/1444042 to your computer and use it in GitHub Desktop.
demo of using basic auth and storing encrypted passwords using sinatra and datamapper
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' | |
require 'digest/md5' | |
require 'dm-core' | |
APP_SECRET = "my special secret" | |
DataMapper.setup(:default, {:adapter => 'yaml', :path => "db"}) | |
class User | |
include DataMapper::Resource | |
property :id, Serial | |
property :encrypted_password, Text | |
property :name, Text | |
end | |
helpers do | |
def check_password! | |
auth = Rack::Auth::Basic::Request.new(request.env) | |
if auth.provided? && auth.basic? && auth.credentials | |
user = User.first(:conditions => {:name => auth.credentials[0]}) | |
end | |
if user && user.encrypted_password == Digest::MD5.hexdigest(APP_SECRET + auth.credentials[1]) | |
return true | |
else | |
response['WWW-Authenticate'] = %(Basic realm="Restricted Area") | |
throw(:halt, [401, "Not authorized\n"]) | |
end | |
end | |
end | |
get "/new_user" do | |
<<-HTML | |
<form action="/~gab305/sinatra/auth_demo/create_user" method="post"> | |
<p> | |
<label>Username: </label> | |
<input type="text" name="username"/> | |
</p> | |
<p> | |
<label>Password: </label> | |
<input type="password" name="password"/> | |
</p> | |
<p> | |
<input type="submit" name="login"/> | |
</p> | |
</form> | |
HTML | |
end | |
post "/create_user" do | |
user = User.new | |
user.name = params[:username] | |
user.encrypted_password = Digest::MD5.hexdigest(APP_SECRET + params[:password]) | |
user.save | |
redirect "/~gab305/sinatra/auth_demo/" | |
end | |
get "/" do | |
result = "" | |
for user in User.all | |
result += "<p><b>Username:</b> #{user.name} <b>Encrypted Password:</b> #{user.encrypted_password}" | |
end | |
result | |
end | |
get "/only_users_allowed" do | |
check_password! | |
"welcome, user" | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment