# $Id: ext_password.rb,v 1.2 2004/04/07 06:21:45 eto Exp $
# Copyright (C) 2003-2004 Kouichirou Eto, All rights reserved.
# This is free software with ABSOLUTELY NO WARRANTY.
# You can redistribute it and/or modify it under the terms of the GNU GPL2.

require 'md5'

module Qwik
  module SitePassword # has relation with cmd_save
    def password
      SitePassword.get_pass(load())
    end

    def have_password?()
      password() != nil
    end

    def embed_password(v)
      new_pass = SitePassword.get_pass(v)
      return v if !new_pass
      v.sub(/\{\{password\((.+)\)\}\}/){"{{password("+$1.md5hex+")}}"}
    end

    def match_password?(v)
      return true if !have_password? # go on
      old_pass_md5 = password()
      new_pass_md5 = SitePassword.get_pass(v) # assume already become md5
      return false if !new_pass_md5 # can not go if there is no pass
      return false if new_pass_md5 != old_pass_md5 # should be correct pass
      return true # go on
    end

    def SitePassword.get_pass(str)
      return $1 if str && str =~ /\{\{password\((.+)\)\}\}/
      return nil
    end
  end

  class Page
    include SitePassword
  end

  class Plugin
    def password(pass=nil)
      ""
    end
  end
end
