1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
def call_with_password(user, url, &block)
  abort "misformed URL #{url}" unless url =~ %r{^(\w+)://([^/]+)(.*?/?)[^/]*$}
  proto, host, path = $1, $2, $3 # we should map proto to the four character code which Apple use for the protocol

  res = %x{security find-internet-password -g -a "#{user}" -s "#{host}" -p "#{path}" -r #{proto} 2>&1 >/dev/null}
  if res =~ /^password: "(.*)"$/ then
    block.call $1
  else
    cd_path = ENV['TM_SUPPORT_PATH'] + '/bin/CocoaDialog.app/Contents/MacOS/CocoaDialog'
    res = %x{"#{cd_path}" secure-standard-inputbox \
      --title "Enter Password" \
      --informative-text "Enter password for “#{user}” at host “#{host}”"
    }

    pass = res.split("\n")[1]
    if res[0] == ?1 && block.call(pass) then
      %x{security add-internet-password -a "#{user}" -s "#{host}" -r "#{proto}" -p "#{path}" -w "#{pass}"}
    end
  end
end

call_with_password('duff', 'http://example.com/blog/xmlrpc.php') do |pw|
  true # return false if the pw wasn’t accepted
end