From be052ecf156ffbd530ab88da30211f394867b9e7 Mon Sep 17 00:00:00 2001 From: Hitansh Doshi Date: Wed, 28 Jun 2023 00:45:15 +0530 Subject: [PATCH 1/2] fixed syntax according to eslint --- controller/auth.js | 11 +++--- controller/user.js | 4 +-- middleware/auth.js | 12 ++++--- models/accreditation.js | 2 +- models/attendance.js | 10 +++--- models/faculty.js | 14 ++++---- models/group.js | 73 +++++++++++++++++++-------------------- models/infra.js | 2 +- models/module.js | 6 ++-- models/organization.js | 4 ++- models/otpStore.js | 10 +++--- models/subject.js | 44 ++++++++++++------------ models/user.js | 6 ++-- services/user.js | 4 +-- util.js | 75 ++++++++++++++++++++++------------------- 15 files changed, 144 insertions(+), 133 deletions(-) diff --git a/controller/auth.js b/controller/auth.js index d38860f..3db5753 100644 --- a/controller/auth.js +++ b/controller/auth.js @@ -1,5 +1,5 @@ import OTPStore from "#models/otpStore"; -import util, {logger} from "#util"; +import util, { logger } from "#util"; import { authenticateUser, userExists, updatePassword } from "#services/user"; async function login(req, res) { @@ -16,7 +16,7 @@ async function login(req, res) { userDetails.token = token; res.json({ res: "welcome", user: userDetails }); } catch (error) { - logger.error("Error while login", error) + logger.error("Error while login", error); if (error.name === "UserDoesNotExist") { res.status(403); res.json({ err: "Incorrect ID password" }); @@ -35,7 +35,7 @@ async function sendOTP(req, res) { const { uid, emailId } = req.body; if (await userExists(uid, emailId)) { const otp = Math.floor(1000 + Math.random() * 9000); - await OTPStore.update({uid: uid}, {otp: otp}); + await OTPStore.update({ uid }, { otp }); util.sendOTP(emailId, otp); res.json({ res: "otp sent to emailID" }); } else { @@ -45,13 +45,13 @@ async function sendOTP(req, res) { async function resetPassword(req, res) { const { uid, otp, password } = req.body; - const storedOtp = await OTPStore.read({uid: uid}); + const storedOtp = await OTPStore.read({ uid }); if (storedOtp[0].otp === `${otp}`) { try { await updatePassword(uid, password); res.json({ res: "successfully updated password" }); } catch (error) { - logger.log("Error while updating", error) + logger.log("Error while updating", error); res.status(500); if (error.name === "UpdateError") res.json({ err: "Something went wrong while updating password" }); else res.json({ err: "something went wrong" }); @@ -60,7 +60,6 @@ async function resetPassword(req, res) { res.json({ err: "incorrect otp" }); } } - export default { validateUser, sendOTP, resetPassword, login, diff --git a/controller/user.js b/controller/user.js index a3e94ac..20efc5c 100644 --- a/controller/user.js +++ b/controller/user.js @@ -9,8 +9,8 @@ async function addUser(req, res) { const newUser = await createUser(name, password, emailId, uid, userType); res.json({ res: `added user ${newUser.id}` }); } catch (error) { - logger.error("Error while inserting", error) - res.status(500) + logger.error("Error while inserting", error); + res.status(500); res.json({ err: "Error while inserting in DB" }); } } diff --git a/middleware/auth.js b/middleware/auth.js index 74418f0..016483d 100644 --- a/middleware/auth.js +++ b/middleware/auth.js @@ -1,5 +1,5 @@ import jwt from "jsonwebtoken"; -import util, {logger} from "#util"; +import util from "#util"; async function authenticateToken(req, res, next) { const authHeader = req.headers.authorization; @@ -9,15 +9,17 @@ async function authenticateToken(req, res, next) { const payload = jwt.verify(token, process.env.TOKEN_SECRET); const decryptedIP = util.decrypt(payload.ip); if (decryptedIP !== req.ip) { - res.status(403) - res.send({err:"Unauthorized"}); + res.status(403); + res.send({ err: "Unauthorized" }); } req.user = payload.data; next(); + return true; } catch (error) { - res.status(403) - res.send({err:"Unauthorized"}); + res.status(403); + res.send({ err: "Unauthorized" }); + return false; } } diff --git a/models/accreditation.js b/models/accreditation.js index cd75537..7d62077 100644 --- a/models/accreditation.js +++ b/models/accreditation.js @@ -8,7 +8,7 @@ const accreditationSchema = { dateofExpiry: { type: Date, required: true }, }; -const Accreditation = new connector.model("Accreditation", accreditationSchema); +const Accreditation = connector.model("Accreditation", accreditationSchema); async function remove(filter) { const res = await Accreditation.findOneAndDelete(filter); diff --git a/models/attendance.js b/models/attendance.js index d5ced3c..5b0a723 100644 --- a/models/attendance.js +++ b/models/attendance.js @@ -1,5 +1,4 @@ import connector from "./databaseUtil"; -import Infrastructure from "./infrastructure"; connector.set("debug", true); @@ -7,7 +6,6 @@ const attendanceSchema = { date: { type: Date, required: true }, time: { type: String, required: true }, absentees: { type: Array }, - class: Infrastructure, }; const Attendance = connector.model("Attendance", attendanceSchema); @@ -28,10 +26,14 @@ async function remove(filter) { } async function grantAttendance(roll, date) { - const res = await Attendance.findOneAndUpdate(date, {$pull: { absentees: roll } }, { new: true }); + const res = await Attendance.findOneAndUpdate( + date, + { $pull: { absentees: roll } }, + { new: true }, + ); return res; } export default { create, remove, grantAttendance, -}; \ No newline at end of file +}; diff --git a/models/faculty.js b/models/faculty.js index 3e74312..54e6f72 100644 --- a/models/faculty.js +++ b/models/faculty.js @@ -1,13 +1,13 @@ -const { connector } = require('./databaseUtil'); +const { connector } = require("./databaseUtil"); -const facultySchema = new mongoose.Schema({ +const facultySchema = { name: { type: String, required: true, }, department: { - type: mongoose.Schema.Types.ObjectId, - ref: 'Department', + type: connector.Schema.Types.ObjectId, + ref: "Department", required: true, }, empType: { @@ -19,7 +19,7 @@ const facultySchema = new mongoose.Schema({ required: true, }, preferredSubjects: { - type: [{ type: mongoose.Schema.Types.ObjectId, ref: 'Subject' }], + type: [{ type: connector.Schema.Types.ObjectId, ref: "Subject" }], required: true, }, profileLink: { @@ -87,8 +87,8 @@ const facultySchema = new mongoose.Schema({ type: Date, default: Date.now, }, -}); +}; -const Faculty = connector.model('Faculty', facultySchema); +const Faculty = connector.model("Faculty", facultySchema); module.exports = Faculty; diff --git a/models/group.js b/models/group.js index d5c7bbd..19118eb 100644 --- a/models/group.js +++ b/models/group.js @@ -1,54 +1,55 @@ import connector from "#models/databaseUtil"; + const groupSchema = { - groupName: { type: String, required: true }, - studentIds: { type: [Number], required: true }, + groupName: { type: String, required: true }, + studentIds: { type: [Number], required: true }, }; -const groupModel = new connector.model("group", groupSchema); +const groupModel = connector.model("group", groupSchema); async function createGroup(groupData) { - try { - const newGroup = await groupModel.create(groupData); - return newGroup; - } catch (error) { - console.error("Error creating group:", error); - return null; - } + try { + const newGroup = await groupModel.create(groupData); + return newGroup; + } catch (error) { + console.error("Error creating group:", error); + return null; + } } async function getGroupById(groupId) { - try { - const group = await groupModel.findById(groupId); - return group; - } catch (error) { - console.error("Error retrieving group:", error); - return null; - } + try { + const group = await groupModel.findById(groupId); + return group; + } catch (error) { + console.error("Error retrieving group:", error); + return null; + } } async function updateGroup(groupId, updateData) { - try { - const updatedGroup = await groupModel.findByIdAndUpdate(groupId, updateData, { new: true }); - return updatedGroup; - } catch (error) { - console.error("Error updating group:", error); - return null; - } + try { + const updatedGroup = await groupModel.findByIdAndUpdate(groupId, updateData, { new: true }); + return updatedGroup; + } catch (error) { + console.error("Error updating group:", error); + return null; + } } async function deleteGroup(groupId) { - try { - const deletedGroup = await groupModel.findByIdAndDelete(groupId); - return deletedGroup; - } catch (error) { - console.error("Error deleting group:", error); - return null; - } + try { + const deletedGroup = await groupModel.findByIdAndDelete(groupId); + return deletedGroup; + } catch (error) { + console.error("Error deleting group:", error); + return null; + } } -module.exports = { - createGroup, - getGroupById, - updateGroup, - deleteGroup, +export default { + createGroup, + getGroupById, + updateGroup, + deleteGroup, }; diff --git a/models/infra.js b/models/infra.js index ec2bac8..37c5c16 100644 --- a/models/infra.js +++ b/models/infra.js @@ -8,7 +8,7 @@ const infrastructureSchema = { capacity: { type: Number, required: true }, }; -const Infrastructure = new connector.model("Infrastructure", infrastructureSchema); +const Infrastructure = connector.model("Infrastructure", infrastructureSchema); async function remove(filter) { const res = await Infrastructure.findOneAndDelete(filter); diff --git a/models/module.js b/models/module.js index 3387f38..3ce94ee 100644 --- a/models/module.js +++ b/models/module.js @@ -1,4 +1,4 @@ -import connector from '#models/databaseUtil'; +import connector from "#models/databaseUtil"; const moduleSchema = { moduleNo: { type: Number, required: true }, @@ -9,7 +9,7 @@ const moduleSchema = { cognitiveLevels: [{ type: String, required: true }], }; -const Module = new connector.model('Module', moduleSchema); +const Module = connector.model("Module", moduleSchema); async function remove(filter) { const res = await Module.findOneAndDelete(filter); @@ -22,7 +22,7 @@ async function create( moduleOutcome, moduleContents, hrsPerModule, - cognitiveLevels + cognitiveLevels, ) { const module = new Module({ moduleNo, diff --git a/models/organization.js b/models/organization.js index d70cfa8..95ba478 100644 --- a/models/organization.js +++ b/models/organization.js @@ -11,4 +11,6 @@ const organizationSchema = { employees: [{ type: connector.Schema.Types.ObjectId, ref: "Faculty", required: "true" }], }; -const Organization = new connector.model("Organization", organizationSchema); + +// eslint-disable-next-line no-unused-vars +const Organization = connector.model("Organization", organizationSchema); diff --git a/models/otpStore.js b/models/otpStore.js index 45648b8..6695e49 100644 --- a/models/otpStore.js +++ b/models/otpStore.js @@ -2,10 +2,10 @@ import connector from "#models/databaseUtil"; const otpStoreSchema = { uid: { type: String, unique: true, required: true }, - otp: { type: String, unique: true, required: true } -} + otp: { type: String, unique: true, required: true }, +}; -const OTPStore = connector.model("OTPStore", otpStoreSchema) +const OTPStore = connector.model("OTPStore", otpStoreSchema); async function remove(filter) { const res = await OTPStore.findOneAndDelete(filter); @@ -15,7 +15,7 @@ async function remove(filter) { async function create(uid, otp) { const otpStore = new OTPStore({ uid, - otp + otp, }); const otpDoc = await otpStore.save(); return otpDoc; @@ -31,8 +31,6 @@ async function update(filter, updateObject) { return otpDoc; } - export default { create, read, update, remove, }; - diff --git a/models/subject.js b/models/subject.js index 31b5fbf..e014bcc 100644 --- a/models/subject.js +++ b/models/subject.js @@ -1,26 +1,26 @@ const { connector } = require("#models/databaseUtil"); -const { Module } = require("#models/module"); -const { Practical} = require("#models/practical"); const subjectcontentSchema = { - courseCode: {type: String, required: true}, - courseName: {type: String, required: true}, - totalCredit: {type: Number, required: true}, - duration: {type: Number, required: true}, - subID: {type: String, required: true}, - subName: {type:String, required: true}, - semester: {type: String, required: true}, - ltpCredDist: {type: [Number], required: true}, - subType: {type: String, enum: ["open", "professional", "core"], required: true}, // can be open, professional, or core - prerequisites: {type: String, required: true}, - courseObjective:{type: String, required: true}, - courseOutcomes : [{courseOutcome:{type: String}, RBTLevel: {type:String}}], //this is the modules from syllabus - modules: {type: [Module], required: true}, - reccTextbooks: {type: [String], required: true}, - refBooks: {type: [String], required: true}, - evalScheme: {type: [Number], required: true}, - maxMarks: {type: Number, required: true}, - practicals: {type: [Practical], required: true} -}; + courseCode: { type: String, required: true }, + courseName: { type: String, required: true }, + totalCredit: { type: Number, required: true }, + duration: { type: Number, required: true }, + subID: { type: String, required: true }, + subName: { type: String, required: true }, + semester: { type: String, required: true }, + ltpCredDist: { type: [Number], required: true }, + subType: { type: String, enum: ["open", "professional", "core"], required: true }, // can be open, professional, or core + prerequisites: { type: String, required: true }, + courseObjective: { type: String, required: true }, + courseOutcomes: [{ + courseOutcome: { type: String }, + RBTLevel: { type: String }, + }], // this is the modules from syllabus + reccTextbooks: { type: [String], required: true }, + refBooks: { type: [String], required: true }, + evalScheme: { type: [Number], required: true }, + maxMarks: { type: Number, required: true }, +}; -const subjectcontentModel = new connector.model("subjectcontent", subjectcontentSchema); +// eslint-disable-next-line no-unused-vars +const subjectcontentModel = connector.model("subjectcontent", subjectcontentSchema); diff --git a/models/user.js b/models/user.js index b2bb635..17e63cd 100644 --- a/models/user.js +++ b/models/user.js @@ -1,5 +1,5 @@ import connector from "#models/databaseUtil"; -import { hashPassword, logger } from "#util"; +import { hashPassword } from "#util"; connector.set("debug", true); const userSchema = { @@ -17,8 +17,8 @@ async function remove(filter) { return res; } -async function create(name, password, emailId, uid, userType) { - password = await hashPassword(password); +async function create(name, pass, emailId, uid, userType) { + const password = await hashPassword(pass); const user = new User({ name, password, diff --git a/services/user.js b/services/user.js index e2e8265..b45fe34 100644 --- a/services/user.js +++ b/services/user.js @@ -1,10 +1,10 @@ import User from "#models/user"; import databaseError from "#error/database"; -import { comparePasswords, hashPassword, logger } from "#util"; +import { comparePasswords, hashPassword } from "#util"; export async function authenticateUser(uid, password) { const user = await User.read({ uid }, 1); - const passwordMatched = await comparePasswords(password, user[0]?.password); + const passwordMatched = await comparePasswords(password, user[0]?.password); if (passwordMatched) { return user[0]; } diff --git a/util.js b/util.js index b029159..e7ff739 100644 --- a/util.js +++ b/util.js @@ -1,7 +1,7 @@ import jwt from "jsonwebtoken"; import nodemailer from "nodemailer"; import { logLevel } from "#constant"; -import crypto from "crypto" +import crypto from "crypto"; import "winston-daily-rotate-file"; import winston from "winston"; import dotenv from "dotenv"; @@ -24,26 +24,26 @@ const transporter = nodemailer.createTransport({ const key = crypto.randomBytes(32); const iv = crypto.randomBytes(16); -const algorithm = 'aes-256-cbc'; +const algorithm = "aes-256-cbc"; const encrypt = (IP) => { - const cipher = crypto.createCipheriv(algorithm, key, iv); - let encrypted = cipher.update(IP, 'utf8', 'hex'); - encrypted += cipher.final('hex'); - return encrypted; -} + const cipher = crypto.createCipheriv(algorithm, key, iv); + let encrypted = cipher.update(IP, "utf8", "hex"); + encrypted += cipher.final("hex"); + return encrypted; +}; const decrypt = (IP) => { - const decipher = crypto.createDecipheriv(algorithm, key, iv); - let decrypted = decipher.update(IP, 'hex', 'utf8'); - decrypted += decipher.final('utf8'); - return decrypted; -} + const decipher = crypto.createDecipheriv(algorithm, key, iv); + let decrypted = decipher.update(IP, "hex", "utf8"); + decrypted += decipher.final("utf8"); + return decrypted; +}; -const generateToken = (data, IP)=>{ +const generateToken = (data, IP) => { const encryptedIP = encrypt(IP); - return jwt.sign({data: data, ip: encryptedIP}, process.env.TOKEN_SECRET); -} + return jwt.sign({ data, ip: encryptedIP }, process.env.TOKEN_SECRET); +}; const sendOTP = async (to, otp) => { await transporter.sendMail({ @@ -54,24 +54,24 @@ const sendOTP = async (to, otp) => { }); }; -export const hashPassword = async(password) =>{ - try { - const salt = await bcrypt.genSalt(10); - const hashedPassword = await bcrypt.hash(password,salt); - return hashedPassword; - } catch (error) { - return error.message; - } -} - -export const comparePasswords = async(userPassword,storedPassword) =>{ - try { - const matched = await bcrypt.compare(userPassword,storedPassword); - return matched - } catch (error) { - return error.message; - } -} +export const hashPassword = async (password) => { + try { + const salt = await bcrypt.genSalt(10); + const hashedPassword = await bcrypt.hash(password, salt); + return hashedPassword; + } catch (error) { + return error.message; + } +}; + +export const comparePasswords = async (userPassword, storedPassword) => { + try { + const matched = await bcrypt.compare(userPassword, storedPassword); + return matched; + } catch (error) { + return error.message; + } +}; /** * @@ -143,5 +143,12 @@ logger.stream = { }; export default { - generateToken, encrypt, decrypt, sendOTP, asyncPlaceholders, logger, hashPassword, comparePasswords, + generateToken, + encrypt, + decrypt, + sendOTP, + asyncPlaceholders, + logger, + hashPassword, + comparePasswords, }; From 548d127bfdbe27a97de4bc5b46d7f68b29d16af1 Mon Sep 17 00:00:00 2001 From: Hitansh Doshi Date: Wed, 28 Jun 2023 01:08:03 +0530 Subject: [PATCH 2/2] added eslint script and git precommit hook --- package.json | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/package.json b/package.json index a1c5aea..1f1d7d1 100644 --- a/package.json +++ b/package.json @@ -21,7 +21,8 @@ "serverstartWin": "SET DEBUG=api:* && npm run devstart", "test": "NODE_OPTIONS=--experimental-vm-modules npx jest", "test:watch": "NODE_OPTIONS=--experimental-vm-modules npx jest --watch", - "test:openHandels": "NODE_OPTIONS=--experimental-vm-modules npx jest --detectOpenHandles" + "test:openHandels": "NODE_OPTIONS=--experimental-vm-modules npx jest --detectOpenHandles", + "eslint": "eslint '**/*.js'" }, "dependencies": { "bcrypt": "^5.1.0",