const jwt = require("jsonwebtoken");
const User = require("../models/userModel");
const catchAsync = require("../utils/catchAsync");
const { promisify } = require("util");
const signToken = (id) => {
return jwt.sign({ id }, process.env.JWT_SECRET, {
expiresIn: process.env.JWT_EXPIRES_IN,
});
};
const createSendToken = (user, statusCode, res, req) => {
const token = signToken(user._id);
res.cookie("jwt", token, {
expires: new Date(
Date.now() + process.env.JWT_COOKIE_EXPIRES_IN * 24 * 60 * 60 * 1000
),
secure: true,
httpOnly: true,
});
//Remove password from output
user.password = undefined;
res.status(statusCode).json({
status: "success",
token,
data: {
user,
},
});
};
exports.register = catchAsync(async (req, res) => {
const { name, email, password, passwordConfirm, role } = req.body;
const newUser = await User.create({
name,
email,
password,
passwordConfirm,
role,
});
createSendToken(newUser, 201, res, req);
});
exports.logIn = catchAsync(async (req, res, next) => {
const { email, password } = req.body;
// 1) Check if email and password exist
if (!email || !password) {
return res
.status(400)
.json({ status: "fail", message: "Please provide email and password!" });
}
// 2) Check if the user exists and if the password is correct
const user = await User.findOne({ email }).select("+password");
if (!user || !(await user.checkPassword(password, user.password))) {
return res
.status(401)
.json({ status: "fail", message: "Incorrect email or password!" });
}
// 3) If everythin is ok, send token to the client
createSendToken(user, 200, res, req);
});
exports.protect = catchAsync(async (req, res, next) => {
// 1) Get the token and check if it exists
let token;
if (
req.headers.authorization &&
req.headers.authorization.startsWith("Bearer")
) {
token = req.headers.authorization.split(" ")[1];
}
if (!token) {
return res.status(401).json({
status: "fail",
message: "You are not logged in! Please log in to get access.",
});
}
// 2) Validate token
let decoded;
try {
decoded = await promisify(jwt.verify)(token, process.env.JWT_SECRET);
} catch (err) {
if (err.name === "JsonWebTokenError")
return res.status(401).json({
status: "fail",
message: "Invalid token. Please log in again!",
});
if (err.name === "TokenExpiredError")
return res.status(401).json({
status: "fail",
message: "Your token has expired. Please log in again!",
});
}
// 3) Check if user still exists
const currentUser = await User.findById(decoded.id);
if (!currentUser) {
return res.status(401).json({
status: "fail",
message: "The user belonging to this token no longer exists.",
});
}
// 4) Check if user changed password after the token was issued
if (currentUser.changedPasswordAfter(decoded.iat)) {
return res.status(401).json({
status: "fail",
message: "User recently changed password! Please log in again.",
});
}
// Everything is passed, go to the protected route.
req.user = currentUser;
next();
});
exports.restrictTo = (...roles) => {
return (req, res, next) => {
if (!roles.includes(req.user.role)) {
return res.status(403).json({
status: "fail",
message: "You do not have permission to perform this action",
});
}
next();
};
};
< /code>
, который просто отправляет данные JSON, когда я публикую на это на фронте. .id, name: user.name, email: user.email};
to createSendToken () req.session.user всегда был не определенным Что исправлено, это было просто удаление createsendToken () и просто выполнение res.redirect во время хранения в req.session.user , но я чувствую, что это не то, как я должен его реализовать, потому что это Ввод меня в систему, даже не сохраняя файл cookie, может ли кто -нибудь сказать мне, как его реализовать, или прислать мне учебник/руководство? Я использую EJS для фронта.
Я пытаюсь подключить свой бэкэнд для входа в систему и зарегистрироваться на фронта, и это моя реализация бэкэнда Auth: < /p> [code]const jwt = require("jsonwebtoken"); const User = require("../models/userModel"); const catchAsync = require("../utils/catchAsync"); const { promisify } = require("util");
// 1) Check if email and password exist if (!email || !password) { return res .status(400) .json({ status: "fail", message: "Please provide email and password!" }); } // 2) Check if the user exists and if the password is correct const user = await User.findOne({ email }).select("+password");
if (!user || !(await user.checkPassword(password, user.password))) { return res .status(401) .json({ status: "fail", message: "Incorrect email or password!" }); }
// 3) If everythin is ok, send token to the client createSendToken(user, 200, res, req); });
exports.protect = catchAsync(async (req, res, next) => { // 1) Get the token and check if it exists let token; if ( req.headers.authorization && req.headers.authorization.startsWith("Bearer") ) { token = req.headers.authorization.split(" ")[1]; }
if (!token) { return res.status(401).json({ status: "fail", message: "You are not logged in! Please log in to get access.", }); } // 2) Validate token let decoded; try { decoded = await promisify(jwt.verify)(token, process.env.JWT_SECRET); } catch (err) { if (err.name === "JsonWebTokenError") return res.status(401).json({ status: "fail", message: "Invalid token. Please log in again!", }); if (err.name === "TokenExpiredError") return res.status(401).json({ status: "fail", message: "Your token has expired. Please log in again!", }); }
// 3) Check if user still exists const currentUser = await User.findById(decoded.id); if (!currentUser) { return res.status(401).json({ status: "fail", message: "The user belonging to this token no longer exists.", }); }
// 4) Check if user changed password after the token was issued if (currentUser.changedPasswordAfter(decoded.iat)) { return res.status(401).json({ status: "fail", message: "User recently changed password! Please log in again.", }); }
// Everything is passed, go to the protected route. req.user = currentUser; next(); });
exports.restrictTo = (...roles) => { return (req, res, next) => { if (!roles.includes(req.user.role)) { return res.status(403).json({ status: "fail", message: "You do not have permission to perform this action", }); }
next(); }; }; < /code> , который просто отправляет данные JSON, когда я публикую на это на фронте. .id, name: user.name, email: user.email}; [/code] to createSendToken () req.session.user всегда был не определенным Что исправлено, это было просто удаление createsendToken () и просто выполнение res.redirect во время хранения в req.session.user , но я чувствую, что это не то, как я должен его реализовать, потому что это Ввод меня в систему, даже не сохраняя файл cookie, может ли кто -нибудь сказать мне, как его реализовать, или прислать мне учебник/руководство? Я использую EJS для фронта.