- Started working on User routes and functions

This commit is contained in:
Alexis
2020-07-02 23:06:55 +02:00
parent 939e384722
commit 3f82b487dc
3 changed files with 46 additions and 112 deletions

View File

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