unlocking Mac using Bluetooth

I wanted to share (and get constructive feedback) on my solution for unlocking my Mac automatically when my bluetooth device (iPhone) is within range.

There are a couple of commercial options on the App Store, but they only look for a single bluetooth device. I have a shared Mac in my home that both my wife and I use, and I wanted the Mac to unlock for both her phone and mine.

I hope this solution is helpful for others, and please respond with feedback if there are any security or other concerns.

To make this work I am using EventScripts (http://mousedown.net/mouseware/EventScripts.html) and serialportX (http://www.macupdate.com/app/mac/20440/serialport-x)


on run eventArgs
	--set thisTrigger to "Screen did wake" --for testing
	set thisTrigger to (trigger of eventArgs)
	if thisTrigger is "Screen did wake" then
		
		set aphone to "/dev/cu.WifessiPhone-Wirelessi"
		set cphone to "/dev/cu.MysiPhone-Wireless"
		set donewithit to false
		set portRef to 0
		
		set portRef to serialport open aphone
		serialport close portRef
		if portRef is 0 then
			set portRef to serialport open cphone
			serialport close portRef
		end if
		
		if portRef is greater than 0 then
			set donewithit to my unlock()
		end if
		
		if donewithit is false then display notification "Could not unlock"
		
	end if
end run


on unlock()
	set typethis to getPW("testlogin")
	set queryUserLoginState to "python -c 'import sys,Quartz; d=Quartz.CGSessionCopyCurrentDictionary(); print d'"
	
	--sometimes the screen can be locked and unlocked quick enough that a password isn't required (or the password is entered but you haven't pressed return yet), this section makes sure that the password screen is up before entering the password.  Otherwise, your password can end up being entered somewhere where you will never see it, such as an email that you're working on.  Not that this has happened...
	
	tell application "System Events"
		keystroke return
	end tell
	
	set loginTest to do shell script queryUserLoginState
	if loginTest contains "CGSSessionScreenIsLocked = 1" then
		
		--actual password enter section
		tell application "System Events"
			keystroke return
			delay 0.2
			keystroke typethis
			delay 0.2
			keystroke return
		end tell
		return true
	else
		return false
	end if
	
end unlock


on getPW(keychainItemName) --Password needs to be stored manually in the keychain under an appropriate name, i am using testlogin here.
	do shell script "security 2>&1 >/dev/null find-generic-password -gl " & quoted form of keychainItemName & " | awk '{print $2}'"
	return (text 2 thru -2 of result)
end getPW