Skip to content

Commit

Permalink
Merge branch 'room-vacancy-lost-and-found' into auth-complete
Browse files Browse the repository at this point in the history
  • Loading branch information
Nailsonseat committed Feb 11, 2024
2 parents 5a81236 + b069d7e commit b9dc625
Show file tree
Hide file tree
Showing 32 changed files with 1,720 additions and 234 deletions.
4 changes: 2 additions & 2 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,11 @@
backend/.DS_Store
node_modules/
backend/.env

## Frontend ignored file (Root level)
backend/.idea


## Frontend ignored file (Root level)
frontend/.env

# Miscellaneous
frontend/*.class
Expand Down
7 changes: 7 additions & 0 deletions backend/app.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,10 @@ import cors from "cors";
import tokenRequired from "./middlewares/tokenRequired.js";
import adminResource from "./resources/adminResource.js";

import roomListResource from "./resources/rooms/roomListResource.js";
import roomResource from "./resources/rooms/roomResource.js";
import lostAndFoundListResource from "./resources/lostAndFound/lostAndFoundListResource.js";

const PORT = `${process.env.PORT || 3000}`;
const app = express();

Expand All @@ -26,6 +30,9 @@ app.use("/admin-auth", adminAuthResource);
app.use(authResource);
app.use("otp", otpResource);
app.use("/", testResource);
app.use("/rooms", roomListResource);
app.use("/room", roomResource);
app.use("/lost-and-found", lostAndFoundListResource);

app.get("/protected", tokenRequired, (req, res) => {
res.json({ message: "Access granted" });
Expand Down
33 changes: 18 additions & 15 deletions backend/constants/errorMessages.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,26 +2,29 @@
export const userAlreadyExists = "User with this email already exists!";
export const userNotFound = "User with this email does not exist!";
export const incorrectPassword = "Incorrect password.";
export const internalServerError = "Internal Server Error. Please try again later.";
export const internalServerError =
"Internal Server Error. Please try again later.";
export const userCreated = "User created successfully";

//Database Connection
export const databaseConnected = "Database connected successfully";
export const databaseDisconnected = "Database disconnected";
export const databaseConnectionError = "Error while connecting with the database";
export const databaseConnectionError =
"Error while connecting with the database";

// OTP
export const emailIsRequired = 'Email is required';
export const failedToSendOTPEmail = 'Failed to send OTP to email';
export const emailAndOTPRequired = 'Email and OTP are required';
export const noOTPFoundForEmail = 'No OTP found for the email';
export const incorrectOTP = 'Incorrect OTP';
export const otpVerfied = 'OTP verified successfully';
export const otpSent = 'OTP sent successfully';
// OTP
export const emailIsRequired = "Email is required";
export const failedToSendOTPEmail = "Failed to send OTP to to email";
export const emailAndOTPRequired = "Email and OTP are required";
export const noOTPFoundForEmail = "No OTP found for the email";
export const incorrectOTP = "Incorrect OTP";
export const otpVerfied = "OTP verified successfully";
export const otpSent = "OTP sent successfully";

// Auth Middleware
export const noAuthToken = 'No auth token, access denied';
export const invalidAuthToken = 'Invalid token';
export const tokenVerificationFailed = 'Token verification failed, authorization denied.';
export const invalidUserType = 'Invalid user type';
export const tokenUpdateError= 'Error updating token';
export const noAuthToken = "No auth token, access denied";
export const invalidAuthToken = "Invalid token";
export const tokenVerificationFailed =
"Token verification failed, authorization denied.";
export const invalidUserType = "Invalid user type";
export const tokenUpdateError = "Error updating token";
15 changes: 15 additions & 0 deletions backend/middlewares/multerConfig.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
import multer from "multer";

// Define storage configuration
const storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, "uploads/");
},
filename: function (req, file, cb) {
cb(null, file.originalname);
},
});

const uploader = multer({ storage: storage });

export default uploader;
53 changes: 28 additions & 25 deletions backend/models/lost_and_found.js
Original file line number Diff line number Diff line change
@@ -1,30 +1,33 @@
import mongoose from 'mongoose';
import mongoose from "mongoose";

const lostAndFoundItemSchema = new mongoose.Schema({
name: {
type: String,
required: true
},
lastSeenLocation: {
type: String,
},
imagePath: {
type: String,
},
description: {
type: String,
required: true
},
contactNumber: {
type: String,
required: true
},
isLost: {
type: Boolean,
required: true
}
name: {
type: String,
required: true,
},
lastSeenLocation: {
type: String,
},
imagePath: {
type: String,
nullable: true,
},
description: {
type: String,
},
contactNumber: {
type: String,
required: true,
},
isLost: {
type: Boolean,
required: true,
},
});

const LostAndFoundItem = mongoose.model('LostAndFoundItem', lostAndFoundItemSchema);
const LostAndFoundItem = mongoose.model(
"LostAndFoundItem",
lostAndFoundItemSchema
);

export default LostAndFoundItem;
export default LostAndFoundItem;
36 changes: 15 additions & 21 deletions backend/models/room.js
Original file line number Diff line number Diff line change
@@ -1,26 +1,20 @@

const mongoose = require('mongoose');
import mongoose from "mongoose";

const roomSchema = new mongoose.Schema({
id: {
type: String,
required: true,
},
name: {
type: String,
required: true,
},
vacant: {
type: Boolean,
default: true,
},
occupantId: {
type: String,
default: null,
},
name: {
type: String,
required: true,
},
vacant: {
type: Boolean,
default: true,
},
occupantId: {
type: String,
default: null,
},
});

const Room = mongoose.model('Room', roomSchema);

module.exports = Room;
const Room = mongoose.model("Room", roomSchema);

export default Room;
74 changes: 74 additions & 0 deletions backend/resources/lostAndFound/lostAndFoundListResource.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
import { Router } from "express";
import LostAndFoundItem from "../../models/lost_and_found.js";
import fs from "fs/promises";
import uploader from "../../middlewares/multerConfig.js";

const router = Router();

// GET method to retrieve all items
router.get("/", async (req, res) => {
try {
// Query the database to retrieve all items
const items = await LostAndFoundItem.find({});

// Create an empty array to store items with images
const itemsWithImages = [];

// Iterate through each item
for (const item of items) {
// Check if imagePath is null
let imagePathBase64 = null;
if (item.imagePath) {
// Read the image file if imagePath is not null
const bufferImage = await fs.readFile(item.imagePath);
imagePathBase64 = bufferImage.toString("base64");
}

// Create a new object with the required attributes
const itemWithImage = {
_id: item._id,
name: item.name,
lastSeenLocation: item.lastSeenLocation,
imagePath: imagePathBase64, // Set imagePath to null if null in the database
description: item.description,
contactNumber: item.contactNumber,
isLost: item.isLost,
};

// Push the item with image to the array
itemsWithImages.push(itemWithImage);
}

console.log("Retrieved items:", itemsWithImages.length);

// Send the response with the items
res.json(itemsWithImages);
} catch (error) {
// Handle errors
console.error("Error:", error);
res.status(500).send("Error retrieving items");
}
});

// POST method
router.post("/", uploader.single("image"), async (req, res) => {
// Access the uploaded file using req.file
const file = req.file;

// Construct the LostAndFoundItem object with data from the request
const newItem = new LostAndFoundItem({
name: req.body.name,
lastSeenLocation: req.body.lastSeenLocation,
imagePath: file ? file.path : null,
description: req.body.description,
contactNumber: req.body.contactNumber,
isLost: req.body.isLost,
});

// Save the new item to the database
await newItem.save();

res.send("Added new item");
});

export default router;
27 changes: 27 additions & 0 deletions backend/resources/rooms/occupantListResource.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
import { Router } from "express";
import Room from "../../models/room.js";
import Student from "../../models/student.js";
const router = Router();

//GET method
router.get("/", async (req, res) => {
try {
const documentIds = req.body.documentIds; // Assuming the documentIds are sent in the request body

const occupants = await Promise.all(
documentIds.map(async (documentId) => {
const room = await Room.findOne({ documentId });
const occupant = await Student.findOne({ _id: room.occupantId });
return {
occupantName: occupant.name,
roomId: room._id,
};
})
);

res.json(occupants);
} catch (error) {
console.error(error);
res.status(500).json({ message: "Internal Server Error" });
}
});
40 changes: 40 additions & 0 deletions backend/resources/rooms/roomListResource.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
import { Router } from "express";
import Room from "../../models/room.js";
const router = Router();

// GET method
router.get("/", async (req, res) => {
// Your code here
const rooms = await Room.find({});
res.send(rooms);
});

// POST method
router.post("/", async (req, res) => {
try {
// Extract data from request body
const { name, vacant, occupantId } = req.body;

// Create a new room instance
const newRoom = new Room({
name,
vacant: vacant || true, // Set default value if not provided
occupantId: occupantId || null, // Set default value if not provided
});

// Save the new room to the database
await newRoom.save();
console.log("Room created successfully");

// Respond with success message
res
.status(201)
.json({ message: "Room created successfully", room: newRoom });
} catch (error) {
// Handle errors
console.error("Error creating room:", error);
res.status(500).json({ error: "Internal server error" });
}
});

export default router;
28 changes: 28 additions & 0 deletions backend/resources/rooms/roomResource.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
import { Router } from "express";
import Room from "../../models/room.js";
const router = Router();

// PUT method
router.put("/:id", async (req, res) => {
try {
const { id } = req.params;
const { occupantId } = req.body;
const room = await Room.findById(id);
if (!room) {
return res.status(404).json({ error: "Room not found" });
}

room.vacant = false;
room.occupantId = occupantId || room.occupantId;

await room.save();

console.log("Room updated successfully");
res.json({ message: "Room updated successfully", room });
} catch (error) {
console.error("Error updating room:", error);
res.status(500).json({ error: "Internal server error" });
}
});

export default router;
Loading

0 comments on commit b9dc625

Please sign in to comment.