const jwt = require("jsonwebtoken");
import {Users} from "../../models/index";
import {tokenPrivateKey} from "../../utils/constans/signUp";
import UserNotFound from "../../utils/customErrors/userNotFound";
import {liveTokenExpires} from "../../utils/constans/signUp";


module.exports = async (req, res, next) => {

    const token = jwt.sign({
        id: req.body.id,
        role: req.body.role
    }, tokenPrivateKey, {expiresIn: liveTokenExpires});

    Users.findOne({
        where: {
            id: req.body.id
        }
    }).then(user => {

        user.update({
            token: token
        });

        req.body.token = token;
        next();

    }).catch(() => {
        res.send(new UserNotFound());
    })
};