Skip to content

Instantly share code, notes, and snippets.

@znz
Created February 9, 2011 08:01
Show Gist options
  • Save znz/818126 to your computer and use it in GitHub Desktop.
Save znz/818126 to your computer and use it in GitHub Desktop.
htdigest を生成する rack アプリ
require 'webrick/httpauth/htdigest'
class UtilApp
def call(env)
result = nil
case env['REQUEST_METHOD']
when 'POST'
begin
params = Rack::Utils.parse_query(env['rack.input'].read)
realm = "SET YOUR REALM HERE"
username = params['username']
password = params['password']
case
when /[^ -~]/ =~ username
result = "invalid character in username"
when /[^ -~]/ =~ password
result = "invalid character in password"
when password != params['password_confirm']
result = "password mismatch"
else
path = File.expand_path('tmp.htdigest', File.dirname(__FILE__))
htdigest = WEBrick::HTTPAuth::Htdigest.new(path)
htdigest.set_passwd(realm, username, password)
htdigest.flush
re = /^#{Regexp.quote(username)}:/
File.foreach(path) do |line|
if re =~ line
result = line
break
end
end
end
rescue Exception
result = "Internal Server Error: #$!"
end
end
html = <<-HTML
<!DOCTYPE html>
<html>
<head>
<title>Util</title>
<style type="text/css">
body {
background-color: snow;
}
.result {
color: green;
}
</style>
</head>
<body>
<p class="result">#{Rack::Utils.escape_html(result)}</p>
<form method="POST">
<table>
<tr>
<th>username</th>
<td><input name="username" placeholder="username" type="text" /></td>
</tr>
<tr>
<th>password</th>
<td><input name="password" placeholder="password" type="password" /></td>
</tr>
<tr>
<th>password (confirm)</th>
<td><input name="password_confirm" placeholder="password (confirm)" type="password" /></td>
</tr>
</table>
<input type="submit" />
</form>
</body>
</html>
HTML
[200, {"Content-Type" => "text/html; charset=utf-8"}, [html]]
end
end
run UtilApp.new
# vim: set ft=ruby:
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment