Nodejs, express and mongodb error

Asked

Viewed 36 times

0

Basically, I am making a route from my API, to exchange a user token, however, this can only change between periods of 14 days.

The route code is like this >

const express = require('express');
const ms = require("parse-ms");

const authMiddleware = require('../middlewares/auth');
const router = express.Router();

const User = require('../../database/Schemas/User');

router.use(authMiddleware);


router.post('/token?:token', (req, res) => {
    let token = req.params.token;

    if(!token) {
        return res.status(200).send({ erro: 'Bad request'});
    }
    User.findOne({ id: req.userID }, (err, user) => {
        const cooldown = 1.21e+6;
        const waitTime = user.waitTime;

        if(!user.token) {
            return res.status(400).send({ erro: "You don't have a token."})
        }

        if(waitTime !== null && cooldown - (Date.now() - waitTime) > 0) {
            let time = ms(cooldown - (Date.now() - daily) > 0);
            let days = time.days;
            let hours = time.hours;
            let minutes = time.minutes;
            let seconds = time.seconds; 
            return res.status(400).send({erro: `Você deve esperar ${days <= 1 ? `1 dia` : `${days} dias`}, ${hours <= 1 ? `1 hora` : `${hours} horas`}, ${minutes <= 1 ? `1 minuto` : `${minutes} minutos`} e ${seconds} segundos para trocar seu token novamente.`})
        } else {
            try {
                const result = User.findOneAndUpdate({ id: req.userData.id}, {$set: {token: token, waitTime: cooldown + Date.now()}}, {new: true})
                return res.status(200).send({ id: req.userData.id, token: result.token})
            } catch (error) {
                return res.status(400).send({ error: 'Error changing token'})
            }
        };
    })
})

module.exports = router;

Already the code of my auth middleware, using JWT, is like this >

const jwt = require('jsonwebtoken');
const authConfig = require('../../config/auth.json');

module.exports = (req, res, next) => {
 const authHeader = req.headers.authorization;

 if (!authHeader)
 return res.status(401).send({ error: 'No token provided' });

 const parts = authHeader.split(' ');

 if (!(parts.length === 2))
 return res.status(401).send({ error: 'Token error' });

 const [ scheme, token ] = parts;

 if (!/Bearer$/i.test(scheme))
 return res.status(401).send({ error: 'Token malformatted' });

jwt.verify(token, authConfig.secret, (err, decoded) => {
    if (err) return res.status(401).send({ error: 'Token invalid' });
    req.userData = decoded;
    return next();
});

};

The funny thing is that it does not return error, only the user ID in JSON and does not change anything in DB, and goes through the check if there is a token.

If anyone can help, thank you!

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.