From b2c31774f217a62e440295aaba67f499b483c60c Mon Sep 17 00:00:00 2001 From: Methapon2001 <61303214+Methapon2001@users.noreply.github.com> Date: Wed, 31 Jul 2024 11:43:07 +0700 Subject: [PATCH] feat: image endpoint get or upload --- src/controllers/user-controller.ts | 43 ++++++++++++++++++++++++++++++ 1 file changed, 43 insertions(+) diff --git a/src/controllers/user-controller.ts b/src/controllers/user-controller.ts index 5a1fa45..a1bf870 100644 --- a/src/controllers/user-controller.ts +++ b/src/controllers/user-controller.ts @@ -658,6 +658,49 @@ export class UserController extends Controller { where: { id: userId }, }); } + + @Get("{userId}/image") + async getUserImageByUserId(@Request() req: RequestWithUser, @Path() userId: string) { + const url = await presignedGetObjectIfExist(MINIO_BUCKET, imageLocation(userId), 60 * 60); + + if (!url) { + throw new HttpError(HttpStatus.NOT_FOUND, "Image cannot be found", "imageNotFound"); + } + + return req.res?.redirect(url); + } + + @Put("{userId}/image") + @Security("keycloak", ["system", "head_of_admin", "admin", "branch_admin", "branch_manager"]) + async setUserImageByUserId(@Request() req: RequestWithUser, @Path() userId: string) { + const record = await prisma.user.findFirst({ + include: { + branch: { where: { userId: req.user.sub } }, + }, + where: { + id: userId, + }, + }); + + if (!record) { + throw new HttpError(HttpStatus.NOT_FOUND, "User cannot be found.", "userNotFound"); + } + + if ( + !["system", "head_of_admin", "admin"].some((v) => req.user.roles?.includes(v)) && + !record.branch.some((v) => v.userId === req.user.sub) + ) { + throw new HttpError( + HttpStatus.FORBIDDEN, + "You do not have permission to perform this action.", + "noPermission", + ); + } + + return req.res?.redirect( + await minio.presignedPutObject(MINIO_BUCKET, imageLocation(userId), 12 * 60 * 60), + ); + } } function attachmentLocation(uid: string) {