import { ERRORENUM } from "../config/errorEnum";
import { findUserByUserId } from "../data/admin/user";
import { BizError } from "../util/bizError";

/**
 * 中间件 校验token
 * @param req 
 * @param res 
 * @param next 
 * @returns 
 */
export async function checkFuHuaQiToken(req, res, next) {
    if (!req.headers) req.headers = {};

    const reqToken = req.headers.token;
    const userId = req.headers.userid || "";

    if (!userId) return next(new BizError(ERRORENUM.身份验证失败, `userId:${userId} token:${reqToken}`));

    let userInfo = await findUserByUserId(userId);
    if (!userInfo) return next(new BizError(ERRORENUM.非法登录, `userId:${userId} token:${reqToken}`));
    
    
    if (userInfo.token != reqToken ) return next(new BizError(ERRORENUM.身份验证过期, `userId:${userId} token:${reqToken}`));

    req.headers.userid = userInfo.userId;

    next();
}

