const uuidv4 = require('uuid/v4'); const bcrypt = require('bcryptjs'); class UserController { constructor(database) { this.database = database; }; createUser(data, scb, ecb) { console.log('UserController: create user: ' + data.username); let collection = this.database.collection('users'); collection.findOne({ username: data.username }, {}, function (dbErr, dbRes) { if (dbErr === null) { if (dbRes === null) { bcrypt.hash(data.password, 10, (err, hash) => { if (err) { ecb({ code: 'app error', message: 'could not hash password' }); } let user = { id: uuidv4(), username: data.username, passwordHash: hash, role: 'user' }; collection.insertOne(user, function (insertErr, insertRes) { if (insertErr === null) { let res = { id: user.id, username: user.username, role: user.role }; scb(res); } else { ecb({ code: 'database error. could not create user', message: insertErr.message }); } }); }); } else { ecb({ code: 'app error', message: 'user already exists' }) } } else { ecb({ code: 'database error', message: dbErr.message }); } }); }; login(data, scb, ecb) { console.log('UserController: create user: ' + data.username); let collection = this.database.collection('users'); collection.findOne({ username: data.username }, {}, function (dbErr, user) { if (dbErr === null) { if (user === null) { ecb({ code: 'app error', message: 'user already exists' }); } else { bcrypt.compare(data.password, user.passwordHash, (cryptErr, cryptRes) => { if (cryptErr) { ecb({ code: 'app error', message: 'could not hash password' }); } else { if (cryptRes === true) { let res = { id: user.id, username: user.username, role: user.role }; scb(res); } else { ecb({ code: 'user error', message: 'authentication failed' }); } } }); } } else { ecb({ code: 'database error', message: dbErr.message }); } }); }; getUserData(user, scb, ecb) { scb({}); }; }; module.exports = UserController;