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

#106 [FEAT]: Add search functionality for classrooms by name and for users by username #107

Merged
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
8 changes: 4 additions & 4 deletions src/controllers/applicationAnswerController.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import { ApplicationAnswer, User, UserRole, VisibilityMode } from '@prisma/clien
import * as yup from 'yup';
import prismaClient from '../services/prismaClient';
import errorFormatter from '../services/errorFormatter';
import { unlinkSync } from 'fs';
import { unlinkSync, existsSync } from 'fs';

const checkAuthorization = async (
user: User,
Expand Down Expand Up @@ -324,7 +324,7 @@ export const createApplicationAnswer = async (req: Request, res: Response) => {
res.status(201).json({ message: 'Application answer created.', data: createdApplicationAnswer });
} catch (error: any) {
const files = req.files as Express.Multer.File[];
for (const file of files) unlinkSync(file.path);
for (const file of files) if (existsSync(file.path)) unlinkSync(file.path);
res.status(400).json(errorFormatter(error));
}
};
Expand Down Expand Up @@ -438,7 +438,7 @@ export const updateApplicationAnswer = async (req: Request, res: Response): Prom
},
select: { id: true, path: true },
});
for (const file of filesToDelete) unlinkSync(file.path);
for (const file of filesToDelete) if (existsSync(file.path)) unlinkSync(file.path);
await prisma.file.deleteMany({ where: { id: { in: filesToDelete.map((file) => file.id) } } });
// Create new files (udpating files is not supported)
const itemAnswerFiles = files
Expand Down Expand Up @@ -512,7 +512,7 @@ export const updateApplicationAnswer = async (req: Request, res: Response): Prom
res.status(200).json({ message: 'Application answer updated.', data: upsertedApplicationAnswer });
} catch (error: any) {
const files = req.files as Express.Multer.File[];
for (const file of files) unlinkSync(file.path);
for (const file of files) if (existsSync(file.path)) unlinkSync(file.path);
res.status(400).json(errorFormatter(error));
}
};
Expand Down
12 changes: 8 additions & 4 deletions src/controllers/applicationController.ts
Original file line number Diff line number Diff line change
Expand Up @@ -120,10 +120,14 @@ const fields = {

const fieldsWViewers = {
...fields,
viewersUser: { select: { id: true, username: true } },
viewersClassroom: { select: { id: true, institution: { select: { name: true } } } },
answersViewersUser: { select: { id: true, username: true } },
answersViewersClassroom: { select: { id: true, institution: { select: { name: true } } } },
viewersUser: { select: { id: true, username: true, classrooms: { select: { id: true, name: true } } } },
viewersClassroom: {
select: { id: true, name: true, institution: { select: { name: true } }, users: { select: { id: true, username: true } } },
},
answersViewersUser: { select: { id: true, username: true, classrooms: { select: { id: true, name: true } } } },
answersViewersClassroom: {
select: { id: true, name: true, institution: { select: { name: true } }, users: { select: { id: true, username: true } } },
},
};

const fieldsWProtocol = {
Expand Down
42 changes: 40 additions & 2 deletions src/controllers/classroomController.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,12 @@ const fields = {
updatedAt: true,
};

const publicFields = {
id: true,
name: true,
users: { select: { id: true, name: true, username: true, role: true } },
};

// Only admins or the coordinator of the institution can perform C-UD operations on classrooms
const checkAuthorization = async (user: User, classroomId: number | undefined, institutionId: number | undefined, action: string) => {
switch (action) {
Expand Down Expand Up @@ -51,6 +57,11 @@ const checkAuthorization = async (user: User, classroomId: number | undefined, i
}
}
break;
case 'search':
if (user.role === UserRole.USER) {
throw new Error('This user is not authorized to perform this action');
}
break;
case 'getMy':
// All users can perform get my classrooms operation (the result will be filtered based on the user)
break;
Expand All @@ -64,7 +75,7 @@ export const createClassroom = async (req: Request, res: Response) => {
.object()
.shape({
id: yup.number().min(1),
name: yup.string().min(1).max(255).required(),
name: yup.string().min(3).max(255).required(),
institutionId: yup.number().required(),
users: yup.array().of(yup.number()).min(2).required(),
})
Expand Down Expand Up @@ -98,7 +109,7 @@ export const updateClassroom = async (req: Request, res: Response): Promise<void
// Yup schemas
const updateClassroomSchema = yup
.object()
.shape({ name: yup.string().min(1).max(255), users: yup.array().of(yup.number()).min(2) })
.shape({ name: yup.string().min(3).max(255), users: yup.array().of(yup.number()).min(2) })
.noUnknown();
// Yup parsing/validation
const classroom = await updateClassroomSchema.validate(req.body);
Expand Down Expand Up @@ -169,6 +180,33 @@ export const getMyClassrooms = async (req: Request, res: Response): Promise<void
}
};

export const searchClassroomByName = async (req: Request, res: Response): Promise<void> => {
try {
// User from passport-jwt
const curUser = req.user as User;
// Check if user is authorized to search users
await checkAuthorization(curUser, undefined, undefined, 'search');
// Yup schemas
const searchUserSchema = yup
.object()
.shape({
term: yup.string().min(3).max(20).required(),
})
.noUnknown();
// Yup parsing/validation
const { term } = await searchUserSchema.validate(req.body);
// Prisma operation
const classrooms = await prismaClient.classroom.findMany({
where: { name: { startsWith: term } },
select: publicFields,
});

res.status(200).json({ message: 'Searched classrooms found.', data: classrooms });
} catch (error: any) {
res.status(400).json(errorFormatter(error));
}
};

export const deleteClassroom = async (req: Request, res: Response): Promise<void> => {
try {
// ID from params
Expand Down
18 changes: 9 additions & 9 deletions src/controllers/protocolController.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import { ItemType, ItemGroupType, PageType, ItemValidationType, User, UserRole,
import * as yup from 'yup';
import prismaClient from '../services/prismaClient';
import errorFormatter from '../services/errorFormatter';
import { unlinkSync } from 'fs';
import { unlinkSync, existsSync } from 'fs';

const checkAuthorization = async (user: User, protocolId: number | undefined, action: string) => {
switch (action) {
Expand Down Expand Up @@ -315,10 +315,10 @@ const fields = {
const fieldsWViewers = {
...fields,
managers: { select: { id: true, username: true } },
viewersUser: { select: { id: true, username: true } },
viewersClassroom: { select: { id: true } },
answersViewersUser: { select: { id: true, username: true } },
answersViewersClassroom: { select: { id: true } },
viewersUser: { select: { id: true, username: true, classrooms: { select: { id: true, name: true } } } },
viewersClassroom: { select: { id: true, name: true, users: { select: { id: true, username: true } } } },
answersViewersUser: { select: { id: true, username: true, classrooms: { select: { id: true, name: true } } } },
answersViewersClassroom: { select: { id: true, name: true, users: { select: { id: true, username: true } } } },
appliers: { select: { id: true, username: true } },
};

Expand Down Expand Up @@ -560,7 +560,7 @@ export const createProtocol = async (req: Request, res: Response) => {
res.status(201).json({ message: 'Protocol created.', data: createdProtocol });
} catch (error: any) {
const files = req.files as Express.Multer.File[];
for (const file of files) unlinkSync(file.path);
for (const file of files) if (existsSync(file.path)) unlinkSync(file.path);
res.status(400).json(errorFormatter(error));
}
};
Expand Down Expand Up @@ -836,7 +836,7 @@ export const updateProtocol = async (req: Request, res: Response): Promise<void>
where: { id: { notIn: item.filesIds as number[] }, itemId: upsertedItem.id },
select: { id: true, path: true },
});
for (const file of filesToDelete) unlinkSync(file.path);
for (const file of filesToDelete) if (existsSync(file.path)) unlinkSync(file.path);
await prisma.file.deleteMany({ where: { id: { in: filesToDelete.map((file) => file.id) } } });
const itemFiles = files
.filter((file) =>
Expand Down Expand Up @@ -874,7 +874,7 @@ export const updateProtocol = async (req: Request, res: Response): Promise<void>
where: { id: { notIn: itemOption.filesIds as number[] }, itemOptionId: upsertedItemOption.id },
select: { id: true, path: true },
});
for (const file of filesToDelete) unlinkSync(file.path);
for (const file of filesToDelete) if (existsSync(file.path)) unlinkSync(file.path);
await prisma.file.deleteMany({ where: { id: { in: filesToDelete.map((file) => file.id) } } });
const itemOptionFiles = files
.filter((file) =>
Expand Down Expand Up @@ -983,7 +983,7 @@ export const updateProtocol = async (req: Request, res: Response): Promise<void>
res.status(200).json({ message: 'Protocol updated.', data: upsertedProtocol });
} catch (error: any) {
const files = req.files as Express.Multer.File[];
for (const file of files) unlinkSync(file.path);
for (const file of files) if (existsSync(file.path)) unlinkSync(file.path);
res.status(400).json(errorFormatter(error));
}
};
Expand Down
50 changes: 45 additions & 5 deletions src/controllers/userController.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import { User, UserRole } from '@prisma/client';
import * as yup from 'yup';
import prismaClient from '../services/prismaClient';
import errorFormatter from '../services/errorFormatter';
import { unlinkSync } from 'fs';
import { unlinkSync, existsSync } from 'fs';

// Only admins or the user itself can perform --UD operations on users
const checkAuthorization = async (curUser: User, userId: number | undefined, role: UserRole | undefined, action: string) => {
Expand Down Expand Up @@ -31,7 +31,7 @@ const checkAuthorization = async (curUser: User, userId: number | undefined, rol
(curUser.role === UserRole.APPLIER && role !== UserRole.USER && role !== UserRole.APPLIER) ||
(curUser.role === UserRole.USER && role !== UserRole.USER)
) {
throw new Error('This user is not authorized to perform this action ' + curUser.id + ' ' + userId);
throw new Error('This user is not authorized to perform this action');
}
break;
case 'getAll':
Expand All @@ -51,6 +51,11 @@ const checkAuthorization = async (curUser: User, userId: number | undefined, rol
}
}
break;
case 'search':
if (curUser.role === UserRole.USER) {
throw new Error('This user is not authorized to perform this action');
}
break;
case 'delete':
// Only ADMINs or the user itself can perform update/delete operations on it
if (curUser.role !== UserRole.ADMIN && curUser.id !== userId) {
Expand All @@ -74,6 +79,14 @@ const fields = {
updatedAt: true,
};

const publicFields = {
id: true,
name: true,
username: true,
institution: { select: { id: true, name: true } },
classrooms: { select: { id: true, name: true } },
};

export const createUser = async (req: Request, res: Response) => {
try {
// Yup schemas
Expand Down Expand Up @@ -114,7 +127,7 @@ export const createUser = async (req: Request, res: Response) => {
res.status(201).json({ message: 'User created.', data: createdUser });
} catch (error: any) {
const file = req.file as Express.Multer.File;
if (file) unlinkSync(file.path);
if (file) if (existsSync(file.path)) unlinkSync(file.path);
res.status(400).json(errorFormatter(error));
}
};
Expand Down Expand Up @@ -150,7 +163,7 @@ export const updateUser = async (req: Request, res: Response): Promise<void> =>
where: { id: { not: user.profileImageId }, users: { some: { id: userId } } },
select: { id: true, path: true },
});
for (const file of filesToDelete) unlinkSync(file.path);
for (const file of filesToDelete) if (existsSync(file.path)) unlinkSync(file.path);
await prisma.file.deleteMany({ where: { id: { in: filesToDelete.map((file) => file.id) } } });
const updatedUser = await prisma.user.update({
where: { id: userId },
Expand All @@ -174,7 +187,7 @@ export const updateUser = async (req: Request, res: Response): Promise<void> =>
res.status(200).json({ message: 'User updated.', data: updatedUser });
} catch (error: any) {
const file = req.file as Express.Multer.File;
if (file) unlinkSync(file.path);
if (file) if (existsSync(file.path)) unlinkSync(file.path);
res.status(400).json(errorFormatter(error));
}
};
Expand Down Expand Up @@ -211,6 +224,33 @@ export const getUser = async (req: Request, res: Response): Promise<void> => {
}
};

export const searchUserByUsername = async (req: Request, res: Response): Promise<void> => {
try {
// User from passport-jwt
const curUser = req.user as User;
// Check if user is authorized to search users
await checkAuthorization(curUser, undefined, undefined, 'search');
// Yup schemas
const searchUserSchema = yup
.object()
.shape({
term: yup.string().min(3).max(20).required(),
})
.noUnknown();
// Yup parsing/validation
const { term } = await searchUserSchema.validate(req.body);
// Prisma operation
const users = await prismaClient.user.findMany({
where: { username: { startsWith: term } },
select: publicFields,
});

res.status(200).json({ message: 'Searched users found.', data: users });
} catch (error: any) {
res.status(400).json(errorFormatter(error));
}
};

export const deleteUser = async (req: Request, res: Response): Promise<void> => {
try {
// ID from params
Expand Down
47 changes: 47 additions & 0 deletions src/routes/classroomRoutes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import {
getClassroom,
deleteClassroom,
getMyClassrooms,
searchClassroomByName,
} from '../controllers/classroomController';
import passport from '../services/passportAuth';

Expand Down Expand Up @@ -276,6 +277,52 @@ router.get('/getMyClassrooms', passport.authenticate('jwt', { session: false }),
*/
router.get('/getClassroom/:classroomId', passport.authenticate('jwt', { session: false }), uploader.none(), getClassroom);

/**
* @swagger
* /api/classroom/searchClassroomByName:
* post:
* summary: Search classrooms by name
* tags: [Classroom]
* security:
* - bearerAuth: []
* requestBody:
* required: true
* content:
* multipart/form-data:
* schema:
* type: object
* required:
* - term
* properties:
* term:
* type: string
* description: The search term
* example: 'New York'
* responses:
* 200:
* description: The list of classrooms that match the search term
* content:
* application/json:
* message: Searched classrooms found.
* data:
* type: array
* items:
* $ref: '#/components/schemas/GetClassroom'
* 400:
* description: Request data validation failed
* content:
* application/json:
* error:
* message: Bad Request.
* 500:
* description: Some error occurred while searching classrooms.
* content:
* application/json:
* error:
* message: Internal Server Error.
*/
router.post('/searchClassroomByName', passport.authenticate('jwt', { session: false }), uploader.none(), searchClassroomByName);

/**
* @swagger
* /api/classroom/deleteClassroom/{classroomId}:
Expand Down
Loading