fyardlest
fyardlest

Reputation: 298

Why my API is not working anymor after using JWT?

I am creating an API back-end for my front-end application. Everything was working fine when testing GET and POST requests in Postman. But right after I try to make it secure it does not work anymore, the requests are running, running... and return nothing, not even and error message. I create a jwt.js:

const expressJwt = require('express-jwt');

// creating the function
const authJwt = () => {
    // use the secret
    const secret = process.env.secret_key;

    // returning expressJwt to use the secret and the algorithms
    return expressJwt({
        secret,
        algorithms: ['HS256']
    })
}

module.exports = authJwt;

I update my index.js with the following:

const authJwt = require('./helpers/jwt');
app.use(authJwt);

I create the get request as the following:

// getting the list of users
router.get(`/`, async (req, res) =>{
    const userList = await User.find().select('-passwordHash');

    if(!userList) {
        res.status(500).json({success: false})
    }
    
    return res.status(200).send(userList)
})

And finally, I create the post request for the login:

// login the user api
router.post(`/login`, async (req, res) => {
    const { email, password } = req.body;

    const user = await User.findOne({ email });

    if (!user)
        return res.status(404).send({ message: 'User was not found' })
    
    if (user && bcrypt.compareSync(password, user.passwordHash)) {
        const secret = process.env.secret_key

        const token = jwt.sign(
            {
                userId: user.id,
            },
            secret,
            { expiresIn: '1d' }
        )

        return res.status(200).send({ user: user.email, token: token })
    } else {
        return res.status(404).send({ message: 'Wrong email or password' })
    }    
})

Upvotes: 0

Views: 412

Answers (1)

Bergur
Bergur

Reputation: 4057

You are defining a function authJwt but never invoking it.

Change

app.use(authJwt);

To

app.use(authJwt());

Before you were just passing it in, now you're invoking it, returning the expressJWT middlewere.

Upvotes: 1

Related Questions