From 3f82b487dc0d607474e5370e3416b3e3e41ee248 Mon Sep 17 00:00:00 2001 From: Alexis <35.alexis.pele@gmail.com> Date: Thu, 2 Jul 2020 23:06:55 +0200 Subject: [PATCH] - Started working on User routes and functions --- repositories/user-repository.js | 42 ++++++++++-- routes/users.js | 115 +++----------------------------- validations/UserValidation.js | 1 - 3 files changed, 46 insertions(+), 112 deletions(-) diff --git a/repositories/user-repository.js b/repositories/user-repository.js index 3b77786..3e44083 100644 --- a/repositories/user-repository.js +++ b/repositories/user-repository.js @@ -5,6 +5,7 @@ const model = require('../models/user-model') // Hashing and passwords const bcrypt = require('bcrypt') +const { v4: uuidv4 } = require('uuid') // Model validation const Validator = require('jsonschema').Validator @@ -26,7 +27,7 @@ class UserRepository { getAll() { return new Promise((resolve, reject) => { - this._model.forge() + model.forge() .fetchAll() .then(v => { resolve(v.toJSON({ omitPivot: true })) @@ -38,10 +39,10 @@ class UserRepository { }) } - getOne(id) { + getOneFromUUID(uuid) { return new Promise((resolve, reject) => { - this._model.forge() - .where({ 'id' : id }) + model.forge() + .where({ 'uuid' : uuid }) .fetch() .then(v => { resolve(v.toJSON({ omitPivot: true })) @@ -52,6 +53,39 @@ class UserRepository { }) }) } + + addOne(u) { + return new Promise(async (resolve, reject) => { + // Checks if body exists and if the model fits, and throws errors if it doesn't + if (isEmptyObject(u)) { + reject(new HttpError(403, "Error: User cannot be nothing !")) + } else if (!v.validate(u, UserValidation).valid) { + reject(new HttpError(403, "Error: Schema is not valid - " + v.validate(u, UserValidation).errors)) + } else if (isXSSAttempt(u.name) || isXSSAttempt(u.password) || isXSSAttempt(u.mail)) { + reject(new HttpError(403, 'Injection attempt detected, aborting the request.')) + } else { + let hash = await bcrypt.hash(u.password, 10) + let uuid = uuidv4() + + // Needs to account for duplicate emails + bookshelf.transaction(t => { + return model.forge({ + 'uuid': uuid, + 'name': u.name, + 'mail': u.mail, + 'password': hash, + }) + .save(null, { + transacting: t + }) + .catch(err => { + console.log(err) + }) + }) + + } + }) + } } module.exports = UserRepository \ No newline at end of file diff --git a/routes/users.js b/routes/users.js index 2060af6..427d801 100644 --- a/routes/users.js +++ b/routes/users.js @@ -12,8 +12,6 @@ const db = connection.db const UserRepository = require('../repositories/user-repository'); const Users = new UserRepository(); -const regexInt = RegExp(/^[1-9]\d*$/) - // ROUTES // GET ALL ------------------ const getUsers = () => { @@ -40,16 +38,16 @@ router.get('/', async (req, res) => { }) -// GET ONE ------------------ -const getUser = (id) => { - return Users.getOne(id) +// GET ONE FORM UUID ------------------ +const getUserFromUUID = (uuid) => { + return Users.getOneFromUUID(uuid) .catch(err => { console.log(err) throw err }) } -router.get('/:id/', async (req, res) => { - getUser(req.params.id) +router.get('/:uuid/', async (req, res) => { + getUserFromUUID(req.params.uuid) .then(v => { res.setHeader('Content-Type', 'application/json;charset=utf-8') res.end(JSON.stringify(v)) @@ -67,33 +65,9 @@ router.get('/:id/', async (req, res) => { // CREATE ONE ------------------ const addUser = (u) => { - return new Promise(async (resolve, reject) => { - - // Checks if body exists and if the model fits, and throws errors if it doesn't - if (isEmptyObject(u)) { - reject(new HttpError(403, "Error: User cannot be empty !")) - } else if (!v.validate(u, User).valid) { - reject(new HttpError(403, "Error: Schema is not valid - " + v.validate(u, User).errors)) - } else if (isXSSAttempt(u.name) || isXSSAttempt(u.mail) || isXSSAttempt(u.password)) { - reject(new HttpError(403, 'Injection attempt detected, aborting the request.')) - } else { - let query = `INSERT INTO user (name, mail, password) VALUES (${db.escape(u.name)}, ${db.escape(u.mail)}, ${db.escape(u.password)})` - - db.query(query, async (err, result) => { - if (err) { - reject(new HttpError(500, 'Database error')) - } else { - console.log(`Inserted "${u.name}" with ID ${result.insertId}, affecting ${result.affectedRows} row(s)`) - const new_user_id = result.insertId - let response = { - "message": `User created successfully !`, - "inserted_id": `${new_user_id}` - } - resolve(response) - } - }) - } - }).catch(err => { + return Users.addOne(u) + .catch(err => { + console.log(err) throw err }) } @@ -113,77 +87,4 @@ router.post('/', async (req, res) => { }) }) - -// DELETE ONE ------------------ -const deleteUser = (id) => { - return new Promise(async (resolve, reject) => { - - // Check if user exists - let old_user = await getUser(id) - .catch(() => { - reject((new HttpError(404, 'No user matching this ID'))) - }) - - console.log(old_user) - - let deleteUserData = () => { - return new Promise((resolve, reject) => { - let delete_user_query = `DELETE FROM user WHERE id = ${db.escape(id)}` - db.query(delete_user_query, async (err, result) => { - if (err) { - console.log(err) - reject(new HttpError(500, 'Spell deletion failed')) - } else { - let response = { - "message": "User delete successully", - "deleted_id": `${id}` - } - resolve(response) - } - }) - }) - } - - deleteUserData() - .then(v => { - resolve(v) - }) - .catch(err => { - reject(err) - }) - }) - .catch(err => { - throw err - }) -} -router.delete('/:id/', async (req, res) => { - deleteUser(req.params.id) - .then(v => { - res.setHeader('Content-Type', 'application/json;charset=utf-8') - res.send(JSON.stringify(v)) - }) - .catch(err => { - res.status(err.code).send(JSON.stringify( - { - "error": err.message, - "code": err.code - }) - ) - }) -}) - -// Param validation for single user -// (check if id is int) (could be refactored) -router.param('id', (req, res, next, id) => { - try { - if (regexInt.test(id)) { - next() - } else { - new Error - } - } catch (err) { - throw new HttpError(403, 'Provided ID must be an integer and not zero') - } -}) - module.exports = router \ No newline at end of file diff --git a/validations/UserValidation.js b/validations/UserValidation.js index 1dc9290..4ea8968 100644 --- a/validations/UserValidation.js +++ b/validations/UserValidation.js @@ -5,7 +5,6 @@ const User = { "name": { "type": "string" }, "mail": { "type": "string" }, "password": { "type": "string" }, - "banned": { "type": "boolean"}, }, "required": ["name", "password", "mail"] }