import jwt from "jsonwebtoken"
import config from "../config.js"


export function jwtMiddleware(req, res, next) {
    try {
        let token = req.headers.authorization
        if (!token) throw new Error("未登录");
        token = token.substr(7); // 裁剪字符串，获取token
        res.payload = checkToken(token);
        next();
    } catch (error) {
        res.err(error.message)
    }
}

export function generateToken(payload) {
    return jwt.sign(payload, config.JWT.SECRET, {
        expiresIn: config.JWT.EXP
    })
}

export function checkToken(token) {
    try {
        const payload = jwt.verify(token, config.JWT.SECRET);
        return payload;
    } catch (error) {
        throw new Error("token验证失败")
    }
}
