Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

BTVN8: API Register & Login + Add Middleware #52

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1,106 changes: 1,090 additions & 16 deletions package-lock.json

Large diffs are not rendered by default.

2 changes: 2 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
{
"dependencies": {
"bcrypt": "^5.1.0",
"dotenv": "^16.0.3",
"express": "^4.18.2",
"jsonwebtoken": "^9.0.0",
"mongoose": "^7.0.3",
"nodemon": "^2.0.22"
},
Expand Down
62 changes: 62 additions & 0 deletions src/controllers/auth.controller.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
const User = require("../models/user.model");
const bcrypt = require("bcrypt");
const jwt = require("jsonwebtoken");

const login = async (req, res, next) => {
try {
const { studentCode, password } = req.body;
const user = await User.findOne({ studentCode });
if (!user) {
const err = new Error("classroom not found");
err.status = 400;
throw err;
}

const isPassword = await bcrypt.compare(password, user.password);
if (!isPassword) {
const err = new Error("Student code or password is incorrect!");
err.status = 400;
throw err;
}

const token = await jwt.sign(
{
userId: user._id,
},
process.env.SECRET_KEY
);
res.status(200).json({
token,
});
} catch (err) {
next(err);
}
};

const register = async (req, res, next) => {
const { fullName, password, studentCode } = req.body;
try {
if (!studentCode) {
const err = new Error("Student code is required!");
err.status = 400;
throw err;
}
const checkUser = await User.findOne({ studentCode });
if (checkUser) {
const err = new Error("Student code is exit!");
err.status = 400;
throw err;
}
const user = await User.create({ fullName, password, studentCode });
res.status(201).json({
user,
});
} catch (err) {
next(err);
}
};

module.exports = {
login,
register,
};
279 changes: 149 additions & 130 deletions src/controllers/classroom.controller.js
Original file line number Diff line number Diff line change
@@ -1,159 +1,178 @@
const Classroom = require("../models/classroom.model");

const getClassrooms = async (req, res, next) => {
try {
const classrooms = await Classroom.find().populate(['leaders', 'supports', 'students']);
res.status(200).json({ classrooms });
} catch (err) {
next(err);
}
}
try {
const classrooms = await Classroom.find().populate([
"leaders",
"supports",
"students",
]);
res.status(200).json({ classrooms });
} catch (err) {
next(err);
}
};

const getClassroomById = async (req, res, next) => {
const { classroomId } = req.params;
try {
const classroom = await Classroom.findById(classroomId).populate(['leaders', 'supports', 'students']);
if (!classroom) {
const err = new Error('Classroom not found!');
err.status = 404;
throw err;
}
res.status(200).json({ classroom });
} catch (err) {
next(err);
const { classroomId } = req.params;
try {
const classroom = await Classroom.findById(classroomId).populate([
"leaders",
"supports",
"students",
]);
if (!classroom) {
const err = new Error("Classroom not found!");
err.status = 404;
throw err;
}
res.status(200).json({ classroom });
} catch (err) {
next(err);
}
};

const createClassroom = async (req, res, next) => {
const rawClassroom = req.body;
try {
if (!rawClassroom.name || !rawClassroom.startTime) {
const err = new Error('Invalid classroom');
err.status = 400;
throw err;
}
const newClassroom = await Classroom.create(rawClassroom);
res.status(201).json({ newClassroom });
} catch (err) {
next(err);
const rawClassroom = req.body;

try {
if (!rawClassroom.name || !rawClassroom.startTime) {
const err = new Error("Invalid classroom");
err.status = 400;
throw err;
}
const newClassroom = await Classroom.create(rawClassroom);
res.status(201).json({ newClassroom });
} catch (err) {
next(err);
}
};

const updateClassroomById = async (req, res, next) => {
const { classroomId } = req.params;
const rawClassroom = req.body;
try {
const updatedClassroom = await Classroom.findByIdAndUpdate(classroomId, rawClassroom, { new: true });
if (!updatedClassroom) {
const err = new Error('Classroom not found!');
err.status = 404;
throw err;
}
res.status(200).json({ updatedClassroom });
} catch (err) {
next(err);
const { classroomId } = req.params;
const rawClassroom = req.body;
try {
const updatedClassroom = await Classroom.findByIdAndUpdate(
classroomId,
rawClassroom,
{ new: true }
);
if (!updatedClassroom) {
const err = new Error("Classroom not found!");
err.status = 404;
throw err;
}
res.status(200).json({ updatedClassroom });
} catch (err) {
next(err);
}
};

const deleteClassroomById = async (req, res, next) => {
const { classroomId } = req.params;
try {
const deletedClassroom = await Classroom.findByIdAndDelete(classroomId);
if (!deletedClassroom) {
const err = new Error('Classroom not found!');
err.status = 404;
throw err;
}
res.status(204).json();
} catch (err) {
next(err);
const { classroomId } = req.params;
try {
const deletedClassroom = await Classroom.findByIdAndDelete(classroomId);
if (!deletedClassroom) {
const err = new Error("Classroom not found!");
err.status = 404;
throw err;
}
res.status(204).json();
} catch (err) {
next(err);
}
};

// Add a leader/support/student to a classroom
const addUserToClassroomById = async (req, res, next) => {
// In Postman use Query Params: [key, value] = [role, leader/support/student]
const { classroomId } = req.params;
const { role } = req.query;
const { userId } = req.body;
try {
// Check valid role
if (!["leader", "support", "student"].includes(role)) {
const err = new Error('Invalid role');
err.status = 400;
throw err;
}

const classroom = await Classroom.findById(classroomId);
if (!classroom) {
const err = new Error('Classroom not found!');
err.status = 404;
throw err;
}

// Check if user exists in classroom
const isExistInClassroom = classroom[`${role}s`].includes(userId);
if (isExistInClassroom) {
const err = new Error(`User as ${role} exists in classroom`);
err.status = 400;
throw err;
}

// Add user to classroom
classroom[`${role}s`].push(userId);
const addedUserToClassroom = await classroom.save();

res.status(201).json({ message: `User added as ${role} to classroom`, addedUserToClassroom });
} catch (err) {
next(err);
// In Postman use Query Params: [key, value] = [role, leader/support/student]
const { classroomId } = req.params;
const { role } = req.query;
const { userId } = req.body;
try {
// Check valid role
if (!["leader", "support", "student"].includes(role)) {
const err = new Error("Invalid role");
err.status = 400;
throw err;
}

const classroom = await Classroom.findById(classroomId);
if (!classroom) {
const err = new Error("Classroom not found!");
err.status = 404;
throw err;
}

// Check if user exists in classroom
const isExistInClassroom = classroom[`${role}s`].includes(userId);
if (isExistInClassroom) {
const err = new Error(`User as ${role} exists in classroom`);
err.status = 400;
throw err;
}
}

// Add user to classroom
classroom[`${role}s`].push(userId);
const addedUserToClassroom = await classroom.save();

res.status(201).json({
message: `User added as ${role} to classroom`,
addedUserToClassroom,
});
} catch (err) {
next(err);
}
};

// Delete a leader/support/student from a classroom
const deleteUserFromClassroomById = async (req, res, next) => {
// In Postman use Query Params: [key, value] = [role, leader/support/student]
const { classroomId } = req.params;
const { role } = req.query;
const { userId } = req.body;
try {
// Check valid role
if (!["leader", "support", "student"].includes(role)) {
const err = new Error('Invalid role');
err.status = 400;
throw err;
}

const classroom = await Classroom.findById(classroomId);
if (!classroom) {
const err = new Error('Classroom not found!');
err.status = 404;
throw err;
}

// Check if user exists in classroom
const isExistInClassroom = classroom[`${role}s`].includes(userId);
if (!isExistInClassroom) {
const err = new Error(`User as ${role} don't exists in classroom`);
err.status = 404;
throw err;
}

// Delete user to classroom
classroom[`${role}s`].remove(userId);
const deletedUserFromClassroom = await classroom.save();

res.status(200).json({ message: `User deleted as ${role} to classroom`, deletedUserFromClassroom });
} catch (err) {
next(err);
// In Postman use Query Params: [key, value] = [role, leader/support/student]
const { classroomId } = req.params;
const { role } = req.query;
const { userId } = req.body;
try {
// Check valid role
if (!["leader", "support", "student"].includes(role)) {
const err = new Error("Invalid role");
err.status = 400;
throw err;
}

const classroom = await Classroom.findById(classroomId);
if (!classroom) {
const err = new Error("Classroom not found!");
err.status = 404;
throw err;
}

// Check if user exists in classroom
const isExistInClassroom = classroom[`${role}s`].includes(userId);
if (!isExistInClassroom) {
const err = new Error(`User as ${role} don't exists in classroom`);
err.status = 404;
throw err;
}
}

// Delete user to classroom
classroom[`${role}s`].remove(userId);
const deletedUserFromClassroom = await classroom.save();

res.status(200).json({
message: `User deleted as ${role} to classroom`,
deletedUserFromClassroom,
});
} catch (err) {
next(err);
}
};

module.exports = {
getClassrooms,
getClassroomById,
createClassroom,
updateClassroomById,
deleteClassroomById,
addUserToClassroomById,
deleteUserFromClassroomById
}
getClassrooms,
getClassroomById,
createClassroom,
updateClassroomById,
deleteClassroomById,
addUserToClassroomById,
deleteUserFromClassroomById,
};
Loading