Hotfix: maxAge cookie 'user' - expires in 1 week

This commit is contained in:
Divlo 2020-04-08 20:15:35 +02:00
parent ca0c77a522
commit 42672399ff
7 changed files with 49 additions and 38 deletions

View File

@ -18,7 +18,8 @@ const config = {
user: process.env.EMAIL_USER, user: process.env.EMAIL_USER,
pass: process.env.EMAIL_PASSWORD pass: process.env.EMAIL_PASSWORD
} }
} },
TOKEN_LIFE: '1 week'
}; };
module.exports = config; module.exports = config;

View File

@ -2,12 +2,12 @@ const path = require('path');
const { validationResult } = require('express-validator'); const { validationResult } = require('express-validator');
const bcrypt = require('bcryptjs'); const bcrypt = require('bcryptjs');
const jwt = require('jsonwebtoken'); const jwt = require('jsonwebtoken');
const ms = require('ms');
const uuid = require('uuid'); const uuid = require('uuid');
const errorHandling = require('../assets/utils/errorHandling'); const errorHandling = require('../assets/utils/errorHandling');
const { serverError, generalError } = require('../assets/config/errors'); const { serverError, generalError } = require('../assets/config/errors');
const { JWT_SECRET, FRONT_END_HOST } = require('../assets/config/config'); const { JWT_SECRET, FRONT_END_HOST, EMAIL_INFO, HOST, TOKEN_LIFE } = require('../assets/config/config');
const transporter = require('../assets/config/transporter'); const transporter = require('../assets/config/transporter');
const { EMAIL_INFO, HOST } = require('../assets/config/config');
const { emailTemplate } = require('../assets/config/emails'); const { emailTemplate } = require('../assets/config/emails');
const Users = require('../models/users'); const Users = require('../models/users');
const Favorites = require('../models/favorites'); const Favorites = require('../models/favorites');
@ -128,8 +128,8 @@ exports.login = async (req, res, next) => {
} }
const token = jwt.sign({ const token = jwt.sign({
email: user.email, userId: user.id email: user.email, userId: user.id
}, JWT_SECRET, { expiresIn: '6h' }); }, JWT_SECRET, { expiresIn: TOKEN_LIFE });
return res.status(200).json({ token, id: user.id, name: user.name, email: user.email, biography: user.biography, logo: user.logo, isPublicEmail: user.isPublicEmail, isAdmin: user.isAdmin, createdAt: user.createdAt }); return res.status(200).json({ token, id: user.id, name: user.name, email: user.email, biography: user.biography, logo: user.logo, isPublicEmail: user.isPublicEmail, isAdmin: user.isAdmin, createdAt: user.createdAt, expiresIn: Math.round(ms(TOKEN_LIFE) / 1000) });
} catch (error) { } catch (error) {
console.log(error); console.log(error);
return errorHandling(next, serverError); return errorHandling(next, serverError);

View File

@ -4,15 +4,15 @@ const Users = require('../models/users');
module.exports = (req, _res, next) => { module.exports = (req, _res, next) => {
if (!req.userId) { if (!req.userId) {
return errorHandling(next, { message: "Vous n'êtes pas connecté.", statusCode: 401 }); return errorHandling(next, { message: "Vous n'êtes pas connecté.", statusCode: 403 });
} }
Users.findOne({ where: { id: req.userId } }) Users.findOne({ where: { id: req.userId } })
.then((user) => { .then((user) => {
if (!user) { if (!user) {
return errorHandling(next, { message: "Le mot de passe ou l'adresse email n'est pas valide.", statusCode: 400 }); return errorHandling(next, { message: "Le mot de passe ou l'adresse email n'est pas valide.", statusCode: 403 });
} }
if (!user.isAdmin) { if (!user.isAdmin) {
return errorHandling(next, { message: "Vous n'êtes pas administrateur.", statusCode: 400 }); return errorHandling(next, { message: "Vous n'êtes pas administrateur.", statusCode: 403 });
} }
next(); next();
}) })

View File

@ -1,23 +1,22 @@
const jwt = require('jsonwebtoken'); const jwt = require('jsonwebtoken');
const errorHandling = require('../assets/utils/errorHandling'); const errorHandling = require('../assets/utils/errorHandling');
const { serverError } = require('../assets/config/errors');
const { JWT_SECRET } = require('../assets/config/config'); const { JWT_SECRET } = require('../assets/config/config');
module.exports = (req, _res, next) => { module.exports = (req, _res, next) => {
const token = req.get('Authorization'); const token = req.get('Authorization');
if (!token) { if (!token) {
return errorHandling(next, { message: "Vous n'êtes pas connecté.", statusCode: 401 }); return errorHandling(next, { message: "Vous devez être connecter pour effectuer cette opération.", statusCode: 403 });
} }
let decodedToken; let decodedToken;
try { try {
decodedToken = jwt.verify(token, JWT_SECRET); decodedToken = jwt.verify(token, JWT_SECRET);
} catch (error) { } catch (error) {
return errorHandling(next, serverError); return errorHandling(next, { message: "Vous devez être connecter pour effectuer cette opération.", statusCode: 403 });
} }
if (!decodedToken) { if (!decodedToken) {
return errorHandling(next, { message: "Vous n'êtes pas connecté.", statusCode: 401 }); return errorHandling(next, { message: "Vous devez être connecter pour effectuer cette opération.", statusCode: 403 });
} }
req.userId = decodedToken.userId; req.userId = decodedToken.userId;

20
api/package-lock.json generated
View File

@ -369,6 +369,13 @@
"integrity": "sha512-bC7ElrdJaJnPbAP+1EotYvqZsb3ecl5wi6Bfi6BJTUcNowp6cvspg0jXznRTKDjm/E7AdgFBVeAPVMNcKGsHMA==", "integrity": "sha512-bC7ElrdJaJnPbAP+1EotYvqZsb3ecl5wi6Bfi6BJTUcNowp6cvspg0jXznRTKDjm/E7AdgFBVeAPVMNcKGsHMA==",
"requires": { "requires": {
"ms": "2.0.0" "ms": "2.0.0"
},
"dependencies": {
"ms": {
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz",
"integrity": "sha1-VgiurfwAvmwpAd9fmGF4jeDVl8g="
}
} }
}, },
"deep-extend": { "deep-extend": {
@ -598,6 +605,13 @@
"integrity": "sha512-OX8XqP7/1a9cqkxYw2yXss15f26NKWBpDXQd0/uK/KPqdQhxbPa994hnzjcE2VqQpDslf55723cKPUOGSmMY3g==", "integrity": "sha512-OX8XqP7/1a9cqkxYw2yXss15f26NKWBpDXQd0/uK/KPqdQhxbPa994hnzjcE2VqQpDslf55723cKPUOGSmMY3g==",
"requires": { "requires": {
"ms": "2.0.0" "ms": "2.0.0"
},
"dependencies": {
"ms": {
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz",
"integrity": "sha1-VgiurfwAvmwpAd9fmGF4jeDVl8g="
}
} }
} }
} }
@ -1127,9 +1141,9 @@
} }
}, },
"ms": { "ms": {
"version": "2.0.0", "version": "2.1.2",
"resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz", "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.2.tgz",
"integrity": "sha1-VgiurfwAvmwpAd9fmGF4jeDVl8g=" "integrity": "sha512-sGkPx+VjMtmA6MX27oA4FBFELFCZZ4S4XqeGOXCv68tT+jb3vk/RyaKWP0PTKyWtmLSM0b+adUTEvbs1PEaH2w=="
}, },
"mysql2": { "mysql2": {
"version": "2.1.0", "version": "2.1.0",

View File

@ -19,6 +19,7 @@
"helmet": "^3.21.3", "helmet": "^3.21.3",
"jsonwebtoken": "^8.5.1", "jsonwebtoken": "^8.5.1",
"moment": "^2.24.0", "moment": "^2.24.0",
"ms": "^2.1.2",
"mysql2": "^2.1.0", "mysql2": "^2.1.0",
"nodemailer": "^6.4.6", "nodemailer": "^6.4.6",
"sequelize": "^5.21.5", "sequelize": "^5.21.5",

View File

@ -35,19 +35,15 @@ function UserContextProvider(props) {
setIsAuth(false); setIsAuth(false);
} }
const changeUserValue = (newUser) => {
cookies.remove('user', { path: '/' });
cookies.set('user', newUser, { path: '/' });
setUser(newUser);
}
const loginUser = ({ email, password }) => { const loginUser = ({ email, password }) => {
setLoginLoading(true); setLoginLoading(true);
return new Promise(async (next) => { return new Promise(async (next) => {
try { try {
const response = await api.post('/users/login', { email, password }); const response = await api.post('/users/login', { email, password });
const newUser = response.data; const newUser = response.data;
changeUserValue(newUser); cookies.remove('user', { path: '/' });
cookies.set('user', newUser, { path: '/', maxAge: newUser.expiresIn });
setUser(newUser);
setIsAuth(true); setIsAuth(true);
setMessageLogin('<p class="form-success"><b>Succès:</b> Connexion réussi!</p>'); setMessageLogin('<p class="form-success"><b>Succès:</b> Connexion réussi!</p>');
setLoginLoading(false); setLoginLoading(false);
@ -63,7 +59,7 @@ function UserContextProvider(props) {
} }
return ( return (
<UserContext.Provider value={{ user, loginUser, logoutUser, loginLoading, messageLogin, isAuth, changeUserValue, setMessageLogin }}> <UserContext.Provider value={{ user, loginUser, logoutUser, loginLoading, messageLogin, isAuth, setMessageLogin }}>
{props.children} {props.children}
</UserContext.Provider> </UserContext.Provider>
); );