rasif sahl
rasif sahl

Reputation: 203

I am unable to accesse the authenticated routes in express js

In this when I try to access the api/test route I am redirected to the unauthorized section.

// server.js
const express = require('express');
const passport = require('passport');
const LocalStrategy = require('passport-local').Strategy;
const bcrypt = require('bcrypt');
const session = require('express-session');
const app = express();
const port = 4000;
const cors = require('cors'); // Import the cors middleware
const jwt = require('jsonwebtoken');

// Mock user database
const users = [
  { id: 1, email: '[email protected]', password: '$2b$10$/qyCbk4xtySo4CZQIfwpbunxo1oNQ3.SBdd5uU1YgfhRoIVnDagcm' },
];

app.use(cors({ origin: 'http://localhost:4000', credentials: true }));

// Initialize Passport and express-session
app.use(session({ 
    secret: 'your-secret', 
    resave: true, 
    saveUninitialized: true,
    cookie: { secure: false }, // Set secure to false if not using HTTPS
}));
app.use(express.json());
app.use(passport.initialize());
app.use(passport.session());

// Configure Passport to use LocalStrategy
passport.use(
  new LocalStrategy(
    {
      usernameField: 'email',
      passwordField: 'password',
    },
    async (email, password, done) => {
      const user = users.find((u) => u.email === email);
      if (!user) {
        return done(null, false, { message: 'Incorrect email or password' });
      }
      const passwordMatch = await bcrypt.compare(password, user.password);
      if (!passwordMatch) {
        return done(null, false, { message: 'Incorrect email or password' });
      }
      return done(null, user);
    }
  )
);

// Serialize and deserialize user
passport.serializeUser((user, done) => {
  done(null, user.id);
});

passport.deserializeUser((id, done) => {
  const user = users.find((u) => u.id === id);
  done(null, user);
});

// JWT Secret Key (Change this to a more secure secret)
const JWT_SECRET_KEY = 'your-secret-key';

app.post('/api/login', (req, res, next) => {
    passport.authenticate('local', (err, user) => {
      if (err) {
        return next(err);
      }
      if (!user) {
        return res.status(401).json({ message: 'Incorrect email or password' });
      }
  
      // If authentication is successful, create a JWT token
      const token = jwt.sign({ userId: user.id }, JWT_SECRET_KEY, { expiresIn: '1h' });
      // console.log(token)
  
      // Send the JWT token as a response
      res.json({ message: 'Login successful', token });
    })(req, res, next);
});

app.get('/api/test', (req, res) => {
  console.log(req)
    if (req.isAuthenticated()) {
      res.json({ message: 'This is a test endpoint' });
    } else {
    res.status(401).json({ message: 'Unauthorized' });
  }
});

app.listen(port, () => {
  console.log(`Server is running on port ${port}`);
});

this is the code and also I am getting the req.isAuthenticated() value as isAuthenticated: [Function (anonymous)],

I have checked the authentication middleware structure and also I have tried using the route without authentication when I try it without the authentication it's working.

And in the response header, I was parsing like this. GET {{baseUrl}}/api/test Authorization: Bearer @token

is there anything wrong in this code can someone help me if it is possible.

Upvotes: 0

Views: 40

Answers (1)

Tush
Tush

Reputation: 111

Make sure you access the api/test route after successfully login via the /api/login route. This is because after you login successfully, passport.js will create a session for you. So, afterwards when you try to access the /api/test route, req.isAuthenticated() function will validate the session and will return true.

Probably, you are trying to access the api/test route without the session login and hence req.isAuthenticated() is returning false.

Upvotes: 0

Related Questions