Here, I develop a personal blog backend with node js and express, However, there are problems with authorization

const express = require('express');
const app = express();
const mongoose = require('mongoose');
const path = require('path');
const public = path.join(__dirname, 'public');
const User = require('./models/User.js');
const cors = require('cors');
const jwt = require('jsonwebtoken');
const dotenv = require('dotenv'); 
const cookieParser = require('cookie-parser'); // Import cookie-parser middleware
dotenv.config();

// Body-parser middleware
app.use(express.json());
app.use(express.urlencoded({ extended: false }));

// CORS middleware
app.use(cors());

// Use cookie-parser middleware
app.use(cookieParser());

// Connect to MongoDB
async function main() {
  try {
    await mongoose.connect('mongodb://localhost:27017/securioblog');
  } catch (err) {
    throw err;
  }
}
main();

const userId = User._id; 
const createToken = () => {
  return jwt.sign({ userId }, process.env.JWT_SECRET, { expiresIn: '1h' }); 
}

app.post('/login', async (req, res) => {
  const { username, password } = req.body;
  try {
    const user = await User.findOne({ username, password }).lean();
    if (!user) {
      res.sendFile(path.join(__dirname+'/warning.html'));
    }

    const token = createToken(user._id);

    // Set cookie called "auth" containing the JWT
    res.cookie('auth', token, {
      maxAge: 3600000, // 1 hour
      httpOnly: true, // Prevent client-side JavaScript from accessing the cookie
      secure: true, // Only transmit the cookie over HTTPS if enabled
      sameSite: 'strict' // Only transmit the cookie on requests to the same site as the domain in the cookie
    });

    // Redirect to protected route
    res.redirect('/buffer');
  } catch (error) {
    console.error(error);
    res.sendFile(path.join(__dirname+'/server.html'));
  }
});

const authenticate = async (req, res, next) => {
  try {
    const token = req.cookies.auth;
    if (!token) {
      throw new Error('Authentication failed. Token not found.');
    }

    const decodedToken = await jwt.verify(token, process.env.JWT_SECRET);
    req.user = await User.findById(decodedToken.id);

    next();
  } catch (err) {
    console.log(err);
    res.sendFile(path.join(__dirname+'/token.html'));
  }
};

const dataAuth = async (req,res,next) => {
  try{
    const dataToken = req.headers.authorization.split(" ")[1]; 
    const decodedDataToken = dataToken;
    req.userData = decodedDataToken; 
    next();
  }catch(err){
    res.status(401).json({message: "Auth Failed"}); 
  }


}




app.get('/buffer', authenticate, (req,res) => {
  res.sendFile(path.join(
    __dirname+'/buffer.html'))
})



app.get('/user', dataAuth, async (req, res) => {
  try {
    const users = await User.find(); 
    res.json(users);
  } catch (err) {
    console.error(err);
  }
});


app.get('/composerdashboard', authenticate, (req, res) => {
  res.sendFile(path.join(__dirname+'/compose.html'));
});


app.get('/logout', (req, res) => {
  res.clearCookie('auth');
  res.redirect('/');
});



// Serve static files
app.use('/', express.static(public));

// Start server
app.listen(3000);


here is my code

my authenticate middleware totally works puts a token into cookies and checks

and i want to write an extra middleware for checking is token exists in headers when people fetch data, to protect data routes which is called dataAuth howeever, it seems i wrote middleware right but when i fetch data from protected route without token headers still able to get data which i should not.

here is my front end script too

<script>
	   const token = getCookie('auth');

// Include the token in the headers of the fetch request
const requestOptions = {
  method: 'GET',
  headers: {
	'Content-Type': 'application/json',
	//here i do not pass token variable but still fetching data normally with token ${token} like this it should fetch !!!
	'Authorization': `Bearer `
  }
};

// Make the authenticated request to the protected route
fetch('/user', requestOptions)
  .then(response => response.json())
  .then(data => console.log(data))
  .catch(error => console.error(error));

// Function to get the value of a cookie by name
function getCookie(name) {
  const value = `; ${document.cookie}`;
  const parts = value.split(`; ${name}=`);
  if (parts.length === 2) return parts.pop().split(';').shift();
}
</script>

what i want to do is in some routes i pass user info that existed in my db and fetch that routes in front end for templating for example , Welcome Bla Bla User

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.