Skip to content

[Enhance] Improve login to include both 400 and 401 #51

@gbowne1

Description

@gbowne1

So, http 444 is a Nginx specific error. To fix this, we should use 400 and 401 in the login object and handle both cases individually.

Something like;

export const login = async (req, res) => {
    const { email, password } = req.body;

    // 400 Bad Request: The client forgot to send data
    if (!email || !password) {
        return res.status(400).json({ message: 'Please enter email and password.' });
    }

    try {
        const user = await User.findOne({ email });
        
        // 401 Unauthorized: The credentials don't match our records
        if (!user) {
            return res.status(401).json({ message: 'Invalid Credentials.' });
        }

        const isMatch = await bcrypt.compare(password, user.password);
        
        // 401 Unauthorized: User exists, but the password is wrong
        if (!isMatch) {
            return res.status(401).json({ message: 'Invalid Credentials.' });
        }

        // ... rest of the JWT logic
        const token = jwt.sign({ id: user.id, role: user.role }, JWT_SECRET, { expiresIn: '1d' });

        res.json({ token, user: { id: user.id, username: user.username, email: user.email } });

    } catch (err) {
        console.error(err.message);
        res.status(500).send('Server error');
    }
};

Also, 1 day is pretty long for a token expired

Handle both conditions in the frontend with something like

const response = await fetch('/api/auth/login', { /* ... */ });

if (response.status === 400) {
    showToast("Please fill out all fields.");
} else if (response.status === 401) {
    showToast("Incorrect email or password.");
} else if (response.ok) {
    const data = await response.json();
    localStorage.setItem('token', data.token);
    // Redirect to home
}

Then fix the middleware so that it redirects back to login if token expired on 401

Metadata

Metadata

Assignees

Labels

bugSomething isn't workingenhancementNew feature or requestgood first issueGood for newcomershelp wantedExtra attention is neededquestionFurther information is requested

Projects

Status

Done

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions