Daily Grind

システム開発関連の忘備録です

Webrickでダイジェスト認証

#!/usr/bin/ruby

# -*- coding: utf-8 -*-

IP       = '127.0.0.1'             #IPは変えること
PORT     = '4000'                #port は1024以下にしないこと、する場合はroot権限
DOC      =  './'
#CGI_PATH = '/usr/local/bin/ruby' #環境にあわせてwindows  'C:\Ruby193\bin\ruby.exe'
CGI_PATH = '/usr/bin/ruby'

require 'webrick'

opts  = {
  :BindAddress    => IP,
  :Port           => PORT,
  :DocumentRoot   => DOC,
  :CGIInterpreter => CGI_PATH
}

srv = WEBrick::HTTPServer.new(opts)

# ダイジェスト認証の設定(引数にはダイジェスト認証用のデータベースのパスを渡す)
pswd = WEBrick::HTTPAuth::Htdigest.new("dot.digest")

#if pswd.get_passwd("Secret Zone", "admin", false) == nil
#  pswd.set_passwd("Secret Zone", "admin", "sysadmin") # realm, user, passwd
#  pswd.flush                                     # ファイルに書き込む
#end

auth = WEBrick::HTTPAuth::DigestAuth.new(:UserDB => pswd, :Realm => "Secret Zone")

# HTTPServerの/loginにダイジェスト認証を設定
srv.mount_proc("/"){|req, res|
  # 認証
  auth.authenticate(req, res)
  res.body = "<html><head><title>うんこおお</title></head><body><p>OK.</p></body></html>" 
}

# view.cgiにhttpアクセスした場合、view.rbをcgiで動かす
#srv.mount('/view.cgi', WEBrick::HTTPServlet::CGIHandler,  'view.rb')

#コマンドラインでCtrl+Cした場合止めるイベントハンドラ
Signal.trap(:INT){ srv.shutdown}

#サーバースタート
srv.start