...

/

Project Setup: Part Two

Project Setup: Part Two

Learn how to set up the controller and router for our project.

Imagine if the user is required to provide their login credentials every time they want to access our recipes. This wouldn’t be an ideal user experience. Instead, let’s have the server issue a JWT to the client when a user signs up for the first time or logs in successfully.

Task 5: Create the users controller

Inside src/controllers/users.js, add route handlers to handle user sign up and log in:

Press + to interact
const { create, authenticate, find } = require("../services/users");
const handleSignup = async (req, res, next) => {
try {
const { name, email, password } = req.body;
const user = await find({ email });
if (user) {
throw new Error("Email already exists!");
}
// Create a token for the user
const { token } = await create({ name, email, password });
// Send a token to the client when a user signs up
res.json({ token });
} catch (error) {
next(error);
}
};
const handleLogin = async (req, res, next) => {
try {
const { email, password } = req.body;
const user = await find({ email });
if (!user) {
throw new Error("Unable to login");
}
// Create a token for the user, if successfully authenticated
const { token } = await authenticate({ email, password });
res.json({ token });
} catch (error) {
next(error);
}
};
module.exports = {
handleSignup,
handleLogin,
};

After the user signs up initially or logs in successfully, the server returns a token to the client that the client can attach to any future requests that need to be authenticated. So, there’s no need for the user to provide their login credentials anymore until the token expires.

Task 6: Create the users router

  1. Inside src/routers/users.js, route the requests to the appropriate controllers:
Press + to interact
const express = require("express");
const { handleSignup, handleLogin } = require("../controllers/users");
const router = express.Router();
router.post("/signup", handleSignup);
router.post("/login", handleLogin);
module.exports = router;
  1. Inside src/index.js, mount the user authentication
...