Step 11

Applying auth middleware to book routes

Finally, let's use our auth middleware to guard some of our routes.

src/routes/books.js

const express = require('express');
const { auth } = require('../middleware/passport');
const Book = require('../models/book');
const router = express.Router();

router.get('/', async (req, res) => {
	const books = await Book.findAll();
	res.send(books);
});

router.post('/', auth(), async (req, res) => {
	const { title, author } = req.body;
	if (!title) return res.status(400).send('Please provide a title');
	if (!author) return res.status(400).send('Please provide a author');

	const newBook = await Book.create({ title, author });
	res.send(newBook);
});

router.get('/:id', async (req, res) => {
	const { id } = req.params;
	const book = await Book.findById(id);
	if (!book) return res.status(404).send(`Book with ID: ${id} does not exist!`);

	res.send(book);
});

router.put('/:id', auth(), async (req, res) => {
	const { id } = req.params;
	const { title, author } = req.body;

	const book = await Book.findById(id);
	if (!book) return res.status(400).send(`Book with ID: ${id} does not exist!`);

	if (title) book.title = title;
	if (author) book.author = author;
	await book.save();

	res.send(book);
});

router.delete('/:id', auth(), async (req, res) => {
	const { id } = req.params;
	const book = await Book.findById(id);
	if (!book) return res.status(404).send(`Book with ID: ${id} does not exist!`);

	const removedBook = await book.destroy();
	res.send(removedBook);
});

module.exports = router;

For the routes that mutate the state of our books, we call "auth()" function to activate our middleware for that particular route. When an HTTP request is intercepted by a route with our auth middleware, we check to see if there is a user property on the "req" parameter. If there is, we proceed to execute the logic of our route handler, but if not, we return "Unauthorized" to the user.

Last updated

Was this helpful?