Lock screen with password on a per-use basis

Feb 13, '09 07:30:00AM

Contributed by: DarthMagnus

I like to be able to lock my computer with a password, however, I don't like to have the screensaver require a password every time it is turned on. I have found the Lock Screen from the Keychain menu item to be buggy, and I don't like the extra clutter in my menu bar for just the one function.

Hunting around, I couldn't find anything that did quite what I wanted to, so I wrote this AppleScript to allow you to lock the screen. Then, when you come back from that locked session, it returns to normal screensaver functionality. Simply paste this code into Script Editor and save it as a Stay Open application.

--This application will require the password to wake from
--sleep and then start the screen saver. Once the screen
--saver is finished running, the password is no longer required

global screenSaverOn
on run
    -- Sets computer to require a password
    tell application "System Events"
        tell security preferences
            set require password to wake to true
        end tell
    end tell
    -- Launches the screen saver
    tell application id "com.apple.ScreenSaver.Engine" to launch
    set screenSaverOn to true
end run

-- Polls the system to see if the screen saver is running
on idle
    tell application "System Events"
        -- Polls the system to see if the screen saver is running
        set screenSaverOn to (name of processes) contains "ScreenSaverEngine"
    end tell
    if not screenSaverOn then
        -- Once screensaver is turned off, prompts user to return to not require password. Without this, someone could simply wake the screensaver, cancel the password prompt, and then wake the screensaver again to access the session.
        display dialog "Return to no password required to wake?" buttons {"No", "Yes"} default button 2 giving up after 30 --Change this number to adjust time before prompt disappears
        if the button returned of the result is "Yes" then
            tell application "System Events"
                tell security preferences
                    set require password to wake to false
                end tell
            end tell
            tell me to quit
        end if
    end if
    
    -- delays 5 seconds before next check to reduce CPU load
    return 5
end idle

-- Allows script to be quit cleanly as when scheduled shutdown or logout occurs.
on quit
    continue quit
end quit
[robg adds: I haven't tested this one.]

Comments (28)


Mac OS X Hints
http://hints.macworld.com/article.php?story=20090212074725172