A
A
Alexander Yakovlev2022-02-24 18:58:36
JavaScript
Alexander Yakovlev, 2022-02-24 18:58:36

Why is a 403 code displayed on page reload?

I have a middleware that checks if the administrator is logged in and if he exists:

import jwtDecode from 'jwt-decode';

const Admin = require("../models/Admin");

module.exports = async (req, res, next) => {
  try {
    const auth = req.headers.authorization;

    if (auth) {
      const token = auth.split(' ')[1];

      if (token) {
        const { _doc: { _id } } = jwtDecode(token);
        const candidate = await Admin.findById(_id);

        req.isAdmin = Boolean(candidate);
      } else {
        req.isAdmin = false;
      }
    } else {
      req.isAdmin = false;
    }

    next();
  } catch (err) {
    console.log(err);

    return res.status(500).json({ ok: false, message: "Произошла ошибка сервера" });
  }
}


This only happens on one page: the order page.

When I navigate through the pages, including this one, everything is fine, but if I reload this page, this is displayed:
{
 ok: false,
 message: "У вас нет доступа"
}


And the middleware shows that auth is undefined.

Receiving orders:
router.get("/orders", isAdmin, async (req, res) => {
  try {
    if (req.isAdmin) {
      const orders = await Order.find();

      return res.status(200).json({ ok: true, orders });
    } else {
      return res.status(403).json({ ok: false, message: "У вас нет доступа" });
    }
  } catch (err) {
    console.log(err);

    return res.status(500).json({ ok: false, message: "Произошла ошибка сервера" });
  }
});

Answer the question

In order to leave comments, you need to log in

1 answer(s)
I
Ivan Kulakov, 2022-02-24
@ivankprod

Show the code that is responsible for successful authorization. It looks like your sessions are not being established.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question