code refactoring

This commit is contained in:
Alessandro Ferro
2024-02-20 15:50:37 +01:00
parent bb64ccf7e3
commit 18be287a04
6 changed files with 366 additions and 331 deletions

View File

@ -0,0 +1,37 @@
const jwt = require('jsonwebtoken');
function generateToken(person_id) {
// The payload the JWT will carry within itself
const payload = {
person_id: person_id
};
const token = jwt.sign(payload, process.env.JWT_SECRET_KEY, {
expiresIn: '8h'
});
return token;
}
// Middlware
function verifyToken(req, res, next) {
const token = req.headers.authorization;
if (!token) {
return res.status(401).send({error : 'No token provided'});
}
jwt.verify(token, process.env.JWT_SECRET_KEY, (err, decoded) => {
if (err) {
return res.status(401).send({error : 'Failed to authenticate token'});
}
// If the token is valid, store the decoded data in the request object
req.jwt = decoded;
next();
});
}
module.exports = {
generateToken,
verifyToken
};

View File

@ -0,0 +1,25 @@
/**
* Checks whether an e-mail is in a valid format
* @param {*} email email to validate
* @returns true or false
*/
function validateEmail(email) {
const regex = /^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}$/;
return regex.test(email);
}
/**
* Checks whether a date is in a correct Postgres
* format (YYYY-MM-DD)
* @param {*} dateString the date to validate
* @returns true or false
*/
function isPostgresDateFormatValid(dateString) {
const regex = /^\d{4}-\d{2}-\d{2}$/;
return regex.test(dateString);
}
module.exports = {
validateEmail,
isPostgresDateFormatValid
};