Enforcing authorization through the session

We want to restrict access to all the pages in the app except the home page and the login page, but right now, clicking any of the links on the menu shows the page. Meaning, all the links in the menu is available and is viewable by anyone. We need to rectify that.

Only the home page and the login page should be accessible to anyone and the rest should be accessible only to logged-in users. We should add a way to check if the user is logged in before deciding to open a page.

Edit source\empcontrol.d and add this code at the end.

  private enum auth = before!ensureAuth("_authUser");
  private string ensureAuth(HTTPServerRequest req, HTTPServerResponse res)
  {
    if(!m_user.loggedIn) redirect("index");
    return m_user.email;
  }
  mixin PrivateAccessProxy;

The @auth annotation is a shortcut for calling the ensureAuth() method to check if the user is logged in before running a method.

That mixin statement there is needed to make this private function accessible.

This function redirects to the index() method if the user is not logged in yet.

Then we defined a shortcut to the ensureAuth() function with this:

private enum auth = before!ensureAuth("_authUser");

so we can just use auth to mean we are calling the ensureAuth() private function, like this:

  @auth 
  void getAddEmployee(string _error = null)

The @auth annotation calls the ensureAuth() function, which checks the logged-in state, before running this getAddEmployee() method.

Since the ensureAuth() function is receiving an _authUser variable, we now have to add it as an argument to all the methods that call ensureAuth(), like this:

  @auth 
  void getAddEmployee(string _authUser, string _error = null)

We should add the @auth annotation to each method that requires authorization.

We did not make any changes to the source\empmodel.d, so we are good.

Compile, run and refresh the browser. Click any link on the menu except the Login link and you should be redirected to the home (index) page.

However, once you logged in, you will be able to visit all the pages.

Now we are assured that sensitive data is protected and accessible only to authorized users.

How let's talk about logging out,.

Last updated