JWT error cannot read properties of undefined. req.user is always undefined after authenticate middleware

Viewed 105

I'm trying to create a redirect to the main dashboard by authorizing the token saved in sessionStorage from a new registration or login. However, it seems that the authentication fails every time. It seems the error is because in the authenticate middleware, req.user = decoded is always undefined for some reason, but not sure why.

undefined
TypeError: Cannot read properties of undefined (reading 'where')
    at exports.current (C:\Users\shmue\Desktop\AutoMotionParking\server\controllers\currentController.js:10:9)

here's the client-side Dashboard.js:

import axios from 'axios';
import React, { useState, useEffect} from 'react';
import {Link} from 'react-router-dom';
import './DashboardPage.scss';

function DashboardPage(){

    const API_KEY = 'd7740a55001340a7b39145833220706';
    const [currUser, setCurrUser] = useState('null');
    const [userInput, setUserInput] = useState('');
    const [location, setLocation] = useState(null);
    const [locationData, setlocationData] = useState(null);
    const [maxSortedLowToHi, setMaxSortedLowToHi] = useState(false);
    const [minSortedLowToHi, setMinSortedLowToHi] = useState(false);
    const [rainfallLowToHi, setRainfallLowToHi] = useState(false);
    const [todaysDateFirst, setTodaysDateFirst] = useState(true)
    const [failedAuth, setFailedAuth] = useState(false);

    useEffect(() => {
        const token = sessionStorage.getItem('token');
        if (!token) {
            setFailedAuth(true);
            return;
        }
        // Get the data from the API
        axios
            .get('http://localhost:8080/current', {
                headers: {
                    authorization: 'Bearer ' + token
                }
            })
            .then((response) => {
                console.log(response);
                setCurrUser(response.data.name);
            })
            .catch(() => {
                setFailedAuth(true);
            });
    }, []);

here's the server-side routing

index.js file

require('dotenv').config();
const express = require('express');
const cors = require('cors');
const app = express();
const registerRoute = require('./routes/registerRoute');
const currentRoute = require('./routes/currentRoute');
const loginRoute = require('./routes/loginRoute');
const port = 8080;

//middleware
app.use(cors());
app.use(express.json());

//Routes
app.use('/register', registerRoute);
app.use('/current', currentRoute);
app.use('/login', loginRoute);


//port listener
app.listen(port, () => {
  console.log(`Example app listening on port ${port}`)
})

currentRoute.js file

const router = require('express').Router();
const currentController = require('../controllers/currentController');

router
    .route('/')
    .get(currentController.current);

module.exports = router;

currentController.js is the file that checks if the current user trying to access the main dashboard is authenticated

const knex = require('knex')(require('../knexfile'));
const authenticate = require('../middleware/authenticate');

// [ROUTE] - "/auth/current"
// [GET] - Gets currently logged in user to validate JWT authentication
exports.current = (authenticate, (req, res) => {
  
    knex('users')
        console.log(req.user) ***prints undefined***
        .where({ email: req.user.email })
        .first()
        .then((user) => {
            // Respond with the user data
            delete user.password;
            res.json(user);
        });
});

authenticate middleware

const jwt = require('jsonwebtoken');
const authenticate = (req, res, next) => {
    // If there is no auth header provided
    if (!req.headers.authorization) {
        return res.status(401).send("Please login");
    }

    // Parse the Bearer token
    const authToken = req.headers.authorization.split(" ")[1];
    
    // Verify the token
    jwt.verify(authToken, process.env.JWT_KEY, (err, decoded) => {
        // Sends 401 status if JWT not valid
        if (err) {
            return res.status(401).send("Invalid auth token");
        } 
        req.user = decoded;
        next();
    })

}
module.exports = authenticate;
0 Answers
Related