From db3f940da5727cc44d36bc5e7237e5d70b100eb0 Mon Sep 17 00:00:00 2001 From: Divlo Date: Sat, 2 May 2020 15:51:51 +0200 Subject: [PATCH] =?UTF-8?q?=F0=9F=93=A6=20NEW:=20GET=20/users?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- api/controllers/functions.js | 2 +- api/controllers/users.js | 21 ++++++ api/routes/users.js | 137 ++++++++++++++++++----------------- 3 files changed, 94 insertions(+), 66 deletions(-) diff --git a/api/controllers/functions.js b/api/controllers/functions.js index 219de83..36c9728 100644 --- a/api/controllers/functions.js +++ b/api/controllers/functions.js @@ -9,7 +9,7 @@ const Sequelize = require('sequelize'); exports.getFunctions = async (req, res, next) => { const categoryId = helperQueryNumber(req.query.categoryId, 0); - let search = req.query.search; + let { search } = req.query; try { search = search.toLowerCase(); } catch {}; const options = { where: { diff --git a/api/controllers/users.js b/api/controllers/users.js index c40ebee..3629958 100644 --- a/api/controllers/users.js +++ b/api/controllers/users.js @@ -4,6 +4,7 @@ const bcrypt = require('bc const jwt = require('jsonwebtoken'); const ms = require('ms'); const uuid = require('uuid'); +const Sequelize = require('sequelize'); const errorHandling = require('../assets/utils/errorHandling'); const { serverError, generalError } = require('../assets/config/errors'); const { JWT_SECRET, FRONT_END_HOST, EMAIL_INFO, HOST, TOKEN_LIFE } = require('../assets/config/config'); @@ -16,6 +17,7 @@ const Categories = require('.. const Comments = require('../models/comments'); const Quotes = require('../models/quotes'); const deleteFilesNameStartWith = require('../assets/utils/deleteFilesNameStartWith'); +const getPagesHelper = require('../assets/utils/getPagesHelper'); async function handleEditUser(res, { name, email, biography, isPublicEmail }, userId, logoName) { const user = await Users.findOne({ where: { id: userId } }); @@ -43,6 +45,25 @@ async function handleEditUser(res, { name, email, biography, isPublicEmail }, us return res.status(200).json({ id: user.id, name: user.name, email: user.email, biography: user.biography, logo: user.logo, isPublicEmail: user.isPublicEmail, isAdmin: user.isAdmin, createdAt: user.createdAt }); } +exports.getUsers = async (req, res, next) => { + let { search } = req.query; + try { search = search.toLowerCase(); } catch {}; + const options = { + where: { + isConfirmed: true, + // Recherche + ...(search != undefined) && { + name: Sequelize.where(Sequelize.fn('LOWER', Sequelize.col('name')), 'LIKE', `%${search}%`) + } + }, + attributes: { + exclude: ["updatedAt", "isAdmin", "isConfirmed", "password", "tempToken", "tempExpirationToken", "isPublicEmail", "email"] + }, + order: [['createdAt', 'DESC']] + }; + return await getPagesHelper({ req, res, next }, Users, options); +} + exports.putUser = async (req, res, next) => { const { name, email, biography, isPublicEmail } = req.body; const logo = req.files.logo; diff --git a/api/routes/users.js b/api/routes/users.js index 584d0fa..d3736a7 100644 --- a/api/routes/users.js +++ b/api/routes/users.js @@ -8,6 +8,64 @@ const isAuth = require('../middlewares/isAuth'); const UsersRouter = Router(); +UsersRouter.route('/') + + // Récupère les utilisateurs + .get(usersController.getUsers) + + // Permet de modifier son profil + .put(isAuth, + fileUpload({ + useTempFiles: true, + safeFileNames: true, + preserveExtension: Number, + limits: { fileSize: 5 * 1024 * 1024 }, // 5mb, + parseNested: true + }), + [ + body('email') + .isEmail() + .withMessage("Veuillez rentré une adresse mail valide.") + .custom((async (email) => { + try { + const user = await Users.findOne({ where: { email } }); + if (user && user.email !== email) { + return Promise.reject("L'adresse email existe déjà..."); + } + } catch (error) { + return console.log(error); + } + return true; + })) + .normalizeEmail(), + body('name') + .trim() + .not() + .isEmpty() + .withMessage("Vous devez avoir un nom (ou pseudo).") + .isAlphanumeric() + .withMessage("Votre nom ne peut contenir que des lettres ou/et des nombres.") + .isLength({ max: 30 }) + .withMessage("Votre nom est trop long") + .custom(async (name) => { + try { + const user = await Users.findOne({ where: { name } }); + if (user && user.name !== name) { + return Promise.reject("Le nom existe déjà..."); + } + } catch (error) { + console.log(error); + } + return true; + }), + body('isPublicEmail') + .isBoolean() + .withMessage("L'adresse email peut être public ou privé, rien d'autre."), + body('biography') + .trim() + .escape() + ], usersController.putUser); + // Permet de se connecter UsersRouter.post('/login', [ body('email') @@ -23,59 +81,6 @@ UsersRouter.post('/login', [ // Récupère les informations public d'un profil UsersRouter.get('/:name', usersController.getUserInfo); -// Permet de modifier son profil -UsersRouter.put('/', isAuth, -fileUpload({ - useTempFiles: true, - safeFileNames: true, - preserveExtension: Number, - limits: { fileSize: 5 * 1024 * 1024 }, // 5mb, - parseNested: true -}), -[ - body('email') - .isEmail() - .withMessage("Veuillez rentré une adresse mail valide.") - .custom((async (email) => { - try { - const user = await Users.findOne({ where: { email } }); - if (user && user.email !== email) { - return Promise.reject("L'adresse email existe déjà..."); - } - } catch (error) { - return console.log(error); - } - return true; - })) - .normalizeEmail(), - body('name') - .trim() - .not() - .isEmpty() - .withMessage("Vous devez avoir un nom (ou pseudo).") - .isAlphanumeric() - .withMessage("Votre nom ne peut contenir que des lettres ou/et des nombres.") - .isLength({ max: 30 }) - .withMessage("Votre nom est trop long") - .custom(async (name) => { - try { - const user = await Users.findOne({ where: { name } }); - if (user && user.name !== name) { - return Promise.reject("Le nom existe déjà..."); - } - } catch (error) { - console.log(error); - } - return true; - }), - body('isPublicEmail') - .isBoolean() - .withMessage("L'adresse email peut être public ou privé, rien d'autre."), - body('biography') - .trim() - .escape() -], usersController.putUser); - // Permet de s'inscrire UsersRouter.post('/register', [ body('email') @@ -121,18 +126,20 @@ UsersRouter.post('/register', [ // Confirme l'inscription UsersRouter.get('/confirm-email/:tempToken', usersController.confirmEmail); -// Demande une réinitialisation du mot de passe -UsersRouter.post('/reset-password', [ - body('email') - .isEmail() - .withMessage("Veuillez rentré une adresse mail valide.") -], usersController.resetPassword); +UsersRouter.route('/reset-password') -// Nouveau mot de passe -UsersRouter.put('/reset-password', [ - body('password') - .isLength({ min: 4 }) - .withMessage("Votre mot de passe est trop court!") -], usersController.newPassword); + // Demande une réinitialisation du mot de passe + .post([ + body('email') + .isEmail() + .withMessage("Veuillez rentré une adresse mail valide.") + ], usersController.resetPassword) + + // Nouveau mot de passe + .put([ + body('password') + .isLength({ min: 4 }) + .withMessage("Votre mot de passe est trop court!") + ], usersController.newPassword); module.exports = UsersRouter; \ No newline at end of file