📦 NEW: GET /users

This commit is contained in:
Divlo 2020-05-02 15:51:51 +02:00
parent 650bcac05a
commit db3f940da5
3 changed files with 94 additions and 66 deletions

View File

@ -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: {

View File

@ -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;

View File

@ -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;