Skip to content

Protect routes

LeChatErrant edited this page Dec 18, 2021 · 6 revisions

Authentification

Some routes need the user to be logged in

You can protect such routes with the authMiddleware

import authMiddleware from '../../middlewares/authMiddleware';

router.get(
  '/some-confidential-informations',
  authMiddleware,
  handler(async (req, res) => {
    /*  Here, you are sure the user is logged in*/
  })
);

Roles

Currently, there are two roles: USER and ADMIN

If you want to make a route available to only ADMINs, use the adminMiddleware

import adminMiddleware from '../../middlewares/adminMiddleware';

router.get(
  '/users',
  adminMiddleware,
  handler(async (req, res) => { ... })
);

Ownership

The ownershipMiddleware scopes an API resource to a specific user

It ensures nobody except the user owning the resource can access it, unless admin

Since it needs it, it checks if the user is logged in too

import ownershipMiddleware from '../../middlewares/ownershipMiddleware';

router.get(
  '/users/:userId/resources',
  handler(async (req, res) => {
    /* Any user can GET /users/XXX/resource */
  })
);

router.post(
  '/users/:userId/resources',
  ownershipMiddleware,
  handler(async (req, res) => {
    /* Only the user XXX can POST /users/XXX/resource */
  })
);

Clone this wiki locally