Skip to content

Commit

Permalink
added role checking
Browse files Browse the repository at this point in the history
  • Loading branch information
AydanPirani committed Jul 3, 2024
1 parent 377edfd commit 7ab1da0
Show file tree
Hide file tree
Showing 4 changed files with 63 additions and 16 deletions.
2 changes: 2 additions & 0 deletions src/services/auth/auth-models.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,3 +6,5 @@ export const JwtPayloadValidator = z.object({
userId: z.string(),
roles: Role.array(),
});

export type JwtPayloadType = z.infer<typeof JwtPayloadValidator>;

Check failure on line 10 in src/services/auth/auth-models.ts

View workflow job for this annotation

GitHub Actions / lint

Insert `⏎`
14 changes: 13 additions & 1 deletion src/services/auth/auth-utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
import { Strategy as GoogleStrategy } from "passport-google-oauth20";
import { Config } from "../../config";
import { Database } from "../../database";
import { Role } from "./auth-models";
import { JwtPayloadType, Role } from "./auth-models";

export function createGoogleStrategy(device: string) {
return new GoogleStrategy(
Expand Down Expand Up @@ -46,3 +46,15 @@ export async function getJwtPayloadFromDatabase(userId: string) {

return payload;
}

export function isUser(payload?: JwtPayloadType) {
return payload?.roles.includes(Role.Enum.USER);
}

export function isStaff(payload?: JwtPayloadType) {
return payload?.roles.includes(Role.Enum.STAFF);
}

export function isAdmin(payload?: JwtPayloadType) {
return payload?.roles.includes(Role.Enum.ADMIN);
}

Check failure on line 60 in src/services/auth/auth-utils.ts

View workflow job for this annotation

GitHub Actions / lint

Insert `⏎`
61 changes: 47 additions & 14 deletions src/services/events/events-router.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,17 +3,23 @@ import { StatusCodes } from "http-status-codes";
import { publicEventValidator, privateEventValidator } from "./events-schema";
import { Database } from "../../database";
import { checkInUserToEvent } from "./events-utils";
// import {mongoose} from "mongoose";
import RoleChecker from "../../middleware/role-checker";
import { Role } from "../auth/auth-models";
import { isAdmin, isStaff, isUser } from "../auth/auth-utils";

Check failure on line 8 in src/services/events/events-router.ts

View workflow job for this annotation

GitHub Actions / lint

'isUser' is defined but never used

Check failure on line 8 in src/services/events/events-router.ts

View workflow job for this annotation

GitHub Actions / build

'isUser' is declared but its value is never read.

const eventsRouter = Router();

// Get current or next event based on current time
eventsRouter.get("/currentOrNext", async (req, res, next) => {
eventsRouter.get("/currentOrNext", RoleChecker([], true), async (req, res, next) => {

Check failure on line 13 in src/services/events/events-router.ts

View workflow job for this annotation

GitHub Actions / lint

Replace `"/currentOrNext",·RoleChecker([],·true),` with `⏎····"/currentOrNext",⏎····RoleChecker([],·true),⏎···`
const currentTime = new Date();

Check failure on line 14 in src/services/events/events-router.ts

View workflow job for this annotation

GitHub Actions / lint

Insert `····`
const payload = res.locals.payload;

Check failure on line 15 in src/services/events/events-router.ts

View workflow job for this annotation

GitHub Actions / lint

Replace `····` with `········`

const isUser = !(isStaff(payload) || isAdmin(payload))

Check failure on line 17 in src/services/events/events-router.ts

View workflow job for this annotation

GitHub Actions / lint

Replace `····const·isUser·=·!(isStaff(payload)·||·isAdmin(payload))` with `········const·isUser·=·!(isStaff(payload)·||·isAdmin(payload));`

try {

Check failure on line 19 in src/services/events/events-router.ts

View workflow job for this annotation

GitHub Actions / lint

Insert `····`
const event = await Database.EVENTS.findOne({

Check failure on line 20 in src/services/events/events-router.ts

View workflow job for this annotation

GitHub Actions / lint

Insert `····`
startTime: { $gte: currentTime },

Check failure on line 21 in src/services/events/events-router.ts

View workflow job for this annotation

GitHub Actions / lint

Replace `············` with `················`
isVisible: isUser ? { $eq: true } : {},
}).sort({ startTime: 1 });

if (event) {
Expand All @@ -29,35 +35,63 @@ eventsRouter.get("/currentOrNext", async (req, res, next) => {
});

// Get all events
eventsRouter.get("/", async (req, res, next) => {
eventsRouter.get("/", RoleChecker([], true), async (req, res, next) => {
const payload = res.locals.payload;

var filterFunction;

try {
const unfiltered_events = await Database.EVENTS.find();
const filtered_events = unfiltered_events.map((unfiltered_event) => {
return publicEventValidator.parse(unfiltered_event.toJSON());
});
var unfiltered_events = await Database.EVENTS.find();

if (isStaff(payload) || isAdmin(payload)) {
filterFunction = (x: any) => privateEventValidator.parse(x);
} else {
unfiltered_events = unfiltered_events.filter(x => x.isVisible)
filterFunction = (x: any) => publicEventValidator.parse(x);
}

const filtered_events = unfiltered_events.map(filterFunction);
console.log(filtered_events)
return res.status(StatusCodes.OK).json(filtered_events);
} catch (error) {
next(error);
}
});

eventsRouter.get("/:EVENTID", async (req, res, next) => {
eventsRouter.get("/:EVENTID", RoleChecker([], true), async (req, res, next) => { // add RoleChecker here as well
const eventId = req.params.EVENTID;
const payload = res.locals.payload;

var filterFunction;

try {
const event = await Database.EVENTS.findOne({ eventId: eventId });

if (!event) {
return res
.status(StatusCodes.NOT_FOUND)
.json({ error: "DoesNotExist" });
}
const validatedData = publicEventValidator.parse(event.toJSON());

if (isStaff(payload) || isAdmin(payload)) {
filterFunction = privateEventValidator.parse;
} else {
filterFunction = publicEventValidator.parse;
if (!event.isVisible) {
return res
.status(StatusCodes.NOT_FOUND)
.json({ error: "DoesNotExist" });
}
}

const validatedData = filterFunction(event.toObject());
return res.status(StatusCodes.OK).json(validatedData);
} catch (error) {
next(error);
}
});

eventsRouter.post("/", async (req, res, next) => {
eventsRouter.post("/", RoleChecker([Role.Enum.STAFF]), async (req, res, next) => {
try {
const validatedData = privateEventValidator.parse(req.body);
const event = new Database.EVENTS(validatedData);
Expand All @@ -68,7 +102,7 @@ eventsRouter.post("/", async (req, res, next) => {
}
});

eventsRouter.put("/:EVENTID", async (req, res, next) => {
eventsRouter.put("/:EVENTID", RoleChecker([Role.Enum.STAFF], true), async (req, res, next) => {
const eventId = req.params.EVENTID;
try {
const validatedData = privateEventValidator.parse(req.body);
Expand All @@ -90,10 +124,9 @@ eventsRouter.put("/:EVENTID", async (req, res, next) => {
});

// Delete event
eventsRouter.delete("/:EVENTID", async (req, res, next) => {
eventsRouter.delete("/:EVENTID", RoleChecker([Role.Enum.STAFF], true), async (req, res, next) => {
const eventId = req.params.EVENTID;
try {
// const objectId = mongoose.Types.ObjectId(eventId)
await Database.EVENTS.findOneAndDelete({ eventId: eventId });

return res.sendStatus(StatusCodes.NO_CONTENT);
Expand All @@ -102,7 +135,7 @@ eventsRouter.delete("/:EVENTID", async (req, res, next) => {
}
});

eventsRouter.post("/check-in", async (req, res, next) => {
eventsRouter.post("/check-in", RoleChecker([Role.Enum.STAFF], true), async (req, res, next) => { // add RoleChecker for staff
try {
const { eventId, userId } = req.body;
const result = await checkInUserToEvent(eventId, userId);
Expand Down
2 changes: 1 addition & 1 deletion src/services/events/events-schema.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,12 +13,12 @@ export const publicEventValidator = z.object({
description: z.string(),
isVirtual: z.boolean(),
imageUrl: z.string().nullable().optional(),
isVisible: z.boolean().default(false),
eventType: EventType,
});

export const privateEventValidator = publicEventValidator.extend({
attendanceCount: z.number(),
isVisible: z.boolean(),
});

export const EventSchema = new Schema({
Expand Down

0 comments on commit 7ab1da0

Please sign in to comment.