Vibe.d tutorial
  • Build web apps with Vibe.d
  • Setting up
  • The default hello world app
  • Use your own HTML page
  • Serving other static files
  • Diet templates
  • More template pages
  • Use your own functions
  • Templates for ease of maintenance
  • Using include in templates
  • Responsive layout using CSS Grid
  • A fixed navbar and sticky footer
  • CSS modal dialogues
  • The web interface
  • Setting up MySQL server and tools
  • The schema
  • Setting up MySQL for Vibe.d
  • The EmployeeController class
  • The EmployeeModel class
  • A form for adding a new employee
  • Saving form data into the database
  • Testing the whole thing
  • Listing all the employees
  • Retrieving a record for editing
  • Saving form changes to the database
  • Deleting a record from the database
  • Finding an employee record by name
  • Displaying error messages with _error
  • Authentication and authorization
  • Logging in and authentication
  • Saving the login state to the session
  • Enforcing authorization through the session
  • Logging out
  • All the sources so far
  • A new project
    • The timekeeping system
Powered by GitBook
On this page

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.

PreviousAuthentication and authorizationNextSaving the login state to the session

Last updated 5 months ago