Search code examples
macoscocoaswitch-user

Cocoa - Force User To Switch?


I am building a mac application, that at a certain time, needs to switch the currently logged in user to a different, preset one. Essentially a modified login window.

Is there a way to do this using cocoa?

-- Ari

Edit: Is there a way to not require the user to input their password?


Solution

  • Before I say my solution, I want to say that @jrodatus's answer is excellent, it just is for a slightly different use case.

    I came up with this little applescript:

    set theUser to "user"
    set theUser to do shell script "/usr/bin/id -u " & theUser
    set password to "pswd"
    do shell script "/System/Library/CoreServices/Menu\\ Extras/User.menu/Contents/Resources/CGSession -switchToUserID " & theUser
    repeat
        try
            tell application "System Events"
                repeat until visible of process "SecurityAgent" is false
                    set visible of process "SecurityAgent" to false
                end repeat
                keystroke password
                keystroke return
            end tell
            exit repeat
        on error
            tell application "System Events"
            end tell
        end try
    end repeat
    

    This simply triggers the login screen, with -switchToUserID set to the username's user id. Then when at least one window of SecurityAgent (The login screen) is visible, simulate the keystroke of the password, then enter the result is when run the login window opens, with the password typed in. Also, this has no delays.