Skip to content

Optimization added with rbac #73

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

Merged
merged 5 commits into from
Mar 30, 2024
Merged
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
12 changes: 11 additions & 1 deletion server/src/controllers/auth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import {
import CustomError from "../services/CustomError";
import { randomOTPGenerator, randomPasswordGenerator } from "../services/utils";
import { sendMail, sendOTPMail } from "../services/mailService";
import { PERMISSIONS, getPermittedRoleNames } from "../permissions/permissions";

const prisma = new PrismaClient();

Expand Down Expand Up @@ -54,7 +55,7 @@ const login = errorWrapper(

const user = await prisma.user.findUnique({
where: {
email,
email,
},
include: {
landfill: true,
Expand All @@ -72,6 +73,15 @@ const login = errorWrapper(
throw new Error("Invalid email or password");
}

const roles = await getPermittedRoleNames(PERMISSIONS.LOGIN);

console.log(roles);
console.log(user.roleName);

if (!roles.includes(user.roleName)) {
throw new CustomError("You are not allowed to login", 403);
}

const token = generateToken(
{
id: user.id,
Expand Down
44 changes: 0 additions & 44 deletions server/src/controllers/optimization.ts

This file was deleted.

97 changes: 97 additions & 0 deletions server/src/controllers/schedule.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,97 @@
import { Prisma, PrismaClient } from "@prisma/client";
import { Request, Response } from "express";
import { getSchedule } from "../services/schedule";

import errorWrapper from "../middlewares/errorWrapper";

const prisma = new PrismaClient();

const createSchedule = errorWrapper(
async (req: Request, res: Response) => {
const { date } = req.params;

// check if schedule of this date already exists
const schedule = await prisma.schedule.findFirst({
where: {
scheduleDate: new Date(date),
},
});

if (schedule) {
return res.json({ message: "Schedule Already Exists" });
}

const stsList = await prisma.sTS.findMany();

for (let sts of stsList) {
const { ctw } = await getSchedule(sts.id, new Date(date));

await prisma.sTS.update({
where: {
id: sts.id,
},
data: {
currentTotalWaste: ctw >= 0 ? ctw : 0,
},
});
}

res.json({ message: "Schedule Created" });
},
{ message: "Schedule Creation Failed", statusCode: 500 }
);

const getScheduleBySTS = errorWrapper(async (req: Request, res: Response) => {
const stsId = req.params.stsId;
const schedules = await prisma.schedule.findMany({
where: {
stsId: stsId,
},
});

res.json(schedules);
});

const searchSchedule = errorWrapper(async (req: Request, res: Response) => {
const { stsId, date } = req.query;

let where: Prisma.ScheduleWhereInput | undefined = undefined;

if (stsId || date) {
where = {};
if (stsId) {
where.stsId = stsId as string;
}

if (date) {
const dateObject = {
gte: new Date(date as string),
lt: new Date(
new Date(date as string).setDate(
new Date(date as string).getDate() + 1
)
),
};
where.scheduleDate = dateObject;
}
}

const schedules = await prisma.schedule.findMany({
where,
include: {
sts: true,
vehicle: {
include: {
landFill: true,
},
},
},
orderBy: {
scheduleTime: "asc",
},
});

res.json(schedules);
});

export { createSchedule, getScheduleBySTS, searchSchedule };
29 changes: 26 additions & 3 deletions server/src/controllers/trip.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,15 @@ const createTrip = errorWrapper(async (req: Request, res: Response) => {
const vehicle = stsVehicleInfo.vehicle;
const sts = stsVehicleInfo.sts;

await prisma.sTS.update({
where: {
id: sts.id,
},
data: {
currentTotalWaste: Number(sts.currentTotalWaste) - weightOfWaste,
},
});

const unloadedFuelCostPerKm = Number(vehicle.unloadedFuelCostPerKm);
const loadedFuelCostPerKm = Number(vehicle.loadedFuelCostPerKm);
const capacity = Number(vehicle.capacity);
Expand All @@ -61,12 +70,10 @@ const createTrip = errorWrapper(async (req: Request, res: Response) => {
});

const getListOfTrips = errorWrapper(async (req: Request, res: Response) => {

const { tripStatus, landfillId } = req.query;

let where: Prisma.TripWhereInput | undefined = undefined;


if (tripStatus || landfillId) {
where = {};
if (tripStatus) {
Expand Down Expand Up @@ -98,9 +105,10 @@ const completeTrip = errorWrapper(async (req: Request, res: Response) => {
}

const landfillId = trip.landfillId;

const vehicleId = trip.vehicleId;

prisma.landfillVehicleEntry.create({
await prisma.landfillVehicleEntry.create({
data: {
landfillId,
vehicleId,
Expand All @@ -109,6 +117,21 @@ const completeTrip = errorWrapper(async (req: Request, res: Response) => {
},
});

const landfill = await prisma.landfill.findUnique({
where: {
id: landfillId,
},
});

await prisma.landfill.update({
where: {
id: landfillId,
},
data: {
currentTotalWaste: landfill?.currentTotalWaste + weightOfWaste,
},
});

const shortage = Number(trip.weightOfWaste) - weightOfWaste;

const tripStartTime = new Date(trip.tripStartTime as Date);
Expand Down
17 changes: 10 additions & 7 deletions server/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,9 @@ import landfillEntryRoute from "./routes/landfillVehicle";
import stsEntryRoute from "./routes/stsVehicle";
import billRoute from "./routes/bills";
import tripRoute from "./routes/trip";
import scheduleRoute from "./routes/schedule";
import cors from "cors";
import authChecker from "./middlewares/auth";

const prisma = new PrismaClient();

Expand All @@ -34,14 +36,15 @@ app.use(urlencoded({ extended: true }));
app.use("/auth", authRoute);
app.use("/users", userRoute);
app.use("/profile", profileRoute);
app.use("/rbac", rbacRoute);
app.use("/vehicles", vehicleRoute);
app.use("/sts", stsRoute);
app.use("/landfills", landfillRoute);
app.use("/landfill-entry", landfillEntryRoute);
app.use("/sts-entry", stsEntryRoute);
app.use("/bills", billRoute);
app.use("/rbac", rbacRoute); // authentication and authorization both will be added here
app.use("/vehicles", authChecker, vehicleRoute);
app.use("/sts", authChecker, stsRoute);
app.use("/landfills", authChecker, landfillRoute);
app.use("/landfill-entry", authChecker, landfillEntryRoute);
app.use("/sts-entry", authChecker, stsEntryRoute);
app.use("/bills", authChecker, billRoute);
app.use("/trips", tripRoute);
app.use("/schedules", scheduleRoute);

app.get("/", (req, res) => {
res.send("EcoSync Server is Up...");
Expand Down
23 changes: 19 additions & 4 deletions server/src/prisma/schema.prisma
Original file line number Diff line number Diff line change
Expand Up @@ -73,9 +73,10 @@ model Vehicle {
LandfillVehicleEntry LandfillVehicleEntry[]
Bill Bill[]

createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
Trip Trip[]
Schedule Schedule[]
}

model STS {
Expand All @@ -92,9 +93,10 @@ model STS {
manager User[]
Trip Trip[]

createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
Bill Bill[]
Schedule Schedule[]
}

model Landfill {
Expand Down Expand Up @@ -190,3 +192,16 @@ model Trip {
updatedAt DateTime @updatedAt
Bill Bill[]
}

model Schedule {
id String @id @default(uuid())
sts STS @relation(fields: [stsId], references: [id], onDelete: Cascade)
stsId String
vehicle Vehicle @relation(fields: [vehicleId], references: [id], onDelete: Cascade)
vehicleId String
scheduleDate DateTime
scheduleTime String
wasteAmount Decimal? @db.Decimal(10, 2)
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
}
6 changes: 4 additions & 2 deletions server/src/routes/auth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,10 +17,12 @@ const router = express.Router();
router
.route("/create")
.post(authChecker, authorizer(PERMISSIONS.CREATE_USER), createUser);
router.route("/login").post(login); // add permission
router.route("/login").post(login); // add permission, have to do it manually, done
router.route("/logout").get(authChecker, logout);
router.route("/reset-password/initiate").post(resetPasswordInit);
router.route("/reset-password/confirm").post(resetPasswordConfirm);
router.route("/change-password").post(authChecker, updatePassword); // add permission
router
.route("/change-password")
.post(authChecker, authorizer(PERMISSIONS.CHANGE_PASSWORD), updatePassword); // add permission

export default router;
13 changes: 10 additions & 3 deletions server/src/routes/bills.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,13 +10,20 @@ import {
getListOfBills,
removeBill,
} from "../controllers/bills";
import { authorizer } from "../middlewares/authorizer";
import { PERMISSIONS } from "../permissions/permissions";
import authChecker from "../middlewares/auth";

router.route("/").get(fetchBills);
router.route("/search").get(getListOfBills); // add permission
router.route("/search").get(authorizer(PERMISSIONS.GET_BILLS), getListOfBills); // add permission
router.route("/create").post(createBill);
router.route("/:billId").get(fetchBill);
router.route("/:billId").put(editBill);
router.route("/:billId").delete(removeBill); // add permission
router.route("/create-from-trip/").post(createBillFromTrip); // add permission
router
.route("/:billId")
.delete(authorizer(PERMISSIONS.DELETE_BILL), removeBill); // add permission
router
.route("/create-from-trip/")
.post(authorizer(PERMISSIONS.CREATE_BILL), createBillFromTrip); // add permission

export default router;
20 changes: 17 additions & 3 deletions server/src/routes/landfillVehicle.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,12 +6,26 @@ import {
getVehicleEntryById,
updateVehicleEntry,
} from "../controllers/landfillVehicle";
import { authorizer } from "../middlewares/authorizer";
import { PERMISSIONS } from "../permissions/permissions";
const router = express.Router();

router.route("/create").post(addVehicleEntry); // add permission
router
.route("/create")
.post(authorizer(PERMISSIONS.CREATE_LANDFILL_VEHICLE_ENTRY), addVehicleEntry); // add permission
router.route("/").get(getAllVehicleEntries);
router.route("/:vehicleEntryId").get(getVehicleEntryById);
router.route("/:vehicleEntryId").put(updateVehicleEntry); // add permission
router.route("/:vehicleEntryId").delete(deleteVehicleEntry); // add permission
router
.route("/:vehicleEntryId")
.put(
authorizer(PERMISSIONS.UPDATE_LANDFILL_VEHICLE_ENTRY),
updateVehicleEntry
); // add permission
router
.route("/:vehicleEntryId")
.delete(
authorizer(PERMISSIONS.DELETE_LANDFILL_VEHICLE_ENTRY),
deleteVehicleEntry
); // add permission

export default router;
Loading