const jwt = require("jsonwebtoken");

const {
    secret: tokenSecret,
} = require("../conf/config.json").secure.jwt;

const authMiddleware = (req, res, next) => {
    try {
        const token = req.cookies.auth_token;

        if (!token) {
            return res.status(401).json({
                ok: false,
                message: "토큰이 없습니다.",
            });
        }

        const decoded = jwt.verify(token, tokenSecret);

        req.user = decoded;

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

        return res.status(401).json({
            ok: false,
            message: "유효하지 않은 토큰입니다.",
        });
    }
};

module.exports = authMiddleware;