How can I resolve an invalid token in js

I am trying to resolve the error. When I verify my touch it marks it as invalid and my req.user as defined

index.js(this is my file)

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>const express = require('express');
const mongoose = require('mongoose');
const bcrypt = require('bcrypt');
const jwt = require('jsonwebtoken');
const { expressjwt: expressJwt } = require('express-jwt');
const User = require('./user');
const jwtSecret = 'mi-string-secreto';
mongoose.connect('mongodb+srv://prprueba37:[email protected]/auth?retryWrites=true&w=majority&appName=Cluster0');
const app = express();
app.use(express.json());
// Middleware para validar el JWT
const validateJwt = expressJwt({
secret: jwtSecret,
algorithms: ['HS256']
});
// Función para firmar el token
const signToken = _id => jwt.sign({ _id }, jwtSecret, { algorithm: 'HS256' });
app.post('/register', async (req, res) => {
const { email, password } = req.body;
try {
const isUser = await User.findOne({ email });
if (isUser) {
return res.status(403).send('Usuario existente');
}
const salt = await bcrypt.genSalt();
const hashed = await bcrypt.hash(password, salt);
const user = await User.create({ email, password: hashed, salt });
const token = signToken(user._id);
res.status(201).send({ token });
} catch (err) {
res.status(500).send(err.message);
}
});
app.post('/login', async (req, res) => {
const { email, password } = req.body;
try {
const user = await User.findOne({ email });
if (!user) {
return res.status(403).send('Usuario y/o contraseña inválida');
}
const isMatch = await bcrypt.compare(password, user.password);
if (isMatch) {
const token = signToken(user._id);
res.status(200).send({ token });
} else {
res.status(403).send('Usuario y/o contraseña incorrecta');
}
} catch (err) {
res.status(500).send(err.message);
}
});
// Ruta protegida que requiere autenticación
app.get('/lele', validateJwt, (req, res) => {
res.send('ok');
});
app.listen(3000, () => {
console.log('Listening on port 3000');
});
</code>
<code>const express = require('express'); const mongoose = require('mongoose'); const bcrypt = require('bcrypt'); const jwt = require('jsonwebtoken'); const { expressjwt: expressJwt } = require('express-jwt'); const User = require('./user'); const jwtSecret = 'mi-string-secreto'; mongoose.connect('mongodb+srv://prprueba37:[email protected]/auth?retryWrites=true&w=majority&appName=Cluster0'); const app = express(); app.use(express.json()); // Middleware para validar el JWT const validateJwt = expressJwt({ secret: jwtSecret, algorithms: ['HS256'] }); // Función para firmar el token const signToken = _id => jwt.sign({ _id }, jwtSecret, { algorithm: 'HS256' }); app.post('/register', async (req, res) => { const { email, password } = req.body; try { const isUser = await User.findOne({ email }); if (isUser) { return res.status(403).send('Usuario existente'); } const salt = await bcrypt.genSalt(); const hashed = await bcrypt.hash(password, salt); const user = await User.create({ email, password: hashed, salt }); const token = signToken(user._id); res.status(201).send({ token }); } catch (err) { res.status(500).send(err.message); } }); app.post('/login', async (req, res) => { const { email, password } = req.body; try { const user = await User.findOne({ email }); if (!user) { return res.status(403).send('Usuario y/o contraseña inválida'); } const isMatch = await bcrypt.compare(password, user.password); if (isMatch) { const token = signToken(user._id); res.status(200).send({ token }); } else { res.status(403).send('Usuario y/o contraseña incorrecta'); } } catch (err) { res.status(500).send(err.message); } }); // Ruta protegida que requiere autenticación app.get('/lele', validateJwt, (req, res) => { res.send('ok'); }); app.listen(3000, () => { console.log('Listening on port 3000'); }); </code>
const express = require('express');
const mongoose = require('mongoose');
const bcrypt = require('bcrypt');
const jwt = require('jsonwebtoken');
const { expressjwt: expressJwt } = require('express-jwt');
const User = require('./user');

const jwtSecret = 'mi-string-secreto';

mongoose.connect('mongodb+srv://prprueba37:[email protected]/auth?retryWrites=true&w=majority&appName=Cluster0');

const app = express();
app.use(express.json());

// Middleware para validar el JWT
const validateJwt = expressJwt({
  secret: jwtSecret,
  algorithms: ['HS256']
});

// Función para firmar el token
const signToken = _id => jwt.sign({ _id }, jwtSecret, { algorithm: 'HS256' });

app.post('/register', async (req, res) => {
  const { email, password } = req.body;

  try {
    const isUser = await User.findOne({ email });
    if (isUser) {
      return res.status(403).send('Usuario existente');
    }
    const salt = await bcrypt.genSalt();
    const hashed = await bcrypt.hash(password, salt);
    const user = await User.create({ email, password: hashed, salt });
    const token = signToken(user._id);
    res.status(201).send({ token });
  } catch (err) {
    res.status(500).send(err.message);
  }
});

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

  try {
    const user = await User.findOne({ email });
    if (!user) {
      return res.status(403).send('Usuario y/o contraseña inválida');
    }
    const isMatch = await bcrypt.compare(password, user.password);
    if (isMatch) {
      const token = signToken(user._id);
      res.status(200).send({ token });
    } else {
      res.status(403).send('Usuario y/o contraseña incorrecta');
    }
  } catch (err) {
    res.status(500).send(err.message);
  }
});

// Ruta protegida que requiere autenticación
app.get('/lele', validateJwt, (req, res) => {
  res.send('ok');
});

app.listen(3000, () => {
  console.log('Listening on port 3000');
});

user.js(this is my schematics file)

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>const mongoose = require('mongoose')
const User = mongoose.model('User', {
email: {type: String, required: true},
password: {type: String, required: true},
salt: {type: String, required: true},
})
module.exports = User
</code>
<code>const mongoose = require('mongoose') const User = mongoose.model('User', { email: {type: String, required: true}, password: {type: String, required: true}, salt: {type: String, required: true}, }) module.exports = User </code>
const mongoose = require('mongoose')

const User = mongoose.model('User', {
    email: {type: String, required: true},
    password: {type: String, required: true},
    salt: {type: String, required: true},
    
})

module.exports = User

I have tried several things but my token is still invalid,
I have the libraries installed but I get some warnings
npm WARN deprecated [email protected]: This module is not supported, and leaks memory. Do not use it. Check out lru-cache if you want a good and tested way to coalesce async requests by a key value, which is much more comprehensive and powerful.
npm WARN deprecated [email protected]: This package is no longer supported.
npm WARN deprecated [email protected]: Rimraf versions prior to v4 are no longer supported
npm WARN deprecated [email protected]: Glob versions prior to v9 are no longer supported
npm WARN deprecated [email protected]: This package is no longer supported.
npm WARN deprecated [email protected]: This package is no longer supported.

New contributor

Prueba Pr is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật