DEV Community

Seif Ahmed
Seif Ahmed

Posted on Edited on AI-assisted

Building a Secure Authentication System

I was wondering how I'd add a proper auth system in Vlox. So, I searched different resources and found this great method. And now, I'm going to share it with you guys.


The Logic

1. Database Lookup

When a user submits their credentials, the system queries MongoDB to locate the user profile.

  • Method: findOne({ username }) via Mongoose.
  • Security Rule: If the username does not exist, stop execution and return unauthorized status immediately.

2. Password Verification

If the user account exists, the system compares the plain text input password against the hashed password stored in the database.

  • Method: await bcrypt.compare(password, user.password).
  • Security Rule: If the comparison returns false, stop executiob and return unauthorized status again.

3. Session Management

Once both checks pass, the system init a secure session to keep the user authenticated across subsequent requests.

  • State Flags:
    • req.session.isLoggedIn = true
    • req.session.userId = user._id
  • Response: Return a 200 OK status with a success message.

Security Best Practices:

  • Generic Error Messages: Both missing usernames and incorrect passwords return the exact same message: "Invalid username or password". This prevents attackers from brute-forcing valid usernames.
  • Cryptographic Hashing: Passwords are never stored or compared in plain text. Bcrypt handles salt generation to protect against rainbow table attacks.
  • Stateful Sessions: Using server-side sessions keeps user identity secure and reduces the risk of token theft common in purely client-side storage.

If you found this article helpful, please consider giving it a ❤️! Thanks for reading!

Top comments (0)