code-8
code-8

Reputation: 58632

res.jwt is not a function - NodeJS Express

I kept getting

res.jwt is not a function 

I have installed jwt-express and import it like so

import jwt from 'jwt-express'  

This is my auth.js

import Account from '../services/account.js'
import env from 'dotenv'
import _ from 'lodash'

const dotenv = env.config();

module.exports = {
    /**
     * Process the user login, generating and returning a token if successful.
     *
     * @return {res}
     */
    async login(req, res, next) {
        try {
            let origin = req.headers.origin;
            let accounts = await Account.getAccounts();

            let account = _.find(accounts, {
                'email_address' : req.body.username,
                'password' : req.body.password
            });

            if (!account) {
                res.send('Username/Password Wrong');
            }

            // res.send(account);

            let authentication = res.jwt({
                'email': account.email_address,
                'id': account.account_id
            });
            res.send(authentication);

        } catch (error) {
            next(error)
        }
    }
};

index.js

import express from 'express'
import favicon from 'serve-favicon'
import path from 'path'
import bodyParser from 'body-parser'
import bluebird from 'bluebird'
import jwt from 'jwt-express'
import env from 'dotenv'

//Controllers
import fortinetController from './controllers/fortinet'
import authController from './controllers/auth.js'

//Logger
import logger from './config/logger.js'

//Constant
const router = express.Router();
const app = express();
const PORT = 3000;
const dotenv = env.config();
Promise = bluebird;

app.use(bodyParser.urlencoded({extended: true }));
app.use(bodyParser.json());
app.use(router)
app.use(express.static('public'))
app.use(favicon(path.join(__dirname,'public','favicon.ico')))
app.use(jwt.init('CARWASH', {cookies: false }));


router.get('/', (req,res) => {
    res.send('Welcome to the backend provisioning daemon to program FortiManager')
});

router.post('/login', authController.login);

//Fortinet
router.post('/fortinet/login', fortinetController.login);
router.post('/fortinet/getSessionTimeOut', fortinetController.getSessionTimeOut);
router.post('/fortinet/logout', fortinetController.logout);

//Error handling function
app.use((err,req,res,next) => {
    console.error(err.stack)
    res.status(500).send(`Red alert! Red alert!: ${err.stack}`)
    logger.error(`${req.method} ${req.url} - ${err.log || err.message}`);
});

app.listen(PORT, () => {
        console.log(`Your server is running on ${PORT}`)
    }
);

How can I debug this?


Update

I've tried to add this

console.log(jwt);

I got

[nodemon] 1.17.3                                                                                        
[nodemon] to restart at any time, enter `rs`                                                            
[nodemon] watching: *.*                                                                                 
[nodemon] starting `babel-node ./index.js`                                                              
{ active: [Function: active],                                                                           
  clear: [Function: clear],                                                                             
  create: [Function: create],                                                                           
  init: [Function: init],                                                                               
  options:                                                                                              
   { cookie: 'jwt-express',                                                                             
     cookieOptions: { httpOnly: true },                                                                 
     cookies: false,                                                                                    
     refresh: true,                                                                                     
     reqProperty: 'jwt',                                                                                
     revoke: [Function: revoke],                                                                        
     signOptions: {},                                                                                   
     stales: 900000,                                                                                    
     verify: [Function: verify],                                                                        
     verifyOptions: {} },                                                                               
  require: [Function: require],                                                                         
  valid: [Function: valid] }                                                                            
Your server is running on 3000  

Upvotes: 0

Views: 1153

Answers (1)

Cisco
Cisco

Reputation: 22952

  1. You are not configuring express-jwt correctly.
  2. You are using express-jwt completely wrong.

Let's walk through each point.

I'm not sure why you think you need to call jwt.init(...) when the documentation here states to simply do: jwt(...). So you'll need to make the following changes:

Change

app.use(jwt.init('CARWASH', {cookies: false }));

To

app.use(jwt({secret: 'CARWASH'}));

There does not exist a cookies options, not sure where you got that from.

Now express-jwt will only handle verification of the JWT. It does not generate JWT for as you are trying to do in your auth.js.

In order to generate JWT, you will need another module: jsonwebtoken. You will then use the module in your auth.js like so:

import jwt from "jsonwebtoken";
// ...

module.export = {
    async login(req, res, next) {
        try {
            // ... auth logic omitted

            // Here we generate the JWT
            // Make sure the JWT secret is the SAME secret you used for express-jwt
            let authentication = jwt.sign({
                'email': account.email_address,
                'id': account.account_id
            }, 'CARWASH');
            res.send(authentication);
        }
        catch (error) {
            next(error);
        }
    }
}

Upvotes: 2

Related Questions