Updated gitignore to ignore log files, Refactored Authcontroller to use DB interface, Added Try/Catch to validation to catch uncaught error, Added username optional validation to Joi so it expects a username

This commit is contained in:
Alex Holliday committed 2024-05-14 11:12:22 -07:00
1 parent c5b93e7437
commit a4a61695b0
7 files changed
+137 -72

No files matched your search

+2 -1
View File
@@ -1,2 +1,3 @@
node_modules node_modules
.env .env
*.log
+34 -23
View File
@@ -1,32 +1,43 @@
const express = require('express') const express = require("express");
const UserModel = require('../models/user') const UserModel = require("../models/user");
const { authValidation } = require('../validation/joi') const { authValidation } = require("../validation/joi");
/** /**
* @function * @function
* @param {express.Request} req * @param {express.Request} req
* @param {express.Response} res * @param {express.Response} res
* @returns {{success: Boolean, msg: String}} * @returns {{success: Boolean, msg: String}}
*/ */
const registerController = async (req, res) => { const registerController = async (req, res) => {
// joi validation // joi validation
const { error } = await authValidation.validateAsync(req.body); try {
if (error) return res.status(400).json({ success: false, msg: error.details[0].message }); await authValidation.validateAsync(req.body);
} catch (error) {
return res
.status(400)
.json({ success: false, msg: error.details[0].message });
}
// Check if the user exists // Check if the user exists
const isUser = await UserModel.findOne({ email: req.body.email }); try {
if (isUser) return res.status(400).json({ success: false, msg: "User already exists!" }) const isUser = await req.db.getUserByEmail(req, res);
if (isUser)
return res
.status(400)
.json({ success: false, msg: "User already exists!" });
} catch (error) {
return res.status(500).json({ success: false, msg: error.message });
}
try { try {
// Create a new user // Create a new user
const newUser = await UserModel.create({ ...req.body }); const newUser = await req.db.insertUser(req, res);
return res.json({ success: true, msg: "User created}", data: newUser });
// Send an email to user
// Will add this later
} catch (error) {
return res.status(500).json({ success: false, msg: error.message });
}
};
// Send an email to user module.exports = { registerController };
// Will add this later
} catch (error) {
return res.status(500).json({success:false,msg:'Something went wrong!'})
}
}
module.exports = {registerController}
+29
View File
@@ -21,8 +21,10 @@
// ************************** // **************************
const Monitor = require("../models/Monitor"); const Monitor = require("../models/Monitor");
const UserModel = require("../models/user");
const FAKE_MONITOR_DATA = []; const FAKE_MONITOR_DATA = [];
const USERS = [];
for (let i = 0; i < 10; i++) { for (let i = 0; i < 10; i++) {
FAKE_MONITOR_DATA.push( FAKE_MONITOR_DATA.push(
@@ -47,6 +49,31 @@ const connect = async () => {
} }
}; };
const insertUser = async (req, res) => {
try {
const newUser = new UserModel({ ...req.body });
USERS.push(newUser);
return newUser;
} catch (error) {
throw error;
}
};
const getUserByEmail = async (req, res) => {
const email = req.body.email;
try {
const idx = USERS.findIndex((user) => {
return user.email === email;
});
if (idx === -1) {
return null;
}
return USERS[idx];
} catch (error) {
throw new Error(`User with email ${email} not found`);
}
};
const getAllMonitors = async () => { const getAllMonitors = async () => {
return FAKE_MONITOR_DATA; return FAKE_MONITOR_DATA;
}; };
@@ -75,6 +102,8 @@ const getMonitorsByUserId = async (userId) => {
module.exports = { module.exports = {
connect, connect,
insertUser,
getUserByEmail,
getAllMonitors, getAllMonitors,
getMonitorById, getMonitorById,
getMonitorsByUserId, getMonitorsByUserId,
+22
View File
@@ -1,5 +1,6 @@
const Monitor = require("../models/Monitor"); const Monitor = require("../models/Monitor");
const mongoose = require("mongoose"); const mongoose = require("mongoose");
const UserModel = require("../models/user");
const connect = async () => { const connect = async () => {
try { try {
@@ -11,6 +12,25 @@ const connect = async () => {
} }
}; };
const insertUser = async (req, res) => {
try {
const newUser = await UserModel.create({ ...req.body });
return newUser;
} catch (error) {
throw error;
}
};
const getUserByEmail = async (req, res) => {
try {
// Returns null if no user is found
const user = await UserModel.findOne({ email: req.body.email });
return user;
} catch (error) {
throw error;
}
};
// Gets all monitors // Gets all monitors
const getAllMonitors = async (req, res) => { const getAllMonitors = async (req, res) => {
try { try {
@@ -43,6 +63,8 @@ const getMonitorsByUserId = async (req, res) => {
module.exports = { module.exports = {
connect, connect,
insertUser,
getUserByEmail,
getAllMonitors, getAllMonitors,
getMonitorById, getMonitorById,
getMonitorsByUserId, getMonitorsByUserId,
+7 -7
View File
@@ -5,7 +5,7 @@ const authRouter = require("./routes/authRoute");
const monitorRouter = require("./routes/monitorRoute"); const monitorRouter = require("./routes/monitorRoute");
const { connectDbAndRunServer } = require("./configs/db"); const { connectDbAndRunServer } = require("./configs/db");
require("dotenv").config(); require("dotenv").config();
const logger = require('./utils/logger'); const logger = require("./utils/logger");
// const { sendEmail } = require('./utils/sendEmail') // const { sendEmail } = require('./utils/sendEmail')
// ************************** // **************************
@@ -23,7 +23,7 @@ const db = require("./db/MongoDB");
/** /**
* NOTES * NOTES
* Email Service will be added * Email Service will be added
* Logger Service will be added (Winston or similar) * Logger Service will be added (Winston or similar)
*/ */
@@ -60,11 +60,11 @@ app.use("/api/v1/monitors", monitorRouter);
//health check //health check
app.use("/api/v1/healthy", (req, res) => { app.use("/api/v1/healthy", (req, res) => {
try { try {
logger.info("Checking Health of the server.") logger.info("Checking Health of the server.");
return res.status(200).json({ message: "Healthy" }); return res.status(200).json({ message: "Healthy" });
} catch (error) { } catch (error) {
logger.error(error.message) logger.error(error.message);
return res.status(500).json({ message: error.message }); return res.status(500).json({ message: error.message });
} }
}); });
+42 -41
View File
@@ -1,45 +1,46 @@
const mongoose = require('mongoose') const mongoose = require("mongoose");
const bcrypt = require('bcrypt') const bcrypt = require("bcrypt");
const UserSchema = mongoose.Schema({ const UserSchema = mongoose.Schema({
username: { username: {
type: String type: String,
}, },
email: { email: {
type: String, type: String,
required: true required: true,
}, unique: true,
password: { },
type: String, password: {
required: true type: String,
}, required: true,
profilePicUrl: { },
type: String profilePicUrl: {
}, type: String,
isActive: { },
type: Boolean, isActive: {
default: true type: Boolean,
}, default: true,
isVerified: { },
type: Boolean, isVerified: {
default: false type: Boolean,
}, default: false,
updated_at: { },
type: Date, updated_at: {
default: Date.now type: Date,
}, default: Date.now,
created_at: { },
type: Date, created_at: {
default: Date.now type: Date,
} default: Date.now,
}) },
});
UserSchema.pre('save', async function (next) { UserSchema.pre("save", async function (next) {
if (!this.isModified('password')) { if (!this.isModified("password")) {
next() next();
} }
const salt = bcrypt.genSalt(10); const salt = await bcrypt.genSalt(10); //genSalt is asynchronous, need to wait
this.password = await bcrypt.hash(this.password, salt); this.password = bcrypt.hash(this.password, salt);
}) });
module.exports = mongoose.model('User',UserSchema) module.exports = mongoose.model("User", UserSchema);
+1
View File
@@ -2,6 +2,7 @@ const joi = require("joi");
const user = require("../models/user"); const user = require("../models/user");
const authValidation = joi.object({ const authValidation = joi.object({
username: joi.string(),
email: joi.string().email().required(), email: joi.string().email().required(),
password: joi.string().min(8).required(), password: joi.string().min(8).required(),
}); });