В моем NodeJS API я добавил Auth для регистрации / входа пользователя. Вход в систему осуществляется с помощью токена, и когда пользователь вошел в систему, он должен выполнить некоторые операции. На этом этапе res.locals
должен держать пользователя loggedIn
, вместо этого я сразу получаю сообщение об ошибке You need to be logged in to perform this operation
кажется пользователю, когда логин не передается местным жителям, как должно быть. То, что я попробовал, так и дальше. Я создал промежуточное программное обеспечение для проверки зарегистрированного пользователя
// Allow if user logged in
const allowIfLoggedin = async (req, res, next) => {
try {
const user = res.locals.loggedInUser;
if (!user)
throw new ErrorHandlers.ErrorHandler(
401,
"You need to be logged in to perform this operation"
);
// User
req.user = user;
next();
} catch (error) {
next(error);
}
};
На моем сервере. js Я вызывал это до routes
// ENV
const { Config } = require("../config");
// Utilities
const { ErrorHandlers } = require("../utilities");
// JWT
const jwt = require("jsonwebtoken");
// Model
const { User } = require("../models");
// Access token header
const accessToken = async (req, res, next) => {
// Token pass in header
if (req.headers["x-access-token"]) {
// Token from header
const accessToken = req.headers["x-access-token"];
// Token verification with user provided
const { userId, exp } = await jwt.verify(
accessToken,
Config.jwt.secret
);
// Check if token has expired
if (exp < Date.now().valueOf() / 1000) {
throw new ErrorHandlers.ErrorHandler(
401,
"JWT token has expired, please login to obtain a new one"
);
}
// Logged in user find
res.locals.loggedInUser = await User.findById(userId);
next();
} else {
next();
}
};
module.exports = accessToken;
Мои маршруты
// Auth we specify that we only want to grant access to roles
// that are permitted to perform the specified action on the provided resource
// SignUp user register
router.post("/signup", UserAuthCtrl.signup);
// Login user access
router.post("/login", UserAuthCtrl.login);
// GET one user access
router.get(
"/:userId",
Auth.allowIfLoggedin,
UserCtrl.getUser
);
// GET users roles access
router.get(
"/",
Auth.allowIfLoggedin,
Auth.grantAccess("readAny", "profile"),
UserCtrl.getUsers
);
// PUT update user
router.put(
"/:userId",
Auth.allowIfLoggedin,
Auth.grantAccess("updateAny", "profile"),
UserCtrl.updateUser
);
// DELETE user
router.delete(
"/:userId",
Auth.allowIfLoggedin,
Auth.grantAccess("deleteAny", "profile"),
UserCtrl.deleteUser
);