auth.js 로그인 라우터
router.post("/login", async (req, res, next) => {
const user = await User.findOne({ where: { name: req.body.name }});
const compare = await bcrypt.compare(req.body.password, user.password);
if (!compare) {
console.log("비밀번호 불일치");
return res.redirect("/");
}
const token = jwt.sign({
name: user.name,
}, process.env.COOKIE_SECRET, {
expiresIn: "1m",
issuer: "test",
});
res.cookie("user", token).redirect("/test");
});
router.get("/test", verifyToken, async (req, res, next) => {
console.log(req.decoded);
res.end();
});
verifyToken 미들웨어
const jwt = require("jsonwebtoken");
exports.verifyToken = (req, res, next) => {
try {
req.decoded = jwt.verify(req.cookies.user, process.env.COOKIE_SECRET);
return next();
} catch (err) {
console.error(err);
}
};