feat: Add photo management features, duplicate detection, attempt limits, and admin deletion
CI / skip-ci-check (pull_request) Successful in 1m19s
CI / lint-and-type-check (pull_request) Failing after 1m37s
CI / test (pull_request) Successful in 2m16s
CI / build (pull_request) Failing after 1m46s
CI / secret-scanning (pull_request) Successful in 1m20s
CI / dependency-scan (pull_request) Successful in 1m27s
CI / sast-scan (pull_request) Successful in 2m29s
CI / workflow-summary (pull_request) Successful in 1m18s

- Add duplicate photo detection (file hash and URL checking)
- Add max attempts per photo with UI counter
- Simplify penalty system (auto-enable when points > 0)
- Prevent scores from going below 0
- Add admin photo deletion functionality
- Improve navigation with always-visible logout
- Prevent users from guessing their own photos
This commit is contained in:
2026-01-02 14:57:30 -05:00
commit 9640627972
69 changed files with 20858 additions and 0 deletions
+144
View File
@@ -0,0 +1,144 @@
import { NextRequest, NextResponse } from "next/server"
import { auth } from "@/lib/auth"
import { prisma } from "@/lib/prisma"
import { normalizeString } from "@/lib/utils"
export async function POST(
req: NextRequest,
{ params }: { params: Promise<{ photoId: string }> }
) {
try {
const session = await auth()
if (!session) {
return NextResponse.json({ error: "Unauthorized" }, { status: 401 })
}
const { photoId } = await params
const { guessText } = await req.json()
if (!guessText || !guessText.trim()) {
return NextResponse.json(
{ error: "Guess text is required" },
{ status: 400 }
)
}
const photo = await prisma.photo.findUnique({
where: { id: photoId },
})
if (!photo) {
return NextResponse.json({ error: "Photo not found" }, { status: 404 })
}
// Prevent users from guessing their own photos
if (photo.uploaderId === session.user.id) {
return NextResponse.json(
{ error: "You cannot guess on your own photos" },
{ status: 403 }
)
}
// Check if user already has a correct guess
const existingCorrectGuess = await prisma.guess.findFirst({
where: {
userId: session.user.id,
photoId: photoId,
correct: true,
},
})
if (existingCorrectGuess) {
return NextResponse.json(
{ error: "You already guessed this correctly" },
{ status: 400 }
)
}
// Check max attempts limit
const photoWithMaxAttempts = photo as typeof photo & { maxAttempts: number | null }
if (photoWithMaxAttempts.maxAttempts !== null && photoWithMaxAttempts.maxAttempts > 0) {
const userGuessCount = await prisma.guess.count({
where: {
userId: session.user.id,
photoId: photoId,
},
})
if (userGuessCount >= photoWithMaxAttempts.maxAttempts) {
return NextResponse.json(
{ error: `You have reached the maximum number of attempts (${photoWithMaxAttempts.maxAttempts}) for this photo` },
{ status: 400 }
)
}
}
// Check if guess is correct (case-insensitive, trimmed)
const normalizedGuess = normalizeString(guessText)
const normalizedAnswer = normalizeString(photo.answerName)
const isCorrect = normalizedGuess === normalizedAnswer
// Create the guess
const guess = await prisma.guess.create({
data: {
userId: session.user.id,
photoId: photoId,
guessText: guessText.trim(),
correct: isCorrect,
},
})
// Update user points based on guess result
let pointsChange = 0
const photoWithPenalty = photo as typeof photo & { penaltyEnabled: boolean; penaltyPoints: number }
if (isCorrect) {
// Award points for correct answer
pointsChange = photo.points
await prisma.user.update({
where: { id: session.user.id },
data: {
points: {
increment: photo.points, // Award points based on photo difficulty
},
},
})
} else if (photoWithPenalty.penaltyEnabled && photoWithPenalty.penaltyPoints > 0) {
// Deduct points for wrong answer if penalty is enabled
// First, get current user points to prevent going below 0
const currentUser = await prisma.user.findUnique({
where: { id: session.user.id },
select: { points: true },
})
if (currentUser) {
const currentPoints = currentUser.points
const penaltyAmount = photoWithPenalty.penaltyPoints
const newPoints = Math.max(0, currentPoints - penaltyAmount)
const actualDeduction = currentPoints - newPoints
pointsChange = -actualDeduction
await prisma.user.update({
where: { id: session.user.id },
data: {
points: newPoints,
},
})
}
}
return NextResponse.json({
guess,
correct: isCorrect,
pointsChange
})
} catch (error) {
console.error("Error submitting guess:", error)
return NextResponse.json(
{ error: "Internal server error" },
{ status: 500 }
)
}
}
+69
View File
@@ -0,0 +1,69 @@
import { NextRequest, NextResponse } from "next/server"
import { auth } from "@/lib/auth"
import { prisma } from "@/lib/prisma"
import { unlink } from "fs/promises"
import { join } from "path"
import { existsSync } from "fs"
export async function DELETE(
req: NextRequest,
{ params }: { params: Promise<{ photoId: string }> }
) {
try {
const session = await auth()
if (!session) {
return NextResponse.json({ error: "Unauthorized" }, { status: 401 })
}
// Only admins can delete photos
if (session.user.role !== "ADMIN") {
return NextResponse.json(
{ error: "Only admins can delete photos" },
{ status: 403 }
)
}
const { photoId } = await params
// Find the photo
const photo = await prisma.photo.findUnique({
where: { id: photoId },
})
if (!photo) {
return NextResponse.json({ error: "Photo not found" }, { status: 404 })
}
// Delete all guesses associated with this photo first
await prisma.guess.deleteMany({
where: { photoId: photoId },
})
// Delete the photo file if it's a local upload (starts with /uploads/)
if (photo.url.startsWith("/uploads/")) {
const filepath = join(process.cwd(), "public", photo.url)
if (existsSync(filepath)) {
try {
await unlink(filepath)
} catch (error) {
console.error(`Failed to delete file ${filepath}:`, error)
// Continue with database deletion even if file deletion fails
}
}
}
// Delete the photo
await prisma.photo.delete({
where: { id: photoId },
})
return NextResponse.json({ success: true, message: "Photo deleted successfully" })
} catch (error) {
console.error("Error deleting photo:", error)
return NextResponse.json(
{ error: "Internal server error" },
{ status: 500 }
)
}
}
+88
View File
@@ -0,0 +1,88 @@
import { NextRequest, NextResponse } from "next/server"
import { auth } from "@/lib/auth"
import { prisma } from "@/lib/prisma"
import { sendNewPhotoEmail } from "@/lib/email"
// Legacy endpoint for URL-based uploads (kept for backward compatibility)
export async function POST(req: NextRequest) {
try {
const session = await auth()
if (!session) {
return NextResponse.json({ error: "Unauthorized" }, { status: 401 })
}
const { url, answerName, points, maxAttempts } = await req.json()
if (!url || !answerName) {
return NextResponse.json(
{ error: "URL and answer name are required" },
{ status: 400 }
)
}
// Validate points (must be positive integer, default to 1)
const pointsValue = points ? Math.max(1, parseInt(points, 10)) : 1
const maxAttemptsValue = maxAttempts && parseInt(maxAttempts, 10) > 0
? parseInt(maxAttempts, 10)
: null
// Check for duplicate URL
const existingPhoto = await prisma.photo.findFirst({
where: { url },
})
if (existingPhoto) {
return NextResponse.json(
{ error: "This photo URL has already been uploaded (duplicate URL detected)" },
{ status: 409 }
)
}
const photo = await prisma.photo.create({
data: {
uploaderId: session.user.id,
url,
answerName: answerName.trim(),
points: pointsValue,
maxAttempts: maxAttemptsValue,
} as any,
include: {
uploader: {
select: {
name: true,
},
},
},
})
// Send emails to all other users
const allUsers = await prisma.user.findMany({
where: {
id: { not: session.user.id },
},
select: {
id: true,
email: true,
name: true,
},
})
// Send emails asynchronously (don't wait for them)
Promise.all(
allUsers.map((user: { id: string; email: string; name: string }) =>
sendNewPhotoEmail(user.email, user.name, photo.id, photo.uploader.name).catch(
(err) => console.error(`Failed to send email to ${user.email}:`, err)
)
)
)
return NextResponse.json({ photo }, { status: 201 })
} catch (error) {
console.error("Error creating photo:", error)
return NextResponse.json(
{ error: "Internal server error" },
{ status: 500 }
)
}
}
+218
View File
@@ -0,0 +1,218 @@
import { NextRequest, NextResponse } from "next/server"
import { auth } from "@/lib/auth"
import { prisma } from "@/lib/prisma"
import { sendNewPhotoEmail } from "@/lib/email"
import { writeFile } from "fs/promises"
import { join } from "path"
import { existsSync, mkdirSync } from "fs"
import { createHash } from "crypto"
import type { Photo } from "@prisma/client"
export async function POST(req: NextRequest) {
try {
const session = await auth()
if (!session) {
return NextResponse.json({ error: "Unauthorized" }, { status: 401 })
}
// Verify the user exists in the database
const user = await prisma.user.findUnique({
where: { id: session.user.id },
select: { id: true },
})
if (!user) {
return NextResponse.json(
{ error: "User not found. Please log out and log back in." },
{ status: 401 }
)
}
const formData = await req.formData()
const count = parseInt(formData.get("count") as string, 10)
if (!count || count < 1) {
return NextResponse.json(
{ error: "Invalid photo count" },
{ status: 400 }
)
}
const uploadsDir = join(process.cwd(), "public", "uploads")
if (!existsSync(uploadsDir)) {
mkdirSync(uploadsDir, { recursive: true })
}
type PhotoWithUploader = Photo & {
uploader: { name: string }
}
const createdPhotos: PhotoWithUploader[] = []
for (let i = 0; i < count; i++) {
const answerName = (formData.get(`photo_${i}_answerName`) as string)?.trim()
const pointsStr = (formData.get(`photo_${i}_points`) as string) || "1"
const pointsValue = Math.max(1, parseInt(pointsStr, 10))
const penaltyEnabled = formData.get(`photo_${i}_penaltyEnabled`) === "true"
const penaltyPointsStr = (formData.get(`photo_${i}_penaltyPoints`) as string) || "0"
const penaltyPointsValue = Math.max(0, parseInt(penaltyPointsStr, 10))
const maxAttemptsStr = (formData.get(`photo_${i}_maxAttempts`) as string)?.trim() || ""
const maxAttemptsValue = maxAttemptsStr && parseInt(maxAttemptsStr, 10) > 0
? parseInt(maxAttemptsStr, 10)
: null
if (!answerName) {
return NextResponse.json(
{ error: `Photo ${i + 1}: Answer name is required` },
{ status: 400 }
)
}
const file = formData.get(`photo_${i}_file`) as File | null
const url = (formData.get(`photo_${i}_url`) as string)?.trim() || null
if (!file && !url) {
return NextResponse.json(
{ error: `Photo ${i + 1}: File or URL is required` },
{ status: 400 }
)
}
let photoUrl: string
let fileHash: string | null = null
if (file) {
// Handle file upload
if (!file.type.startsWith("image/")) {
return NextResponse.json(
{ error: `Photo ${i + 1}: File must be an image` },
{ status: 400 }
)
}
if (file.size > 10 * 1024 * 1024) {
return NextResponse.json(
{ error: `Photo ${i + 1}: File size must be less than 10MB` },
{ status: 400 }
)
}
const bytes = await file.arrayBuffer()
const buffer = Buffer.from(bytes)
// Calculate SHA256 hash for duplicate detection
fileHash = createHash("sha256").update(buffer).digest("hex")
// Check for duplicate file
const existingPhoto = await prisma.photo.findFirst({
where: { fileHash } as any,
})
if (existingPhoto) {
return NextResponse.json(
{ error: `Photo ${i + 1}: This photo has already been uploaded (duplicate file detected)` },
{ status: 409 }
)
}
const timestamp = Date.now()
const randomStr = Math.random().toString(36).substring(2, 15)
const extension = file.name.split(".").pop() || "jpg"
const filename = `${timestamp}-${i}-${randomStr}.${extension}`
const filepath = join(uploadsDir, filename)
await writeFile(filepath, buffer)
photoUrl = `/uploads/${filename}`
} else if (url) {
// Handle URL upload
photoUrl = url
// Check for duplicate URL
const existingPhoto = await prisma.photo.findFirst({
where: { url: photoUrl },
})
if (existingPhoto) {
return NextResponse.json(
{ error: `Photo ${i + 1}: This photo URL has already been uploaded (duplicate URL detected)` },
{ status: 409 }
)
}
} else {
return NextResponse.json(
{ error: `Photo ${i + 1}: File or URL is required` },
{ status: 400 }
)
}
// Create photo record
const photo = await prisma.photo.create({
data: {
uploaderId: session.user.id,
url: photoUrl,
fileHash,
answerName,
points: pointsValue,
penaltyEnabled: penaltyEnabled,
penaltyPoints: penaltyPointsValue,
maxAttempts: maxAttemptsValue,
} as any,
include: {
uploader: {
select: {
name: true,
},
},
},
})
createdPhotos.push(photo as PhotoWithUploader)
}
// Send emails to all other users for all photos
const allUsers = await prisma.user.findMany({
where: {
id: { not: session.user.id },
},
select: {
id: true,
email: true,
name: true,
},
})
// Send emails asynchronously for all photos
Promise.all(
allUsers.map((user: { id: string; email: string; name: string }) =>
Promise.all(
createdPhotos.map((photo: PhotoWithUploader) =>
sendNewPhotoEmail(
user.email,
user.name,
photo.id,
photo.uploader.name
).catch((err) =>
console.error(
`Failed to send email to ${user.email} for photo ${photo.id}:`,
err
)
)
)
)
)
)
return NextResponse.json(
{ photos: createdPhotos, count: createdPhotos.length },
{ status: 201 }
)
} catch (error) {
console.error("Error uploading photos:", error)
return NextResponse.json(
{ error: "Internal server error" },
{ status: 500 }
)
}
}
+164
View File
@@ -0,0 +1,164 @@
import { NextRequest, NextResponse } from "next/server"
import { auth } from "@/lib/auth"
import { prisma } from "@/lib/prisma"
import { sendNewPhotoEmail } from "@/lib/email"
import { writeFile } from "fs/promises"
import { join } from "path"
import { existsSync, mkdirSync } from "fs"
import { createHash } from "crypto"
export async function POST(req: NextRequest) {
try {
const session = await auth()
if (!session) {
return NextResponse.json({ error: "Unauthorized" }, { status: 401 })
}
const formData = await req.formData()
const file = formData.get("file") as File | null
const answerName = formData.get("answerName") as string | null
const pointsStr = formData.get("points") as string | null
const maxAttemptsStr = (formData.get("maxAttempts") as string)?.trim() || ""
if (!answerName) {
return NextResponse.json(
{ error: "Answer name is required" },
{ status: 400 }
)
}
// Validate points (must be positive integer, default to 1)
const pointsValue = pointsStr ? Math.max(1, parseInt(pointsStr, 10)) : 1
const maxAttemptsValue = maxAttemptsStr && parseInt(maxAttemptsStr, 10) > 0
? parseInt(maxAttemptsStr, 10)
: null
let photoUrl: string
let fileHash: string | null = null
if (file) {
// Handle file upload
if (!file.type.startsWith("image/")) {
return NextResponse.json(
{ error: "File must be an image" },
{ status: 400 }
)
}
// Check file size (max 10MB)
if (file.size > 10 * 1024 * 1024) {
return NextResponse.json(
{ error: "File size must be less than 10MB" },
{ status: 400 }
)
}
const bytes = await file.arrayBuffer()
const buffer = Buffer.from(bytes)
// Calculate SHA256 hash for duplicate detection
fileHash = createHash("sha256").update(buffer).digest("hex")
// Check for duplicate file
const existingPhoto = await prisma.photo.findFirst({
where: { fileHash } as any,
})
if (existingPhoto) {
return NextResponse.json(
{ error: "This photo has already been uploaded (duplicate file detected)" },
{ status: 409 }
)
}
// Generate unique filename
const timestamp = Date.now()
const randomStr = Math.random().toString(36).substring(2, 15)
const extension = file.name.split(".").pop() || "jpg"
const filename = `${timestamp}-${randomStr}.${extension}`
// Ensure uploads directory exists
const uploadsDir = join(process.cwd(), "public", "uploads")
if (!existsSync(uploadsDir)) {
mkdirSync(uploadsDir, { recursive: true })
}
// Save file
const filepath = join(uploadsDir, filename)
await writeFile(filepath, buffer)
// Set URL to the uploaded file
photoUrl = `/uploads/${filename}`
} else {
// Handle URL upload (fallback)
const url = formData.get("url") as string | null
if (!url) {
return NextResponse.json(
{ error: "Either file or URL is required" },
{ status: 400 }
)
}
photoUrl = url
// Check for duplicate URL
const existingPhoto = await prisma.photo.findFirst({
where: { url: photoUrl },
})
if (existingPhoto) {
return NextResponse.json(
{ error: "This photo URL has already been uploaded (duplicate URL detected)" },
{ status: 409 }
)
}
}
const photo = await prisma.photo.create({
data: {
uploaderId: session.user.id,
url: photoUrl,
fileHash,
answerName: answerName.trim(),
points: pointsValue,
maxAttempts: maxAttemptsValue,
} as any,
include: {
uploader: {
select: {
name: true,
},
},
},
})
// Send emails to all other users
const allUsers = await prisma.user.findMany({
where: {
id: { not: session.user.id },
},
select: {
id: true,
email: true,
name: true,
},
})
// Send emails asynchronously (don't wait for them)
Promise.all(
allUsers.map((user: { id: string; email: string; name: string }) =>
sendNewPhotoEmail(user.email, user.name, photo.id, photo.uploader.name).catch(
(err) => console.error(`Failed to send email to ${user.email}:`, err)
)
)
)
return NextResponse.json({ photo }, { status: 201 })
} catch (error) {
console.error("Error uploading photo:", error)
return NextResponse.json(
{ error: "Internal server error" },
{ status: 500 }
)
}
}