/tools/Ruby/lib/ruby/1.8/webrick/httpauth/htpasswd.rb

http://github.com/agross/netopenspace · Ruby · 83 lines · 66 code · 9 blank · 8 comment · 3 complexity · 0a65aa9cecb69a8585ebc4fd27270225 MD5 · raw file

  1. #
  2. # httpauth/htpasswd -- Apache compatible htpasswd file
  3. #
  4. # Author: IPR -- Internet Programming with Ruby -- writers
  5. # Copyright (c) 2003 Internet Programming with Ruby writers. All rights
  6. # reserved.
  7. #
  8. # $IPR: htpasswd.rb,v 1.4 2003/07/22 19:20:45 gotoyuzo Exp $
  9. require 'webrick/httpauth/userdb'
  10. require 'webrick/httpauth/basicauth'
  11. require 'tempfile'
  12. module WEBrick
  13. module HTTPAuth
  14. class Htpasswd
  15. include UserDB
  16. def initialize(path)
  17. @path = path
  18. @mtime = Time.at(0)
  19. @passwd = Hash.new
  20. @auth_type = BasicAuth
  21. open(@path,"a").close unless File::exist?(@path)
  22. reload
  23. end
  24. def reload
  25. mtime = File::mtime(@path)
  26. if mtime > @mtime
  27. @passwd.clear
  28. open(@path){|io|
  29. while line = io.gets
  30. line.chomp!
  31. case line
  32. when %r!\A[^:]+:[a-zA-Z0-9./]{13}\z!
  33. user, pass = line.split(":")
  34. when /:\$/, /:\{SHA\}/
  35. raise NotImplementedError,
  36. 'MD5, SHA1 .htpasswd file not supported'
  37. else
  38. raise StandardError, 'bad .htpasswd file'
  39. end
  40. @passwd[user] = pass
  41. end
  42. }
  43. @mtime = mtime
  44. end
  45. end
  46. def flush(output=nil)
  47. output ||= @path
  48. tmp = Tempfile.new("htpasswd", File::dirname(output))
  49. begin
  50. each{|item| tmp.puts(item.join(":")) }
  51. tmp.close
  52. File::rename(tmp.path, output)
  53. rescue
  54. tmp.close(true)
  55. end
  56. end
  57. def get_passwd(realm, user, reload_db)
  58. reload() if reload_db
  59. @passwd[user]
  60. end
  61. def set_passwd(realm, user, pass)
  62. @passwd[user] = make_passwd(realm, user, pass)
  63. end
  64. def delete_passwd(realm, user)
  65. @passwd.delete(user)
  66. end
  67. def each
  68. @passwd.keys.sort.each{|user|
  69. yield([user, @passwd[user]])
  70. }
  71. end
  72. end
  73. end
  74. end