Only require password when waking up from suspend when suspended for 10 minutes

I generally want my laptop to be locked when it's suspended but not when I just suspended it because there is a use case in which entering my password after my laptop woke up from suspend is pretty cumbersome. A good compromise is to only require the login password if the laptop was suspended more than 10 minutes ago. How do I do this?

I use Ubuntu 16.04 with Unity.


Solution 1:

Create a file within /lib/systemd/system-sleep/, named e.g: lightdm:

sudo touch /lib/systemd/system-sleep/lightdm

make this file executable:

sudo chmod +x /lib/systemd/system-sleep/lightdm

Every time you "suspend" or "resume" your Ubuntu, this script going to be run.

Open it using your desired text editor, e.g: sudo nano /lib/systemd/system-sleep/lightdm, and paste this lines into it and then save it:

#!/bin/sh
set -e

case "$1" in
   pre)

    #Store current timestamp (while suspending)
    /bin/echo "$(date +%s)" > /tmp/_suspend 
    ;;

   post)
      #Compute old and current timestamp
      oldts="$(cat /tmp/_suspend)"
      ts="$(date +%s)"

      #Prompt for password if suspended > 10 minutes
      if [ $((ts-oldts)) -ge 600 ];
       then
         export XDG_SEAT_PATH=/org/freedesktop/DisplayManager/Seat0
         /usr/bin/dm-tool lock
      fi

      /bin/rm /tmp/_suspend
   ;;
esac

What it does?

When you are putting your Ubuntu into "sleep" mode this script will save current timestamps, then while resuming system it will check old timestamps with the current one, if the different was more that "600" second (10 Minuets) it's going to show you "lightdm" lock screen otherwise it does nothing.

For the last step:

open "system settings" -> "Brightness & lock". Disable asking password after waking up from suspend, because we leave handling the lock screen to the script.

enter image description here

After reboot or shutdown you still need to enter your password.