Answer the question
In order to leave comments, you need to log in
What data needs to be written to jwt (node.js + mongo)?
To generate a token I use
jwt = require('jsonwebtoken');
/* далее какой-то код */
//функция для создания токена
function createToken(user) {
return jwt.sign(user, config.secret, { expiresIn: 60*60*5 });
}
/* далее какой-то код */
//после регистрации/авторизации ( в случае успеха) вызывается функция для создания токена
createToken(user);
Answer the question
In order to leave comments, you need to log in
You don't need to put your login into the token. The token should not contain "personal information", but ObjectId is already possible. This does not fit "personally", because by 5821d94dbb021a1360582da3 you can not find out something about the user if your database has not been stolen (I could be wrong).
Just in case, I will give the full code of the route with the issuance of a token, if it is not particularly useful to you, then someone can scold me, since I am not strong in the backend. The code is not on promises, but on callbacks (as in ancient times). This is bad. With the help of promises, the code will be "flatter" and easier to maintain.
const express = require('express')
const router = express.Router()
const User = require('../models/user')
const v4 = require('node-uuid').v4
const jwt = require('jsonwebtoken')
router.post('/signup', (req, res, next) => {
req.check('email', 'Please enter a valid email').len(1).isEmail()
req.check('password', 'Please enter a password with a length between 4 and 34 digits').len(4, 34)
const errors = req.validationErrors()
if (errors) {
return res.status(400).json({ errors })
} else {
User.hashPassword(req.body.password, (err, passwordHash) => {
if (err) {
return res.status(400).json({ error: err.message })
}
const user = new User({
name: req.body.name,
nickname: req.body.nickname,
email: req.body.email,
password: req.body.password,
})
user.passwordHash = passwordHash
user.save((err, item) => {
if (err) {
return res.status(400).json({ error: err.message })
}
const payload = {
_id: item._id,
iss: 'http://localhost:3000',
permissions: 'poll',
}
const options = {
expiresIn: '7d',
jwtid: v4(),
}
const secret = new Buffer(process.env.AUTH0_CLIENT_SECRET, 'base64')
jwt.sign(payload, secret, options, (err, token) => {
return res.json({ data: token })
})
})
})
}
})
router.post('/signin', (req, res, next) => {
req.check('email', 'Please enter a valid email').len(1).isEmail()
req.check('password', 'Please enter a password with a length between 4 and 34 digits').len(4, 34)
const errors = req.validationErrors()
const password = req.body.password
if (errors) {
return res.status(400).json({ errors })
} else {
User.findOne({ email: req.body.email }, (err, user) => {
if (err) {
return res.status(400).json({ error: err.message })
}
if (!user) {
return res.status(400).json({ error: 'User not found' })
}
User.comparePasswordAndHash(password, user.passwordHash, (err, areEqual) => {
if (err) {
return res.status(400).json({ error: err.message })
}
if (!areEqual) {
return res.status(400).json({ error: 'Wrong password' })
}
const payload = {
_id: user._id,
iss: 'http://localhost:3000',
permissions: 'poll',
}
const options = {
expiresIn: '7d',
jwtid: v4(),
}
const secret = new Buffer(process.env.AUTH0_CLIENT_SECRET, 'base64')
jwt.sign(payload, secret, options, (err, token) => {
return res.json({ data: token })
})
})
})
}
})
module.exports = router;
const payload = {
_id: item._id,
iss: 'http://localhost:3000',
permissions: 'poll',
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question