import User from './user.model.js' import formidable from 'formidable' import extend from 'lodash/extend.js' import fs from 'fs' const create = async (req, res) => { const user = new User(req.body) try { await user.save() return res.json({ message: 'Successfully signed up!' }) } catch (error) { return res.status(400).json({ error: 'User creation error' }) } } const list = async (req, res) => { try { let users = await User.find().select('name email updated created').exec() return res.json(users) } catch (error) { return res.status(400).json({ error: 'Users not found' }) } } const read = (req, res) => { req.profile.hashedPassword = undefined req.profile.salt = undefined return res.json(req.profile) } const update = (req, res) => { let form = new formidable.IncomingForm() form.keepExtensions = true form.parse(req, async (err, fields, files) => { if (err) { return res.status(400).json({ error: 'Photo could not be uploaded' }) } let user = req.profile user = extend(user, fields) user.updated = new Date() if (files.photo) { user.photo.data = fs.readFileSync(files,photo.path) user.photo.contentType = files.photo.type } try { await user.save() user.hashedPassword = undefined user.salt = undefined res.json(user) } catch (error) { return res.status(400).json({ error: 'User save error' }) } }) } const remove = async (req, res) => { try { let user = req.profile let deletedUser = await user.remove() deletedUser.hashedPassword = undefined deletedUser.salt = undefined res.json(deletedUser) } catch (error) { return res.status(400).json({ error: 'User delete error' }) } } const isInstructor = (req, res, next) => { const instructor = req.profile && req.profile.instructor if (!instructor) { return res.status(403).json({ error: 'User is not an instructor' }) } next() } const userById = async (req, res, next, id) => { // console.log('req.body in userById', req.body); try { let user = await User.findById(id) .exec() if (!user) { return res.status(400).json({ error: 'User not found' }) } req.profile = user next() } catch (error) { return res.status(400).json({ error: 'Could not retrieve user' }) } } export default { create, list, read, update, remove, isInstructor, userById, }