jws-backend/src/controllers/02-user-controller.ts

813 lines
22 KiB
TypeScript
Raw Normal View History

import {
Body,
Controller,
Delete,
Get,
Put,
Path,
Post,
Query,
Request,
Route,
Security,
Tags,
2024-10-22 17:54:46 +07:00
Head,
} from "tsoa";
import { Branch, Prisma, Status, User, UserType } from "@prisma/client";
2024-04-05 10:42:16 +07:00
import prisma from "../db";
import { RequestWithUser } from "../interfaces/user";
import HttpError from "../interfaces/http-error";
import HttpStatus from "../interfaces/http-status";
2024-04-17 16:35:35 +07:00
import {
addUserRoles,
createUser,
deleteUser,
editUser,
2024-07-01 13:24:02 +07:00
listRole,
2024-04-17 16:35:35 +07:00
getUserRoles,
removeUserRoles,
} from "../services/keycloak";
2024-09-05 09:01:28 +07:00
import { isSystem } from "../utils/keycloak";
2024-10-22 17:54:46 +07:00
import {
deleteFile,
deleteFolder,
fileLocation,
getFile,
getPresigned,
listFile,
setFile,
} from "../utils/minio";
2024-09-09 14:51:17 +07:00
import { filterStatus } from "../services/prisma";
import {
branchRelationPermInclude,
createPermCheck,
createPermCondition,
} from "../services/permission";
import {
connectOrDisconnect,
connectOrNot,
queryOrNot,
whereAddressQuery,
} from "../utils/relation";
import { isUsedError, notFoundError, relationError } from "../utils/error";
2024-10-22 17:59:31 +07:00
import { retry } from "../utils/func";
if (!process.env.MINIO_BUCKET) {
throw Error("Require MinIO bucket.");
}
2024-09-04 11:40:55 +07:00
const MANAGE_ROLES = ["system", "head_of_admin", "admin", "branch_manager"];
function globalAllow(user: RequestWithUser["user"]) {
const listAllowed = ["system", "head_of_admin"];
return user.roles?.some((v) => listAllowed.includes(v)) || false;
}
type UserCreate = {
status?: Status;
2024-04-09 13:05:49 +07:00
userType: UserType;
userRole: string;
username: string;
2024-09-12 09:48:56 +07:00
citizenId: string;
citizenIssue: Date;
citizenExpire?: Date | null;
namePrefix?: string | null;
firstName: string;
firstNameEN: string;
middleName?: string | null;
middleNameEN?: string | null;
lastName: string;
lastNameEN: string;
2024-04-05 16:43:59 +07:00
gender: string;
2024-04-17 16:22:07 +07:00
checkpoint?: string | null;
checkpointEN?: string | null;
2024-04-09 17:34:53 +07:00
registrationNo?: string | null;
startDate?: Date | null;
retireDate?: Date | null;
discountCondition?: string | null;
licenseNo?: string | null;
licenseIssueDate?: Date | null;
licenseExpireDate?: Date | null;
sourceNationality?: string | null;
importNationality?: string | null;
trainingPlace?: string | null;
responsibleArea?: string[] | null;
2024-04-10 11:37:12 +07:00
birthDate?: Date | null;
address: string;
addressEN: string;
2024-09-11 15:06:27 +07:00
soi?: string | null;
soiEN?: string | null;
moo?: string | null;
mooEN?: string | null;
street?: string | null;
streetEN?: string | null;
email: string;
telephoneNo: string;
subDistrictId?: string | null;
districtId?: string | null;
provinceId?: string | null;
2024-09-06 13:38:18 +07:00
selectedImage?: string;
branchId: string | string[];
};
type UserUpdate = {
status?: "ACTIVE" | "INACTIVE";
username?: string;
2024-04-09 13:05:49 +07:00
userType?: UserType;
userRole?: string;
2024-09-12 09:48:56 +07:00
citizenId?: string;
citizenIssue?: Date;
citizenExpire?: Date | null;
namePrefix?: string | null;
firstName?: string;
firstNameEN?: string;
middleName?: string | null;
middleNameEN?: string | null;
lastName?: string;
lastNameEN?: string;
2024-04-05 16:43:59 +07:00
gender?: string;
2024-04-17 16:22:07 +07:00
checkpoint?: string | null;
checkpointEN?: string | null;
2024-04-09 17:34:53 +07:00
registrationNo?: string | null;
startDate?: Date | null;
retireDate?: Date | null;
discountCondition?: string | null;
licenseNo?: string | null;
licenseIssueDate?: Date | null;
licenseExpireDate?: Date | null;
sourceNationality?: string | null;
importNationality?: string | null;
trainingPlace?: string | null;
responsibleArea?: string[];
2024-04-10 11:37:12 +07:00
birthDate?: Date | null;
address?: string;
addressEN?: string;
2024-09-11 15:06:27 +07:00
soi?: string | null;
soiEN?: string | null;
moo?: string | null;
mooEN?: string | null;
street?: string | null;
streetEN?: string | null;
email?: string;
telephoneNo?: string;
2024-09-06 13:38:18 +07:00
selectedImage?: string;
subDistrictId?: string | null;
districtId?: string | null;
provinceId?: string | null;
branchId?: string | string[];
};
const permissionCond = createPermCondition(globalAllow);
const permissionCheck = createPermCheck(globalAllow);
async function userBranchCodeGen(user: User, branch: Branch) {
2024-10-22 17:59:31 +07:00
return await retry(() =>
prisma.$transaction(
async (tx) => {
const typ = user.userType;
const mapTypeNo = {
USER: 1,
MESSENGER: 2,
DELEGATE: 3,
AGENCY: 4,
}[typ];
const last = await tx.runningNo.upsert({
where: {
key: `BR_USR_${branch.code}_${mapTypeNo}`,
},
create: {
key: `BR_USR_${branch.code}_${mapTypeNo}`,
value: 1,
},
update: { value: { increment: 1 } },
});
return await tx.user.update({
where: { id: user.id },
data: {
code: mapTypeNo + `${last.value}`.padStart(6, "0"),
},
});
},
{ isolationLevel: Prisma.TransactionIsolationLevel.Serializable },
),
);
}
2024-06-06 09:42:02 +07:00
@Route("api/v1/user")
@Tags("User")
export class UserController extends Controller {
2024-04-09 17:51:46 +07:00
@Get("type-stats")
@Security("keycloak")
2024-09-04 17:01:18 +07:00
async getUserTypeStats(@Request() req: RequestWithUser) {
2024-04-09 17:51:46 +07:00
const list = await prisma.user.groupBy({
by: "userType",
_count: true,
where: {
2024-09-04 17:01:18 +07:00
userRole: { not: "system" },
branch: isSystem(req.user)
? undefined
: {
some: {
branch: {
OR: permissionCond(req.user),
2024-09-04 17:01:18 +07:00
},
},
},
},
2024-04-09 17:51:46 +07:00
});
return list.reduce<Record<UserType, number>>(
(a, c) => {
a[c.userType] = c._count;
return a;
},
{
USER: 0,
MESSENGER: 0,
DELEGATE: 0,
AGENCY: 0,
},
);
}
@Get()
@Security("keycloak")
async getUser(
@Request() req: RequestWithUser,
2024-04-09 13:05:49 +07:00
@Query() userType?: UserType,
@Query() includeBranch: boolean = false,
@Query() query: string = "",
@Query() page: number = 1,
@Query() pageSize: number = 30,
2024-08-16 10:48:56 +07:00
@Query() status?: Status,
) {
const where = {
OR: queryOrNot<Prisma.UserWhereInput[]>(query, [
2024-10-24 10:03:20 +07:00
{ code: { contains: query, mode: "insensitive" } },
2024-09-10 16:26:23 +07:00
{ firstName: { contains: query } },
{ firstNameEN: { contains: query } },
{ lastName: { contains: query } },
{ lastNameEN: { contains: query } },
{ email: { contains: query } },
{ telephoneNo: { contains: query } },
2024-09-11 15:06:27 +07:00
...whereAddressQuery(query),
]),
AND: {
userRole: { not: "system" },
2024-09-10 16:26:23 +07:00
userType,
...filterStatus(status),
2024-09-04 16:47:31 +07:00
branch: isSystem(req.user)
? undefined
: {
some: {
branch: {
OR: permissionCond(req.user),
2024-09-04 16:47:31 +07:00
},
},
},
},
} satisfies Prisma.UserWhereInput;
const [result, total] = await prisma.$transaction([
prisma.user.findMany({
2024-06-24 13:20:59 +07:00
orderBy: [{ statusOrder: "asc" }, { createdAt: "asc" }],
include: {
responsibleArea: true,
province: true,
district: true,
subDistrict: true,
branch: { include: { branch: includeBranch } },
2024-07-01 14:38:07 +07:00
createdBy: true,
updatedBy: true,
},
where,
take: pageSize,
skip: (page - 1) * pageSize,
}),
prisma.user.count({ where }),
]);
return {
2024-09-06 14:25:19 +07:00
result: result.map((v) => ({
...v,
responsibleArea: v.responsibleArea.map((v) => v.area),
2024-09-06 14:25:19 +07:00
branch: includeBranch ? v.branch.map((a) => a.branch) : undefined,
})),
page,
pageSize,
total,
};
}
@Get("{userId}")
@Security("keycloak")
async getUserById(@Path() userId: string) {
const record = await prisma.user.findFirst({
include: {
province: true,
district: true,
subDistrict: true,
2024-07-01 14:38:07 +07:00
createdBy: true,
updatedBy: true,
},
where: { id: userId },
});
2024-09-11 18:04:53 +07:00
if (!record) throw notFoundError("User");
2024-09-05 14:43:33 +07:00
return record;
}
@Post()
2024-09-04 11:40:55 +07:00
@Security("keycloak", MANAGE_ROLES)
async createUser(@Request() req: RequestWithUser, @Body() body: UserCreate) {
2024-08-29 13:18:25 +07:00
const [province, district, subDistrict, branch, user] = await prisma.$transaction([
prisma.province.findFirst({ where: { id: body.provinceId ?? undefined } }),
prisma.district.findFirst({ where: { id: body.districtId ?? undefined } }),
prisma.subDistrict.findFirst({ where: { id: body.subDistrictId ?? undefined } }),
prisma.branch.findMany({
include: branchRelationPermInclude(req.user),
where: { id: { in: Array.isArray(body.branchId) ? body.branchId : [body.branchId] } },
}),
2024-08-29 13:18:25 +07:00
prisma.user.findFirst({
where: { username: body.username },
2024-08-29 13:18:25 +07:00
}),
]);
2024-09-11 18:04:53 +07:00
if (body.provinceId && !province) throw relationError("Province");
if (body.districtId && !district) throw relationError("District");
if (body.subDistrictId && !subDistrict) throw relationError("SubDistrict");
if (branch.length === 0) {
throw new HttpError(
HttpStatus.BAD_REQUEST,
"Require at least one branch for a user.",
"minimumBranchNotMet",
);
}
2024-09-07 20:19:34 +07:00
2024-09-11 18:04:53 +07:00
await Promise.all(branch.map((branch) => permissionCheck(req.user, branch)));
2024-09-07 20:19:34 +07:00
if (user) {
throw new HttpError(HttpStatus.BAD_REQUEST, "User exists.", "userExists");
2024-08-29 13:18:25 +07:00
}
2024-08-30 09:57:22 +07:00
2024-09-04 16:19:07 +07:00
const setRoleIndex = MANAGE_ROLES.findIndex((v) => v === body.userRole);
const userRoleIndex = MANAGE_ROLES.reduce(
(a, c, i) => (req.user.roles?.includes(c) ? i : a),
-1,
);
2024-09-04 11:40:55 +07:00
const THROW_PERM_MSG = "You do not have permission to perform this action.";
const THROW_PERM_CODE = "noPermission";
2024-09-05 11:03:45 +07:00
if (setRoleIndex !== -1 && setRoleIndex < userRoleIndex) {
2024-09-04 11:40:55 +07:00
throw new HttpError(HttpStatus.FORBIDDEN, THROW_PERM_MSG, THROW_PERM_CODE);
}
if (!globalAllow(req.user)) {
if (branch.some((v) => !v.user.find((v) => v.userId === req.user.sub))) {
throw new HttpError(HttpStatus.FORBIDDEN, THROW_PERM_MSG, THROW_PERM_CODE);
}
}
const { branchId, provinceId, districtId, subDistrictId, username, ...rest } = body;
2024-07-01 13:24:02 +07:00
let list = await listRole();
2024-04-17 16:22:07 +07:00
if (!Array.isArray(list)) throw new Error("Failed. Cannot get role(s) data from the server.");
if (Array.isArray(list)) {
list = list.filter(
(a) =>
!["uma_authorization", "offline_access", "default-roles"].some((b) => a.name.includes(b)),
);
}
const userId = await createUser(username, username, {
firstName: body.firstName,
lastName: body.lastName,
2024-09-25 13:20:27 +07:00
email: body.email,
requiredActions: ["UPDATE_PASSWORD"],
2024-06-24 13:14:44 +07:00
enabled: rest.status !== "INACTIVE",
});
2024-04-17 16:22:07 +07:00
if (!userId || typeof userId !== "string") {
throw new Error("Cannot create user with keycloak service.");
}
2024-04-18 16:47:50 +07:00
const role = list.find((v) => v.name === body.userRole);
2024-04-17 16:22:07 +07:00
const resultAddRole = role && (await addUserRoles(userId, [role]));
if (!resultAddRole) {
await deleteUser(userId);
throw new Error("Failed. Cannot set user's role.");
}
const record = await prisma.user.create({
2024-07-01 14:38:07 +07:00
include: {
province: true,
district: true,
subDistrict: true,
createdBy: true,
updatedBy: true,
},
data: {
2024-04-17 16:22:07 +07:00
id: userId,
...rest,
responsibleArea: rest.responsibleArea
? {
create: rest.responsibleArea.map((v) => ({ area: v })),
}
: undefined,
2024-06-24 13:14:44 +07:00
statusOrder: +(rest.status === "INACTIVE"),
2024-04-17 16:48:49 +07:00
username,
2024-04-17 16:22:07 +07:00
userRole: role.name,
2024-09-10 16:26:23 +07:00
province: connectOrNot(provinceId),
district: connectOrNot(districtId),
subDistrict: connectOrNot(subDistrictId),
2024-09-04 11:40:55 +07:00
branch: {
create: Array.isArray(branchId)
? branchId.map((v) => ({
branchId: v,
createdByUserId: req.user.sub,
2024-10-29 14:21:31 +07:00
updatedByUserId: req.user.sub,
2024-09-04 11:40:55 +07:00
}))
: {
branchId,
createdByUserId: req.user.sub,
updatedByUserId: req.user.sub,
},
},
2024-07-01 13:24:02 +07:00
createdBy: { connect: { id: req.user.sub } },
updatedBy: { connect: { id: req.user.sub } },
},
});
const updated = await userBranchCodeGen(record, branch[0]); // only generate code by using first branch only
record.code = updated.code;
this.setStatus(HttpStatus.CREATED);
2024-09-05 14:43:33 +07:00
return record;
}
@Put("{userId}")
2024-09-04 11:40:55 +07:00
@Security("keycloak", MANAGE_ROLES)
async editUser(
@Request() req: RequestWithUser,
@Body() body: UserUpdate,
@Path() userId: string,
) {
const [province, district, subDistrict, user, branch] = await prisma.$transaction([
prisma.province.findFirst({ where: { id: body.provinceId || undefined } }),
prisma.district.findFirst({ where: { id: body.districtId || undefined } }),
prisma.subDistrict.findFirst({ where: { id: body.subDistrictId || undefined } }),
prisma.user.findFirst({
include: {
branch: {
include: {
branch: {
include: branchRelationPermInclude(req.user),
2024-09-07 20:19:34 +07:00
},
},
},
},
where: { id: userId },
}),
prisma.branch.findMany({
include: branchRelationPermInclude(req.user),
where: {
id: {
in: Array.isArray(body.branchId) ? body.branchId : body.branchId ? [body.branchId] : [],
},
},
}),
]);
2024-09-11 18:04:53 +07:00
if (!user) throw notFoundError("User");
if (body.provinceId && !province) throw relationError("Province");
if (body.districtId && !district) throw relationError("District");
if (body.subDistrictId && !subDistrict) throw relationError("SubDistrict");
if (body.branchId && branch.length === 0) {
throw new HttpError(
HttpStatus.BAD_REQUEST,
"Require at least one branch for a user.",
"minimumBranchNotMet",
);
}
await Promise.all([
...user.branch.map(async ({ branch }) => await permissionCheck(req.user, branch)),
...branch.map(async (branch) => await permissionCheck(req.user, branch)),
]);
2024-09-04 16:19:07 +07:00
const setRoleIndex = MANAGE_ROLES.findIndex((v) => v === body.userRole);
const userRoleIndex = MANAGE_ROLES.reduce(
(a, c, i) => (req.user.roles?.includes(c) ? i : a),
-1,
);
2024-09-04 11:40:55 +07:00
const THROW_PERM_MSG = "You do not have permission to perform this action.";
const THROW_PERM_CODE = "noPermission";
2024-09-04 16:47:14 +07:00
if (setRoleIndex !== -1 && setRoleIndex < userRoleIndex) {
2024-09-04 11:40:55 +07:00
throw new HttpError(HttpStatus.FORBIDDEN, THROW_PERM_MSG, THROW_PERM_CODE);
}
2024-09-04 16:47:14 +07:00
if (!globalAllow(req.user) && body.branchId) {
2024-09-04 11:40:55 +07:00
if (branch.some((v) => !v.user.find((v) => v.userId === req.user.sub))) {
throw new HttpError(HttpStatus.FORBIDDEN, THROW_PERM_MSG, THROW_PERM_CODE);
}
}
2024-04-18 16:32:38 +07:00
let userRole: string | undefined;
2024-09-06 17:41:04 +07:00
if (body.userRole && user.userRole !== body.userRole) {
2024-07-01 13:24:02 +07:00
let list = await listRole();
2024-04-18 16:32:38 +07:00
if (!Array.isArray(list)) throw new Error("Failed. Cannot get role(s) data from the server.");
if (Array.isArray(list)) {
list = list.filter(
(a) =>
!["uma_authorization", "offline_access", "default-roles"].some((b) =>
a.name.includes(b),
),
);
}
const currentRole = await getUserRoles(userId);
2024-04-17 16:35:35 +07:00
const role = list.find((v) => v.name === body.userRole);
2024-04-17 16:35:35 +07:00
2024-09-04 16:47:14 +07:00
if (role) {
const resultAddRole = await addUserRoles(userId, [role]);
if (!resultAddRole) {
throw new Error("Failed. Cannot set user's role.");
} else {
if (Array.isArray(currentRole))
await removeUserRoles(
userId,
currentRole.filter(
(a) =>
!["uma_authorization", "offline_access", "default-roles"].some((b) =>
a.name.includes(b),
),
),
);
}
userRole = role.name;
2024-04-18 16:32:38 +07:00
}
2024-04-17 16:35:35 +07:00
}
if (body.username) {
2024-09-25 13:20:27 +07:00
await editUser(userId, {
username: body.username,
email: body.email,
enabled: body.status !== "INACTIVE",
});
}
const { provinceId, districtId, subDistrictId, branchId, ...rest } = body;
2024-04-09 13:05:49 +07:00
const record = await prisma.user.update({
2024-07-01 14:38:07 +07:00
include: {
province: true,
district: true,
subDistrict: true,
createdBy: true,
updatedBy: true,
},
data: {
...rest,
responsibleArea: rest.responsibleArea
? {
deleteMany: {},
create: rest.responsibleArea.map((v) => ({ area: v })),
}
: undefined,
2024-06-24 13:14:44 +07:00
statusOrder: +(rest.status === "INACTIVE"),
2024-04-18 16:32:38 +07:00
userRole,
2024-09-10 16:26:23 +07:00
province: connectOrDisconnect(provinceId),
district: connectOrDisconnect(districtId),
subDistrict: connectOrDisconnect(subDistrictId),
2024-07-01 13:24:02 +07:00
updatedBy: { connect: { id: req.user.sub } },
},
where: { id: userId },
});
2024-04-09 13:05:49 +07:00
if (branchId) {
await prisma.$transaction([
prisma.branchUser.deleteMany({
where: {
userId,
branchId: { not: { in: Array.isArray(branchId) ? branchId : [branchId] } },
},
}),
prisma.branchUser.createMany({
data: (Array.isArray(branchId) ? branchId : [branchId])
.filter((a) => !user.branch.some((b) => a === b.branchId))
.map((v) => ({
userId,
branchId: v,
})),
}),
prisma.branch.updateMany({
where: {
id: { in: Array.isArray(branchId) ? branchId : [branchId] },
status: "CREATED",
},
data: { status: "ACTIVE" },
}),
]);
2024-08-14 20:32:24 +07:00
if (branch[0]?.id !== user.branch[0]?.branchId) {
const updated = await userBranchCodeGen(user, branch[0]);
record.code = updated.code;
}
}
2024-09-05 14:43:33 +07:00
return record;
}
@Delete("{userId}")
2024-09-04 11:40:55 +07:00
@Security("keycloak", MANAGE_ROLES)
async deleteUser(@Request() req: RequestWithUser, @Path() userId: string) {
2024-04-03 16:26:52 +07:00
const record = await prisma.user.findFirst({
include: {
province: true,
district: true,
subDistrict: true,
2024-07-01 14:38:07 +07:00
createdBy: true,
updatedBy: true,
branch: {
2024-09-04 17:41:54 +07:00
include: {
branch: {
2024-09-10 14:51:05 +07:00
include: branchRelationPermInclude(req.user),
2024-09-04 17:41:54 +07:00
},
},
},
2024-04-03 16:26:52 +07:00
},
where: { id: userId },
});
if (!record) throw notFoundError("User");
2024-04-03 16:26:52 +07:00
await Promise.all([
...record.branch.map(async ({ branch }) => await permissionCheck(req.user, branch)),
]);
2024-09-07 20:19:34 +07:00
if (record.status !== Status.CREATED) throw isUsedError("User");
2024-04-03 16:26:52 +07:00
2024-09-13 16:16:14 +07:00
await deleteFolder(fileLocation.user.profile(userId));
await deleteFolder(fileLocation.user.attachment(userId));
await deleteUser(userId);
2024-04-03 16:26:52 +07:00
return await prisma.user.delete({
include: {
province: true,
district: true,
subDistrict: true,
2024-07-01 14:38:07 +07:00
createdBy: true,
updatedBy: true,
2024-04-03 16:26:52 +07:00
},
where: { id: userId },
});
2024-07-31 11:43:07 +07:00
}
}
2024-09-10 15:17:48 +07:00
async function getUserCheckPerm(user: RequestWithUser["user"], userId: string) {
const record = await prisma.user.findFirst({
include: {
province: true,
district: true,
subDistrict: true,
createdBy: true,
updatedBy: true,
branch: {
include: {
branch: {
2024-09-10 16:26:23 +07:00
include: branchRelationPermInclude(user),
2024-09-10 15:17:48 +07:00
},
},
},
},
where: { id: userId },
});
if (!record) throw notFoundError("User");
2024-09-10 15:17:48 +07:00
await Promise.all(record.branch.map(async ({ branch }) => await permissionCheck(user, branch)));
}
2024-09-05 14:43:33 +07:00
@Route("api/v1/user/{userId}/profile-image")
@Tags("User")
export class UserProfileController extends Controller {
@Get()
@Security("keycloak")
async listImage(@Path() userId: string) {
const record = await prisma.user.findFirst({
where: { id: userId },
});
if (!record) throw notFoundError("User");
2024-09-05 14:43:33 +07:00
return await listFile(fileLocation.user.profile(userId));
}
@Get("{name}")
async getImage(@Request() req: RequestWithUser, @Path() userId: string, @Path() name: string) {
2024-09-13 16:16:14 +07:00
return req.res?.redirect(await getFile(fileLocation.user.profile(userId, name)));
2024-09-05 14:43:33 +07:00
}
2024-10-22 17:54:46 +07:00
@Head("{name}")
async headImage(@Request() req: RequestWithUser, @Path() userId: string, @Path() name: string) {
return req.res?.redirect(await getPresigned("head", fileLocation.user.profile(userId, name)));
}
2024-09-05 14:43:33 +07:00
@Put("{name}")
@Security("keycloak")
async putImage(@Request() req: RequestWithUser, @Path() userId: string, @Path() name: string) {
2024-09-10 15:17:48 +07:00
await getUserCheckPerm(req.user, userId);
2024-09-13 16:16:14 +07:00
return req.res?.redirect(await setFile(fileLocation.user.profile(userId, name)));
2024-09-05 14:43:33 +07:00
}
@Delete("{name}")
2024-09-09 16:13:21 +07:00
@Security("keycloak")
2024-09-07 20:19:34 +07:00
async deleteImage(@Request() req: RequestWithUser, @Path() userId: string, @Path() name: string) {
2024-09-10 15:17:48 +07:00
await getUserCheckPerm(req.user, userId);
2024-09-13 16:16:14 +07:00
await deleteFile(fileLocation.user.profile(userId, name));
2024-09-05 14:43:33 +07:00
}
}
2024-06-06 09:42:02 +07:00
@Route("api/v1/user/{userId}/attachment")
@Tags("User")
@Security("keycloak")
export class UserAttachmentController extends Controller {
@Get()
async listAttachment(@Path() userId: string) {
const record = await prisma.user.findFirst({
where: { id: userId },
});
if (!record) throw notFoundError("User");
2024-09-06 14:13:00 +07:00
const list = await listFile(fileLocation.user.attachment(userId));
2024-09-07 20:19:34 +07:00
2024-09-06 14:13:00 +07:00
return await Promise.all(
list.map(async (v) => ({
name: v,
2024-09-13 16:16:14 +07:00
url: await getFile(fileLocation.user.attachment(userId, v)),
2024-09-06 14:13:00 +07:00
})),
);
}
@Post()
2024-09-07 20:19:34 +07:00
async addAttachment(
@Request() req: RequestWithUser,
@Path() userId: string,
@Body() payload: { file: string[] },
) {
2024-09-10 15:17:48 +07:00
await getUserCheckPerm(req.user, userId);
return await Promise.all(
payload.file.map(async (v) => ({
name: v,
2024-09-13 16:16:14 +07:00
url: await getFile(fileLocation.user.attachment(userId, v)),
uploadUrl: await setFile(fileLocation.user.attachment(userId, v), 12 * 60 * 60),
})),
);
}
@Delete()
2024-09-07 20:19:34 +07:00
async deleteAttachment(
@Request() req: RequestWithUser,
@Path() userId: string,
@Body() payload: { file: string[] },
) {
2024-09-10 15:17:48 +07:00
await getUserCheckPerm(req.user, userId);
await Promise.all(
payload.file.map(async (v) => {
2024-09-13 16:16:14 +07:00
await deleteFile(fileLocation.user.attachment(userId, v));
}),
);
}
}