Secure Access

Since subscriber data contains personally identifiable information about our customers, we would like it to be accessible only to authenticated users.

First, we need to know if a user has a current session. That is, a user has signed in, the application has issued a session token, and the browser stored the token in a cookie.

When a request is made by the browser, a cookie is added to the header of the request. Earlier, we used withSession modifier to store the session token in a cookie:

Reading the value from the request is simple. The value is returned as Option[String].

Once the session token is read, it can be validated and then used to find the user to whom the session token belongs. If the token is null or the session does not exist, the application will deny access to the resource.

Session Model

Add a method to the Session model to validate a session token.

The method uses the Database utility to find a session document by the token. If a document matching the search criteria is found, an instance of a session object is created and returned as Some(Session); otherwise None is returned.

Example: LineDrop Play/Scala Web Application - Session Model

User Model

Add a method to the User model to authenticate the user by the session token (cookie).

The method accepts Option[String] as a parameter which will be the result of request.session.get(“session”).

If the token exists, Session Operations’ validate method is invoked. A valid session is then used to find the user by the email address stored in the session object. Some(User) is returned if all conditions are met; otherwise, None is returned.

Example: LineDrop Play/Scala Web Application - User Model

Dashboard Controller

Update the subscribe method to render the view only if the user has been authenticated.

Test

Application Response

Browse to http://localhost:9000/signout to sign out. The application redirects to http://localhost:9000/signin.

Enter valid email and password and click Sign In.

Log

Logger will have printed debug messages in the Terminal window. The log has also been written to /logs/application.log in the project’s directory.

Review

...

The request is routed to Dashboard controller’s subscribers method. The method gets the token from the request as an Option[String] and passes it User Operations’ authenticate_from_cookie method. If the token exists, Session Operations’ validate method is invoked and, if the session is valid, the user is located by the email address stored in the session. Subscribers view is rendered if all conditions are met; otherwise, Dashboard controller redirects the request to the Sign In view.

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.


Next: Subscriber Management