Key Expiration

As an additional security measure, the application should periodically delete the password reset keys if they are not used in the specific time frame. The task should be completed automatically. Play Framework’s Scheduled Tasks module will be used to do the job.

Key Model

Add a new expire method to the model.

The model uses the Database utility to delete all documents in the keys collection with the expires timestamp which is before now.

Example: LineDrop Play/Scala Web Application - Key Model

Configuration

Add Tasks Module dependency to the configuration.

Example: LineDrop Play/Scala Web Application - Configuration

Tasks Package

Add a new package to the application for the task classes.

Ctrl-click app and select New - Package.

Enter tasks as the package name and press the Enter key.

Maintenance Task

The Maintenance task will periodically execute the Key Operations’ expire method to delete the keys which have not been used for a span of time defined in the key.duration setting in the configuration.

Expand app, ctrl-click package and select New - Scala Class.

Enter MaintenanceTask in the name field and double-click Class.

If prompted, click Add to add the file to version control.

Browse to the project repository to view the file:

LineDrop Play/Scala Web Application - Maintenance Task

Copy and paste the contents into the new file replacing the original content.

After the application starts, the class will wait for 10 seconds and then will run the code inside the brackets every minute. To change the timing, update the initialDelay and delay parameters.

Tasks Module

Add the TasksModule class to bind the MaintenanceTask to the application.

Expand app, ctrl-click package and select New - Scala Class.

Enter TasksModule in the name field and double-click Class.

If prompted, click Add to add the file to version control.

Browse to the project repository to view the file:

LineDrop Play/Scala Web Application - Tasks Module

Copy and paste the contents into the new file replacing the original content.

Test

Before testing, please make sure that the database and the application are running.

Application Response

Browse to http://localhost:9000.

Log

Logger will have printed the maintenance messages in the Terminal window at the same frequency as the task is executed.

The log has also been written to /logs/application.log in the project’s directory.

Review

...

On the application start, the Maintenance task waits for the initial delay and then starts periodically executing the Key Operations’ expire method.

Commit and Push Changes

Select VCS - Commit from the top menu.

Review the files and directories and enter the commit message.

Click the dropdown arrow on the Commit button and select Commit and Push.

Click Push to confirm.

Reference

Play Framework - Scheduled Tasks - 2.8.x


Next: Error Handling