# data[].attributes.attachment_link.readable_text
const jwt = require('jsonwebtoken');
require('dotenv').config();
module.exports = async function isAuthenticated(req, res, next) {
  //const token = req.headers['authorization']?.split(' ')[1]; //je l'ai remplacé par l'instruction qui suit
  const token = req.headers.authorization;
  jwt.verify(token, process.env.JWT_SECRET, (err, user) => {
    if (err) {
      return res.status(401).json({ message: err });
    } else {
      req.user = user;
      next();
    }
  });
};

# data[].attributes.attachment_link.readable_text
to set 'PORT_ONE' variable =>

Using a .env file:

-Create a file named .env in the same directory as your script.

-Inside the .env file, set the PORT_ONE variable:
PORT_ONE=3000

-Then, you can use a package like dotenv to load the variables from the .env file before running your script. 
  =>To do this, you need to install the dotenv package by running: 
    npm install dotenv.
-In your script, add the following line at the top to load the variables:
require('dotenv').config();

After loading the variables, you can access process.env.PORT_ONE as usual.

# data[].attributes.attachment_link.readable_text
const bcrypt = require('bcrypt');
const fixedsalt= '$2b$10$J9p8h1TEhTN6hjkf0p6f2O';
// Generate a salt and hash the plain password
/*
en fournissant un 'fixedsalt' en deuxième argument, la fonction hash() renvoie le même retour pour une 
chaine donnée car sinon, elle générera à chaque fois un 'salt' différent, ce qui entrainera une valeur 
de retour différente à chaque fois pour la même chaine d'entrée
*/ 
bcrypt.hash("plainPassword", fixedsalt) 
  .then(hashedPassword => { // hashedPassword : représente le haché de la chaine : "plainPassword"
    console.log('Hashed password:', hashedPassword);

    // Comparing passwords
    //compare() procèdera au hachage de la chaine : "plainPassword"; puis, elle la compare avec la chaine : hashedPassword
    bcrypt.compare("plainPassword", hashedPassword)
      .then(isMatch => {
        if (isMatch) {
          console.log('Password match!');
        } else {
          console.log('Password does not match!');
        }
      })
      .catch(error => {
        console.error('Error comparing passwords:', error);
      });
  })
  .catch(error => {
    console.error('Error hashing password:', error);
  });

# data[].attributes.attachment_link.readable_text
const express = require('express');
const bcrypt = require('bcrypt');
const jwt = require('jsonwebtoken');

const app = express();

// Middleware to parse JSON body
app.use(express.json());

// Mock User Model
const users = [
  {
    id: 1,
    name: 'karimi',
    email: 'karimi@example.com',
    password: '$2b$10$J9p8h1TEhTN6hjkf0p6f2Of5WV3ISvw7CFVzuHHYhwMsG6hnr3Lc6' // Hashed password: "password"
  }
];

// Authentication Middleware
const authenticateToken = (req, res, next) => {
  // Retrieve the token from the request headers
  const token = req.headers.authorization;
  //res.send(token);
  if (!token) {
    return res.status(401).json({ error: 'Token not found' });
  }

  try {
    // Verify the token using the secret key
    const decoded = jwt.verify(token, 'SECRET_KEY');
    
    req.user = decoded; // Set the user data in the request object
    next(); // Continue to the next middleware or route handler
  } catch (error) {
    return res.status(403).json({ error: 'Invalid token' });
  }
};

// Login Route
app.post('/login', (req, res) => {
  const { email, password } = req.body;

  // Find user by email
  const user = users.find(user => user.email === email);
  if (!user) {
    return res.status(401).json({ error: 'User not found!' });
  }

  // Compare password using bcrypt
  bcrypt.compare(password, user.password)
    .then(isMatch => {
      if (!isMatch) {
        return res.status(401).json({ error: 'Incorrect password!' });
      }

      // Generate JWT token
      const token = jwt.sign({ userIdentifier: user.email }, 'SECRET_KEY', { expiresIn: '1h' });

      res.status(200).json({ token });
    })
    .catch(error => res.status(500).json({ error }));
});

// Protected Route
//to test in in postman => n the request header section, add a new header with the key : 'Authorization' and the value : 'your_token_here'; 'your_token_here' => the string in token object
app.get('/protected', authenticateToken, (req, res) => {
  // Access the authenticated user's data from req.user
  const userId = req.user.userIdentifier;
  //res.json(req.user); => {"userIdentifier": "karimi@example.com","iat": 1686074481,"exp": 1686078081}
  res.json({ message: 'Access granted to protected route', userId });
});

// Unprotected Route
app.get('/unprotected', (req, res) => {
  res.json({ message: 'Access granted to unprotected route' });
});

// Start the server
app.listen(3005, () => {
  console.log('Server started on port 3005');
});

# data[].attributes.attachment_link.readable_text
const express = require('express');
const bcrypt = require('bcrypt');
const jwt = require('jsonwebtoken');

const app = express();

const fixedsalt = '$2b$10$J9p8h1TEhTN6hjkf0p6f2O';

// Middleware to parse JSON body
app.use(express.json());

// Mock User Model
const users = [];
let hashed="";
bcrypt.hash("karimi@523", fixedsalt)
  .then(hashedPassword => {
    hashed = hashedPassword;
    // Create user object with hashed password
    const user = {
      id: 1,
      name: 'karimi',
      email: 'karimi@example.com',
      password: hashedPassword
    };

    // Add user to users array
    users.push(user);

    // Start the server after the user has been created
    app.listen(3004, () => {
      console.log('Server started on port 3004');
    });
  })
  .catch(error => {
    console.error('Error hashing password:', error);
  });

// Login Route
app.post('/login', (req, res) => {
  const { email, password } = req.body;
  //res.send(hashed);
  // Find user by email
  const user = users.find(user => user.email == email);
  if (!user) {
    return res.status(401).json({ error: 'User not found!' });
  }

  // Compare password using bcrypt
  bcrypt.compare(password, user.password)
    .then(isMatch => {
      if (!isMatch) {
        return res.status(401).json({ error: 'Incorrect password!' });
      }
      
      // Generate JWT token
      const token = jwt.sign({ userId: user.id }, 'SECRET_KEY', { expiresIn: '1h' });

      res.status(200).json({ message:'successful authentication', token });
    })
    .catch(error => res.status(500).json({ error }));
});

