From d9aa27ae3b8ecfbfd3f4c26236e32e72a00c4297 Mon Sep 17 00:00:00 2001 From: Mathias Wagner Date: Sun, 26 Jun 2022 17:05:27 +0200 Subject: [PATCH] Created the user controller --- controller/user.js | 37 +++++++++++++++++++++++++++++++++++++ 1 file changed, 37 insertions(+) create mode 100644 controller/user.js diff --git a/controller/user.js b/controller/user.js new file mode 100644 index 0000000..351119a --- /dev/null +++ b/controller/user.js @@ -0,0 +1,37 @@ +const bcrypt = require("bcrypt"); +const {mongo} = require("mongoose"); +const User = require('../models/User'); + +// Gets a user by id +module.exports.getUserById = async (id) => { + if (!mongo.ObjectId.isValid(id)) return; + return await User.findById(id).exec(); +} + +// Gets a user by name +module.exports.getUserByName = async (username) => { + return await User.findOne({username: {$regex: username, $options: 'i'}}).exec(); +} + +// Creates a new user account +module.exports.createAccount = async (username, email, password) => { + const hash = await bcrypt.hash(password, 10); + return await User.create({username, email, password: hash}); +} + +// Updates a user account by id +module.exports.updateAccount = async (user_id, changes) => { + if (!mongo.ObjectId.isValid(user_id)) return; + if (changes.password) changes.password = await bcrypt.hash(changes.password, 10); + return await User.findByIdAndUpdate(user_id, changes).exec(); +} + +// Updates the user socials by id +module.exports.updateUserSocials = async (user_id, socials) => { + let updatedSocials = {}; + for (let social in socials) + updatedSocials["socials."+social] = socials[social]; + + if (!mongo.ObjectId.isValid(user_id)) return; + return await User.findByIdAndUpdate(user_id, {$set: updatedSocials}).exec(); +} \ No newline at end of file