DEV Community

Cover image for Day 65 of Learning MERN Stack
Ali Hamza
Ali Hamza

Posted on

Day 65 of Learning MERN Stack

Hello Dev Community! 👋

It is officially Day 65 of my full-stack engineering run! Yesterday, I designed my role-based registration view. Today, I engineered the absolute brain of the authentication lifecycle within my practice sprint: The Post Login Verification Engine using Cryptographic Comparison and Stateful Session Serialization!

Building a login script involves orchestrating precise asynchronous verification checks and handling errors defensively so you don't leak critical vulnerability vectors to intruders. Today, I wired that entire cycle flawlessly inside my controller layer!


🧠 What I Built on Day 65 (Secure Login Architecture)

As showcased in my implementation files in "Screenshot (154).jpg", a secure request loop requires a step-by-step operational strategy:

1. Verification Checking Loops

Inside my exports.postloginpage controller, the engine isolates the inbound email and password payloads from req.body. It issues an initial pinpoint search via User.findOne({ email: email }). If the pointer yields null, it triggers an early exit with an explicit HTTP 422 status payload, returning structured error objects back to the view overlay.

2. Cryptographic Matching (bcrypt.compare)

Instead of testing strings directly, I used await bcrypt.compare(password, user.password). This securely hashes the incoming plain-text credentials and tests them against the salted cryptographic hash string recorded inside my MongoDB database.

3. Session Serialization Mapping

Once the credentials resolve successfully, the server binds the identity map directly onto the stateful wrapper container as req.session.myUser. Instead of storing dangerous data, I serialized clean target properties:


javascript
req.session.myUser = {
    id: user._id.toString(),
    firstname: user.firstname,
    lastname: user.lastname,
    email: user.email,
    usertype: user.usertype
};
req.session.isloggedIn = true;
await req.session.save(); // Forcing persistence before redirection fires
Enter fullscreen mode Exit fullscreen mode

Top comments (0)