Answer the question
In order to leave comments, you need to log in
How to make middleware jwt?
When registering, I have the following code:
const userRegistration = (req, res) => {
try {
if (req.body && req.body.login) {
User.findOne({ where: { login: req.body.login } }).then(r => {
if (r === null) {
const hashedPassword = bcrypt.hashSync(req.body.password, 10);
const token = jwt.sign({ login: req.body.login }, "secret", {
expiresIn: "1h"
});
User.create({
login: req.body.login,
username: req.body.username,
password: hashedPassword,
role: "user"
}).then(() => {
res.json({
status: true,
user: {
login: req.body.login,
username: req.body.username,
token: token,
role: "user"
},
message: "User was created!"
});
});
} else {
res.json({
message: "Body data already taken!"
});
}
});
} else {
res.json({
message: "Body request is incorrect!"
});
}
} catch (error) {
res.json({
message: error
});
}
};
const ProtectedRoute = (req, res, next) => {
let token = req.headers["x-access-token"] || req.headers["authorization"];
if (token) {
if (token.substr(0, 6) === "Bearer") {
token = token.slice(7, token.length);
}
jwt.verify(token, secret, (err, decoded) => {
console.log(decoded);
req.login = decoded;
next();
});
} else {
res.json({
message: "Invalid token!"
});
}
};
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question