const bcrypt = require('bcryptjs') const User = require('../models/user') const AuthController = { async register(req, res) { var clientError = false; try { if(!req.body.name || !req.body.email || !req.body.password || !req.body.password_confirmation) { clientError = true throw new Error('Error! Bad request data!') } if(req.body.password != req.body.password_confirmation) { clientError = true throw new Error('Error! The two password is not same!') } const user = await User.findOne({ where: { name: req.body.name } }) if(user) { clientError = true throw new Error('Error! User already exists: ' + user.name) } AuthController.tryRegister(req, res) } catch (error) { if (clientError) { res.status(400) }else { res.status(500) } await res.json({ success: false, message: 'Error! User creation failed!', error: error.message }) } }, async tryRegister(req, res) { const user = { name: req.body.name, email: req.body.email, password: bcrypt.hashSync(req.body.password) } await User.create(user) .then( result => { res.status(201) res.json({ succes: true, data: result }) }) } } module.exports = AuthController