L
L
low molecular macro2021-08-05 11:19:52
Vue.js
low molecular macro, 2021-08-05 11:19:52

How to protect routes from unlogged users and by roles if JWT is used?

On the server side, I have 2 middleware - protect (logged in?) and restrictTo (has the appropriate role?), which do not allow certain actions to be performed if the site visitor does not have the rights to do so

exports.protect = catchAsync(async (req, res, next) => {
  let token;

  if (
    req.headers.authorization && req.headers.authorization.startsWith("Bearer")
  ) {
    token = req.headers.authorization.split(" ")[1];
  }

  if (!token) {
    return next(new AppError("Вы не вошли в систему!", 401));
  }

  const decodedToken = await promisify(jwt.verify)(
    token,
    process.env.JWT_SECRET
  );

  const currentUser = await User.findById(decodedToken.id);
  if (!currentUser) {
    return next(new AppError("Пользователя с таким токеном больше не существует"));
  }

  req.user = currentUser;
  next();
});


exports.restrictTo = (...roles) => {
  return (req, res, next) => {
    if (!roles.includes(req.user.role)) {
      return next(new AppError("Нет прав для выполнения этого действия", 403));
    }
    next();
  };
};


But how to secure routes on the client side? So that I can't go to the add new entry page if I'm not logged in, for example? Cookies that store the token have the httpOnly flag . This, as far as I understand, will not let me see the token directly from the Vue router. Store in Vuex? But how then to synchronize the state of the token in cookies and in state?
Make a request to a specific endpoint in beforeEach of the Vue router, which in response will say if I can go to the route or not?

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question