prod
This commit is contained in:
+40
-19
@@ -11,7 +11,7 @@ import { createApplication, getActiveCitizenship, getApplicationEligibility } fr
|
||||
import { prisma } from "../prisma";
|
||||
import { formatAddress } from "@/lib/address";
|
||||
import { Prisma } from "@/lib/generated/prisma/client";
|
||||
import { uploadImage } from "../image";
|
||||
import { removeImage, uploadImage } from "../image";
|
||||
|
||||
function generateDocumentNumber(): string {
|
||||
const letter = () => String.fromCharCode(65 + Math.floor(Math.random() * 26));
|
||||
@@ -70,23 +70,37 @@ export const submitCitizenshipApplication = formAction(citizenshipApplicationSch
|
||||
customAddress: data.customAddress,
|
||||
});
|
||||
|
||||
const profileKey = await uploadImage(profile, "citizenship/profiles");
|
||||
const signatureKey = await uploadImage(signature, "citizenship/signatures");
|
||||
let profileKey: string | undefined;
|
||||
let signatureKey: string | undefined;
|
||||
|
||||
await createApplication(user.id, {
|
||||
surname: user.secondName,
|
||||
givenNames: user.firstName,
|
||||
sex: user.sex,
|
||||
birthDate: user.birthDate!,
|
||||
...applicationData,
|
||||
address,
|
||||
regionId: isEuResidentYes ? data.regionId! : null,
|
||||
city: isEuResidentYes ? data.city! : null,
|
||||
street: isEuResidentYes ? data.street! : null,
|
||||
customAddress: isEuResidentYes ? null : data.customAddress!,
|
||||
profileKey,
|
||||
signatureKey
|
||||
});
|
||||
try {
|
||||
const profileKey = await uploadImage(profile, "citizenship/profiles", {
|
||||
maxWidth: 800, maxHeight: 1000, fit: "cover",
|
||||
});
|
||||
|
||||
const signatureKey = await uploadImage(signature, "citizenship/signatures", {
|
||||
maxWidth: 1000, maxHeight: 400, fit: "inside",
|
||||
});
|
||||
|
||||
await createApplication(user.id, {
|
||||
surname: user.secondName,
|
||||
givenNames: user.firstName,
|
||||
sex: user.sex,
|
||||
birthDate: user.birthDate!,
|
||||
...applicationData,
|
||||
address,
|
||||
regionId: isEuResidentYes ? data.regionId! : null,
|
||||
city: isEuResidentYes ? data.city! : null,
|
||||
street: isEuResidentYes ? data.street! : null,
|
||||
customAddress: isEuResidentYes ? null : data.customAddress!,
|
||||
profileKey,
|
||||
signatureKey
|
||||
});
|
||||
} catch (e) {
|
||||
if (profileKey) await removeImage(profileKey);
|
||||
if (signatureKey) await removeImage(signatureKey);
|
||||
throw e;
|
||||
}
|
||||
|
||||
revalidatePath("/account/citizenship");
|
||||
redirect("/account/citizenship");
|
||||
@@ -102,8 +116,10 @@ export async function approveApplication(id: string): Promise<ActionResult> {
|
||||
if (application.status !== "PENDING") throw new AppError("This application is no longer pending review.");
|
||||
if (application.userId === user.id) throw new AppError("You cannot approve your own application.");
|
||||
|
||||
const existingCitizenship = await prisma.citizenship.findUnique({ where: { userId: application.userId } });
|
||||
if (existingCitizenship && !existingCitizenship.revokedAt) {
|
||||
const existingCitizenship = await prisma.citizenship.findFirst({
|
||||
where: { userId: application.userId, revokedAt: null },
|
||||
});
|
||||
if (existingCitizenship) {
|
||||
throw new AppError("This applicant is already a citizen.");
|
||||
}
|
||||
|
||||
@@ -154,6 +170,11 @@ export async function rejectApplication(id: string, reason: string): Promise<Act
|
||||
data: { status: "REJECTED", rejectionReason: trimmedReason, reviewedAt: new Date(), reviewedBy: user.id },
|
||||
});
|
||||
|
||||
await Promise.allSettled([
|
||||
removeImage(application.profileKey),
|
||||
removeImage(application.signatureKey),
|
||||
]);
|
||||
|
||||
revalidatePath("/account/citizenship/review");
|
||||
});
|
||||
}
|
||||
|
||||
@@ -38,7 +38,7 @@ export async function getApplicationEligibility(
|
||||
};
|
||||
}
|
||||
|
||||
const citizenship = await prisma.citizenship.findUnique({ where: { userId } });
|
||||
const citizenship = await prisma.citizenship.findFirst({ where: { userId, revokedAt: null } });
|
||||
if (citizenship && !citizenship.revokedAt) {
|
||||
return {
|
||||
eligible: false,
|
||||
@@ -100,7 +100,7 @@ export async function getPendingApplicationsCount(): Promise<number> {
|
||||
}
|
||||
|
||||
export async function getActiveCitizenship(userId: string) {
|
||||
const citizenship = await prisma.citizenship.findUnique({ where: { userId } });
|
||||
if (!citizenship || citizenship.revokedAt) return null;
|
||||
return citizenship;
|
||||
}
|
||||
return prisma.citizenship.findFirst({
|
||||
where: { userId, revokedAt: null },
|
||||
});
|
||||
}
|
||||
@@ -36,8 +36,6 @@ export type CitizenshipApplication = {
|
||||
updatedAt: Date;
|
||||
profileKey: string;
|
||||
signatureKey: string;
|
||||
profile: File;
|
||||
signature: File;
|
||||
};
|
||||
|
||||
export type CitizenshipApplicationWithWarning = CitizenshipApplication & {
|
||||
|
||||
+21
-25
@@ -5,53 +5,49 @@ import { AppError } from "@/lib/action-result";
|
||||
import { minioClient } from "@/lib/minio";
|
||||
|
||||
const BUCKET = "uploads";
|
||||
|
||||
const MAX_FILE_SIZE = 5 * 1024 * 1024;
|
||||
const ALLOWED_INPUT_FORMATS = new Set(["jpeg", "png", "webp"]);
|
||||
|
||||
export async function uploadImage(file: File, directory: string): Promise<string> {
|
||||
if (file.size === 0) {
|
||||
throw new AppError("A file is required");
|
||||
}
|
||||
|
||||
if (file.size > MAX_FILE_SIZE) {
|
||||
throw new AppError("Image must be smaller than 5MB");
|
||||
}
|
||||
export async function uploadImage(file: File, directory: string, options: { maxWidth: number; maxHeight: number; fit?: "inside" | "cover"; removeBg?: boolean }): Promise<string> {
|
||||
if (file.size === 0) throw new AppError("A file is required");
|
||||
if (file.size > MAX_FILE_SIZE) throw new AppError("Image must be smaller than 5MB");
|
||||
|
||||
const input = Buffer.from(await file.arrayBuffer());
|
||||
|
||||
let image = sharp(input, {
|
||||
failOn: "error",
|
||||
limitInputPixels: 30_000_000,
|
||||
});
|
||||
|
||||
const metadata = await image.metadata();
|
||||
|
||||
if (!metadata.format) {
|
||||
if (!metadata.format || !ALLOWED_INPUT_FORMATS.has(metadata.format)) {
|
||||
throw new AppError("Only JPEG, PNG, or WEBP images are allowed");
|
||||
}
|
||||
|
||||
if (!metadata.width || !metadata.height || metadata.width < 100 || metadata.height < 100) {
|
||||
throw new AppError("Image is too small");
|
||||
}
|
||||
|
||||
const output = await image
|
||||
.rotate()
|
||||
.webp({
|
||||
quality: 80,
|
||||
effort: 4,
|
||||
.resize({
|
||||
width: options.maxWidth,
|
||||
height: options.maxHeight,
|
||||
fit: options.fit ?? "inside",
|
||||
withoutEnlargement: true,
|
||||
})
|
||||
.webp({ quality: 80, effort: 4 })
|
||||
.toBuffer();
|
||||
|
||||
const key = `${directory}/${crypto.randomUUID()}.webp`;
|
||||
|
||||
await minioClient.putObject(
|
||||
BUCKET,
|
||||
key,
|
||||
output,
|
||||
output.length,
|
||||
{
|
||||
"Content-Type": "image/webp",
|
||||
},
|
||||
);
|
||||
|
||||
await minioClient.putObject(BUCKET, key, output, output.length, { "Content-Type": "image/webp" });
|
||||
return key;
|
||||
}
|
||||
|
||||
export async function removeImage(key: string) {
|
||||
await minioClient.removeObject(BUCKET, key)
|
||||
}
|
||||
|
||||
export async function getImageUrl(key: string): Promise<string> {
|
||||
return minioClient.presignedGetObject(
|
||||
BUCKET,
|
||||
|
||||
+16
-10
@@ -3,16 +3,22 @@
|
||||
import { revalidatePath } from "next/cache";
|
||||
import { addNavLink, deleteNavLinkByPageId } from "./repository";
|
||||
import { prisma } from "../prisma";
|
||||
import { requireAdmin } from "../user/require";
|
||||
import { runAction } from "../run-action";
|
||||
import type { ActionResult } from "../action-result";
|
||||
|
||||
export async function pinPageAction(pageId: string) {
|
||||
const page = await prisma.page.findUnique({ where: { id: pageId } });
|
||||
if (!page) throw new Error(`Page not found: ${pageId}`);
|
||||
export async function togglePinAction(pageId: string, isPinned: boolean): Promise<ActionResult> {
|
||||
return runAction(async () => {
|
||||
await requireAdmin();
|
||||
|
||||
await addNavLink({ pageId });
|
||||
revalidatePath("/", "layout");
|
||||
if (isPinned) {
|
||||
await deleteNavLinkByPageId(pageId);
|
||||
} else {
|
||||
const page = await prisma.page.findUnique({ where: { id: pageId } });
|
||||
if (!page) throw new Error(`Page not found: ${pageId}`);
|
||||
await addNavLink({ pageId });
|
||||
}
|
||||
|
||||
revalidatePath("/", "layout");
|
||||
});
|
||||
}
|
||||
|
||||
export async function unpinPageAction(pageId: string) {
|
||||
await deleteNavLinkByPageId(pageId);
|
||||
revalidatePath("/", "layout");
|
||||
}
|
||||
+36
-23
@@ -6,6 +6,9 @@ import { archivePage, createPage, deletePage, updatePage } from "./repository";
|
||||
import { revalidatePath } from "next/cache";
|
||||
import { deleteNavLinkByPageId } from "../navlinks/repository";
|
||||
import { validatePage } from "./validation";
|
||||
import { requireAdmin } from "../user/require";
|
||||
import { runAction } from "../run-action";
|
||||
import type { ActionResult } from "../action-result";
|
||||
|
||||
export async function savePageAction(params: {
|
||||
id: string | null,
|
||||
@@ -15,31 +18,41 @@ export async function savePageAction(params: {
|
||||
status: PageStatus,
|
||||
blocks: Block[],
|
||||
meta?: PageMeta
|
||||
}) {
|
||||
const parsed = validatePage(params);
|
||||
if (!parsed.success) {
|
||||
throw new Error(parsed.errors.join("; "));
|
||||
}
|
||||
}): Promise<ActionResult> {
|
||||
return runAction(async () => {
|
||||
await requireAdmin();
|
||||
|
||||
if (params.id) {
|
||||
await updatePage(params.id, params.title, params.type, params.status, params.blocks, params.meta);
|
||||
revalidatePath(`/${params.type.toLowerCase()}/${params.slug}`);
|
||||
revalidatePath(`/${params.type.toLowerCase()}`);
|
||||
} else {
|
||||
const page = await createPage(params.slug, params.title, params.type, params.status, params.blocks, params.meta);
|
||||
revalidatePath(`/${params.type.toLowerCase()}`);
|
||||
redirect(`/${params.type.toLowerCase()}/${page.slug}`);
|
||||
}
|
||||
const parsed = validatePage(params);
|
||||
if (!parsed.success) {
|
||||
throw new Error(parsed.errors.join("; "));
|
||||
}
|
||||
|
||||
if (params.id) {
|
||||
await updatePage(params.id, params.title, params.type, params.status, params.blocks, params.meta);
|
||||
revalidatePath(`/${params.type.toLowerCase()}/${params.slug}`);
|
||||
revalidatePath(`/${params.type.toLowerCase()}`);
|
||||
} else {
|
||||
const page = await createPage(params.slug, params.title, params.type, params.status, params.blocks, params.meta);
|
||||
revalidatePath(`/${params.type.toLowerCase()}`);
|
||||
redirect(`/${params.type.toLowerCase()}/${page.slug}`);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
export async function archivePageAction(id: string, slug: string, type: PageType) {
|
||||
await archivePage(id);
|
||||
await deleteNavLinkByPageId(id);
|
||||
revalidatePath(`/${type.toLowerCase()}/${slug}`);
|
||||
revalidatePath(`/${type.toLowerCase()}`);
|
||||
export async function archivePageAction(id: string, slug: string, type: PageType): Promise<ActionResult> {
|
||||
return runAction(async () => {
|
||||
await requireAdmin();
|
||||
await archivePage(id);
|
||||
await deleteNavLinkByPageId(id);
|
||||
revalidatePath(`/${type.toLowerCase()}/${slug}`);
|
||||
revalidatePath(`/${type.toLowerCase()}`);
|
||||
});
|
||||
}
|
||||
|
||||
export async function deletePageAction(id: string, type: PageType) {
|
||||
await deletePage(id);
|
||||
revalidatePath(`/${type.toLowerCase()}`);
|
||||
}
|
||||
export async function deletePageAction(id: string, type: PageType): Promise<ActionResult> {
|
||||
return runAction(async () => {
|
||||
await requireAdmin();
|
||||
await deletePage(id);
|
||||
revalidatePath(`/${type.toLowerCase()}`);
|
||||
});
|
||||
}
|
||||
|
||||
+3
-11
@@ -36,13 +36,7 @@ export async function getPageBySlug(slug: string, type?: PageType) {
|
||||
|
||||
export async function createPage(slug: string, title: string, type: PageType, status: PageStatus, blocks: Block[], meta?: PageMeta) {
|
||||
const user = await getCurrentUser();
|
||||
if (!user) {
|
||||
throw new Error("Failed to fetch user");
|
||||
}
|
||||
|
||||
if (!user.isAdmin) {
|
||||
throw new Error("Access denied");
|
||||
}
|
||||
if (!user) throw new Error("Failed to fetch user");
|
||||
|
||||
try {
|
||||
const page = await prisma.page.create({
|
||||
@@ -87,7 +81,7 @@ export async function updatePage(
|
||||
meta?: PageMeta
|
||||
) {
|
||||
const user = await getCurrentUser();
|
||||
if (!user?.isAdmin) throw new Error("Access denied");
|
||||
if (!user) throw new Error("Failed to fetch user");
|
||||
|
||||
const currentPage = await prisma.page.findUnique({ where: { id }, select: { status: true } });
|
||||
const isNewlyPublished = status === "PUBLISHED" && currentPage?.status !== "PUBLISHED";
|
||||
@@ -125,13 +119,11 @@ export async function updatePage(
|
||||
|
||||
export async function archivePage(id: string) {
|
||||
const user = await getCurrentUser();
|
||||
if (!user?.isAdmin) throw new Error("Access denied");
|
||||
if (!user) throw new Error("Failed to fetch user");
|
||||
await prisma.page.update({ where: { id }, data: { status: "ARCHIVED", updatedBy: user.id } });
|
||||
}
|
||||
|
||||
export async function deletePage(id: string) {
|
||||
const user = await getCurrentUser();
|
||||
if (!user?.isAdmin) throw new Error("Access denied");
|
||||
await prisma.page.delete({ where: { id } });
|
||||
}
|
||||
|
||||
|
||||
+5
-1
@@ -9,7 +9,7 @@ import { deleteUser, updateUser } from "./repository";
|
||||
import { getAccessToken } from "@/lib/auth/tokens";
|
||||
import { fetchKotosoftUser } from "@/lib/kotosoft/client";
|
||||
import { revalidatePath } from "next/cache";
|
||||
import { getCurrentUser } from "../user";
|
||||
import { getCurrentUser, getUser } from "../user";
|
||||
import { runAction } from "@/lib/run-action";
|
||||
import { AppError, type ActionResult } from "@/lib/action-result";
|
||||
|
||||
@@ -61,6 +61,10 @@ export async function updateUserAction(): Promise<ActionResult> {
|
||||
const userId = await getSessionUserId();
|
||||
if (!userId) throw new AppError("Not authenticated");
|
||||
|
||||
const user = await getUser(userId);
|
||||
|
||||
if (user?.kotosoftId !== kotosoftUser.id) throw new AppError("Your session does not match your Kotosoft ID account");
|
||||
|
||||
await updateUser(userId, {
|
||||
email: kotosoftUser.email,
|
||||
firstName: kotosoftUser.first_name,
|
||||
|
||||
Reference in New Issue
Block a user