This commit is contained in:
Harikrishnan Gopal
2024-12-17 11:21:25 +05:30
parent ce73a591c5
commit b4adca13c7
7 changed files with 702 additions and 461 deletions

View File

@@ -1,11 +1,11 @@
const mongoose = require("mongoose");
const { v4: uuidv4 } = require("uuid"); // For UUID generation
const AppointmentSchema = new mongoose.Schema({
appointmentId: { type: String, default: uuidv4 }, // Auto-generate using UUID
courseId: { type: String, required: true, ref: "Course" },
facultyId: { type: String, required: true, ref: "Faculty" },
appointmentType: { type: [String], required: true }, // Array of appointment types
facultyId: { type: String, required: true },
facultyName: { type: String, required: true },
courseId: { type: String, required: true },
courseName: { type: String, required: true },
task: { type: String, required: true },
});
module.exports = mongoose.model("Appointment", AppointmentSchema);

View File

@@ -1,51 +1,65 @@
const express = require("express");
const Appointment = require("../models/Appointment");
const router = express.Router();
const Appointment = require("../models/Appointment");
const Faculty = require("../models/Faculty");
const Course = require("../models/Course");
// Save multiple appointments
router.post("/", async (req, res) => {
try {
const { appointments } = req.body; // Expecting an array of appointments
if (!appointments || !Array.isArray(appointments)) {
return res.status(400).json({ error: "Invalid or missing data" });
}
const savedAppointments = [];
for (const appointment of appointments) {
const { facultyId, courseId, tasks } = appointment;
// Validate input data
if (!facultyId || !courseId || !Array.isArray(tasks) || tasks.length === 0) {
return res.status(400).json({ error: "Invalid appointment data" });
}
const faculty = await Faculty.findOne({ facultyId });
const course = await Course.findOne({ courseId });
if (!faculty || !course) {
return res.status(404).json({
error: `Faculty or Course not found for facultyId: ${facultyId}, courseId: ${courseId}`,
});
}
// Save each task as a separate appointment
for (const task of tasks) {
const newAppointment = new Appointment({
facultyId,
facultyName: faculty.name,
courseId,
courseName: course.name,
task,
});
const savedAppointment = await newAppointment.save();
savedAppointments.push(savedAppointment);
}
}
res.status(201).json(savedAppointments);
} catch (error) {
console.error("Error saving appointments:", error);
res.status(500).json({ error: "Failed to save appointments" });
}
});
// Get all appointments
router.get("/", async (req, res) => {
try {
const appointments = await Appointment.find()
.populate("courseId", "name department")
.populate("facultyId", "name email");
const appointments = await Appointment.find();
res.json(appointments);
} catch (error) {
console.error("Error fetching appointments:", error);
res.status(500).json({ error: "Failed to fetch appointments" });
}
});
// Create a new appointment
router.post("/", async (req, res) => {
try {
const { courseId, facultyId, appointmentType } = req.body;
const newAppointment = new Appointment({
courseId,
facultyId,
appointmentType,
});
await newAppointment.save();
res.status(201).json(newAppointment);
} catch (error) {
res.status(400).json({ error: "Failed to create appointment" });
}
});
// Get appointment by ID
router.get("/:id", async (req, res) => {
try {
const appointment = await Appointment.findOne({ appointmentId: req.params.id })
.populate("courseId", "name department")
.populate("facultyId", "name email");
if (!appointment) {
return res.status(404).json({ error: "Appointment not found" });
}
res.json(appointment);
} catch (error) {
res.status(500).json({ error: "Failed to fetch appointment" });
}
});
module.exports = router;

View File

@@ -1,101 +1,58 @@
const express = require("express");
const mongoose = require("mongoose");
const bodyParser = require("body-parser");
const cors = require("cors");
require("dotenv").config();
const passport = require("passport");
const session = require("express-session");
const bcrypt = require("bcryptjs");
const LocalStrategy = require("passport-local").Strategy;
const crypto = require("crypto");
const jwt = require("jsonwebtoken");
const passport = require("passport");
const bodyParser = require("body-parser");
const path = require("path");
const bcrypt = require("bcryptjs");
require("dotenv").config();
const User = require("./models/User");
const PasswordRouter = require("./routes/authRoutes");
// Import Routes
const authRoutes = require("./routes/authRoutes");
const courseRoutes = require("./routes/courseRoutes");
const facultyRoutes = require("./routes/facultyRoutes");
const appointmentRoutes = require("./routes/appointmentRoutes");
const optionsRoutes = require("./routes/optionsRoutes");
// Existing Database Connection
const { connectdb } = require("./ConnectionDb");
connectdb();
// MongoDB Connection
mongoose
.connect(process.env.mongoURI)
.connect(process.env.mongoURI, { useNewUrlParser: true, useUnifiedTopology: true })
.then(() => console.log("MongoDB connected"))
.catch((err) => console.error("MongoDB connection error:", err));
.catch((err) => {
console.error("MongoDB connection error:", err);
process.exit(1); // Exit the app if the database connection fails
});
// Initialize App
const app = express();
const PORT = 8080;
// Middleware
app.use(cors());
app.use(cors({ origin: "http://localhost:3000", credentials: true }));
app.use(express.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(
session({
secret: "secret",
secret: "secret", // This can be replaced with another secret from .env if required
resave: false,
saveUninitialized: false,
})
);
app.use(passport.initialize());
app.use(passport.session());
// CORS configuration
app.use(
cors({
origin: "http://localhost:3000",
credentials: true,
})
);
// Passport Configuration
// Passport Config
require("./config/passport");
passport.use(
new LocalStrategy(
{ usernameField: "email" },
async (email, password, done) => {
try {
const user = await User.findOne({ email });
if (!user) {
return done(null, false, { message: "Incorrect email" });
}
const isMatch = await bcrypt.compare(password, user.password);
if (isMatch) {
return done(null, user);
} else {
return done(null, false, { message: "Incorrect password" });
}
} catch (error) {
return done(error);
}
}
)
);
passport.serializeUser((user, done) => {
done(null, user.id); // Store user ID in the session
});
passport.deserializeUser((id, done) => {
User.findById(id, (err, user) => {
done(err, user);
});
});
// Routes
app.use("/password", PasswordRouter);
app.use("/password", authRoutes);
app.use("/api/courses", courseRoutes);
app.use("/api/faculty", facultyRoutes);
app.use("/api/appointments", appointmentRoutes);
app.use("/api/appointments", appointmentRoutes); // Appointment route handles the updated structure
app.use("/api/options", optionsRoutes);
// OAuth Routes
// Google OAuth Routes
app.get(
"/auth/google",
passport.authenticate("google", { scope: ["profile", "email"] })
@@ -104,11 +61,12 @@ app.get(
app.get(
"/auth/google/callback",
passport.authenticate("google", { failureRedirect: "/" }),
function (req, res) {
res.redirect("http://localhost:3000/Welcom");
(req, res) => {
res.redirect("http://localhost:3000/Welcom"); // Redirect to a frontend route after successful login
}
);
// Local authentication routes (register and login)
app.post("/api/register", async (req, res) => {
try {
const { username, email, password } = req.body;
@@ -180,6 +138,7 @@ app.get("/auth/logout", function (req, res) {
});
});
// User Profile Route
app.get("/api/user/profile", async (req, res) => {
try {
if (req.user) {
@@ -193,19 +152,19 @@ app.get("/api/user/profile", async (req, res) => {
}
});
// Serve Static Files
// Serve React Build Files
app.use(express.static(path.join(__dirname, "../client/build")));
// Catch-All Route
app.get("*", (req, res) =>
res.sendFile(path.join(__dirname, "../client/build/index.html"))
);
// Error Handling Middleware
app.use((err, req, res, next) => {
console.error("Error:", err.stack);
res.status(err.status || 500).json({ error: err.message || "Internal Server Error" });
});
// Start Server
const Port = process.env.PORT || 8080;
app.listen(Port, () => {
console.log(`Server is Running at port ${Port}`);
app.listen(PORT, () => {
console.log(`Server is running at http://localhost:8080`);
});