LOGGING IN & Controllers Auth.js
Routes With Files
server
├── controllers
│ ├── auth.js
export const login = async (req, res) => {
try {
// Destructure email and password from req.body
const { email, password } = req.body;
// Find the user with the given email
const user = await User.findOne({ email: email });
if (!user) return res.status(400).json({ msg: "User does not exist. " });
// Compare the password with the hashed password in the database
const isMatch = await bcrypt.compare(password, user.password);
if (!isMatch) return res.status(400).json({ msg: "Invalid credentials. " });
// Generate a JWT token and send it to the client
const token = jwt.sign({ id: user._id }, process.env.JWT_SECRET);
delete user.password;
res.status(200).json({ token, user });
} catch (err) {
// Handle any errors that occur during the authentication process
res.status(500).json({ error: err.message });
}
};
Logging In
The login function is responsible for verifying the identity of the user attempting to log in. The function takes in a request object (req) and a response object (res) as arguments.
export const login = async (req, res) => {
Try-catch Block
The first step in the login function is to create a try-catch block. This is to catch any errors that may occur during the execution of the function.
try {
// code goes here
} catch (err) {
res.status(500).json({ error: err.message });
}
Request Body
Next, the function de-structures the email and password values from the request body.
const { email, password } = req.body;
User Verification
After extracting the email and password values, the function verifies the existence of the user. It uses Mongoose, an object data modeling (ODM) library, to query the database and find the user with the specified email.
const user = await User.findOne({ email: email });
if (!user) return res.status(400).json({ msg: "User does not exist. " });
If the user does not exist, the function returns a 400 status code and a "User does not exist" message.
Password Verification
If the user exists, the function uses bcrypt, a password-hashing library, to compare the password entered by the user with the password stored in the database.
const isMatch = await bcrypt.compare(password, user.password);
if (!isMatch) return res.status(400).json({ msg: "Invalid credentials. " });
If the passwords do not match, the function returns a 400 status code and an "Invalid credentials" message.
JWT Token
If the user exists and the password is correct, the function generates a JSON Web Token (JWT). The token is generated using the user's ID and a secret string stored in an environment variable.
const token = jwt.sign({ id: user._id }, process.env.JWT_SECRET);
The JWT token is used to authenticate the user for subsequent requests to the server.
.env
Open the .env file and add the following line. Replace the value with a random string of characters.
JWT_SECRET = 'somesuperhardstringtoguess'
User Deletion
After generating the JWT token, the function deletes the user's password from the user object to prevent it from being sent back to the front end.
delete user.password;
Response
Finally, the function sends a 200 status code and a JSON response containing the JWT token and the user object (without the password).
res.status(200).json({ token, user });
Conclusion
In conclusion, the auth.js script is an essential component of user authentication in a server-side application. The login function verifies the identity of the user attempting to log in and generates a JSON Web Token for authentication. By understanding this script, developers can create secure and robust user authentication systems for their web applications.