Logging in and authentication

We are going to simplify things. We simply match the email and password combination received from the form to what we have on the admins table to verify the user’s identity. Since the saved password is encrypted, we also have to encrypt the raw password received from the form before comparing them.

Edit source\empcontrol.d and add this method.

  @errorDisplay!index
  void postLogin(string email, string password)
  {
    import vibe.http.auth.digest_auth;
    auto scrambled = createDigestPassword(realm, email, password);
    bool isAdmin = empModel.isAdmin(email, scrambled);
    enforce(isAdmin, "Email and password combination not found.");
    redirect("all_employees");
  }

We used the enforce() function before. The enforce() function is a built-in D function that does nothing if the first parameter is true, and aborts and returns the error message if is false.

Edit source\empmodel.d and add this method.

  bool isAdmin(string email, string password)
  {
    string sql = "select * from admins where email=? and pword=?";
    Prepared pstmt = conn.prepare(sql);
    pstmt.setArgs(email, password);
    Row[] rows = conn.query(pstmt).array;
    if(rows.length == 0) return false;
    return true;
  }

Compile, run and refresh the browser, then try to log in with a random, non-existent admin first and click on the Login button. The index page with an error message should be shown.

Then click on the Login link again and input an existing admin and try to login (remember, ‘secret’ is the password).

If the list of employees is shown, you did good.

Now let’s talk about saving the login state. Let's talk about the session.

Last updated