Skip to content

Self-hosted personal gallery application with online photo management and albums, supporting Live/Motion Photos, EXIF parsing, geolocation recognition, and an explore map.

feat(photos): improve reaction retrieval by filtering accessible photo IDs

Ahmet Ömer122161615c82
diff --git a/server/api/photos/[photoId]/reactions.ts b/server/api/photos/[photoId]/reactions.ts
index 57e60488..f97db333 100644
--- a/server/api/photos/[photoId]/reactions.ts
+++ b/server/api/photos/[photoId]/reactions.ts
@@ -1,5 +1,6 @@
import type { H3Event } from 'h3'
import { eq, and, sql } from 'drizzle-orm'
+import { assertPhotoIdAccess } from '../../../utils/album-access'
const REACTION_TYPES = [
'like',
@@ -59,6 +60,8 @@ export default defineEventHandler(async (event) => {
})
}
+ await assertPhotoIdAccess(event, photoId)
+
const db = useDB()
const method = event.method
@@ -129,20 +132,6 @@ export default defineEventHandler(async (event) => {
})
}
- // 检查照片是否存在
- const photo = await db
- .select()
- .from(tables.photos)
- .where(eq(tables.photos.id, photoId))
- .get()
-
- if (!photo) {
- throw createError({
- statusCode: 404,
- message: 'Photo not found',
- })
- }
-
// 获取额外信息用于审计
const headers = getHeaders(event)
const ipAddress = getRequestIP(event, { xForwardedFor: true })
diff --git a/server/api/photos/reactions.get.ts b/server/api/photos/reactions.get.ts
index 60b3666b..9bab70d5 100644
--- a/server/api/photos/reactions.get.ts
+++ b/server/api/photos/reactions.get.ts
@@ -1,4 +1,5 @@
import { sql, inArray } from 'drizzle-orm'
+import { filterAccessiblePhotoIds } from '../../utils/album-access'
export default defineEventHandler(async (event) => {
const query = getQuery(event)
@@ -11,10 +12,15 @@ export default defineEventHandler(async (event) => {
})
}
- // 支持单个或多个 ID
- const ids = Array.isArray(photoIds) ? photoIds : [photoIds]
+ // 支持单个或多个 ID。不可见的照片与不存在的 ID 一样不出现在结果里。
+ const requestedIds = (Array.isArray(photoIds) ? photoIds : [photoIds]).filter(
+ (id): id is string => typeof id === 'string' && id.length > 0,
+ )
+ const accessibleIds = [
+ ...(await filterAccessiblePhotoIds(event, requestedIds)),
+ ]
- if (ids.length === 0) {
+ if (accessibleIds.length === 0) {
return {}
}
@@ -28,14 +34,14 @@ export default defineEventHandler(async (event) => {
count: sql<number>`count(*)`,
})
.from(tables.photoReactions)
- .where(inArray(tables.photoReactions.photoId, ids as string[]))
+ .where(inArray(tables.photoReactions.photoId, accessibleIds))
.groupBy(tables.photoReactions.photoId, tables.photoReactions.reactionType)
.all()
const result: Record<string, Record<string, number>> = {}
- ids.forEach((id) => {
- result[id as string] = {
+ for (const id of accessibleIds) {
+ result[id] = {
like: 0,
love: 0,
amazing: 0,
@@ -45,14 +51,14 @@ export default defineEventHandler(async (event) => {
fire: 0,
sparkle: 0,
}
- })
+ }
- // 填充实际的计数
- reactions.forEach((r) => {
- if (r.photoId && r.reactionType) {
- result[r.photoId][r.reactionType] = r.count
- }
- })
+ for (const reaction of reactions) {
+ if (!reaction.photoId || !reaction.reactionType) continue
+ const counts = result[reaction.photoId]
+ if (!counts) continue
+ counts[reaction.reactionType] = reaction.count
+ }
return result
})
diff --git a/server/utils/album-access.ts b/server/utils/album-access.ts
index 564c0f75..5560eed0 100644
--- a/server/utils/album-access.ts
+++ b/server/utils/album-access.ts
@@ -1,6 +1,6 @@
import { createHmac, randomBytes, scrypt, timingSafeEqual } from 'node:crypto'
import { promisify } from 'node:util'
-import { eq, or } from 'drizzle-orm'
+import { eq, inArray, or } from 'drizzle-orm'
import type { H3Event } from 'h3'
import { tables, useDB } from './db'
@@ -108,15 +108,34 @@ export function grantAlbumAccess(
})
}
+type AlbumAccessTarget = {
+ id: number
+ isHidden: boolean
+ passwordHash: string | null
+}
+
+function photoNotFound() {
+ return createError({ statusCode: 404, statusMessage: 'Photo not found' })
+}
+
+function photoAccessDenied(
+ admin: boolean,
+ memberships: { album: AlbumAccessTarget }[],
+ canAccess: (album: AlbumAccessTarget) => boolean,
+): boolean {
+ if (admin) return false
+ return (
+ memberships.some(({ album }) => album.isHidden) ||
+ (memberships.some(({ album }) => album.passwordHash) &&
+ !memberships.some(({ album }) => album.passwordHash && canAccess(album)))
+ )
+}
+
export async function albumAccess(event: H3Event) {
const session = await getUserSession(event)
const admin = Boolean(session.user)
const grants = readGrants(event)
- const canAccess = (album: {
- id: number
- isHidden: boolean
- passwordHash: string | null
- }) =>
+ const canAccess = (album: AlbumAccessTarget) =>
admin ||
(!album.isHidden &&
(!album.passwordHash ||
@@ -141,7 +160,7 @@ export async function assertPhotoAccess(
? key
: key.replace(/\\/g, '/').replace(/\/+/g, '/').replace(/^\/+/, '')
if (!isAbsoluteUrl && key !== cleanKey) {
- throw createError({ statusCode: 404, statusMessage: 'Photo not found' })
+ throw photoNotFound()
}
const db = useDB()
@@ -187,9 +206,7 @@ export async function assertPhotoAccess(
).values(),
]
if (matchedPhotos.length === 0) {
- if (!admin || requireKnown) {
- throw createError({ statusCode: 404, statusMessage: 'Photo not found' })
- }
+ if (!admin || requireKnown) throw photoNotFound()
return false
}
let restricted = false
@@ -206,16 +223,77 @@ export async function assertPhotoAccess(
if (memberships.some(({ album }) => album.isHidden || album.passwordHash)) {
restricted = true
}
- if (
- !admin &&
- (memberships.some(({ album }) => album.isHidden) ||
- (memberships.some(({ album }) => album.passwordHash) &&
- !memberships.some(
- ({ album }) => album.passwordHash && canAccess(album),
- )))
- ) {
- throw createError({ statusCode: 404, statusMessage: 'Photo not found' })
- }
+ if (photoAccessDenied(admin, memberships, canAccess)) throw photoNotFound()
}
return restricted
}
+
+const photoIdQueryChunkSize = 500
+
+// Indexed photo-id check with the same album rule as assertPhotoAccess.
+// Unknown ids and photos in hidden or locked albums are both omitted, so a
+// guessed id cannot be confirmed. This does not call assertPhotoAccess,
+// which loads every photo row.
+export async function filterAccessiblePhotoIds(
+ event: H3Event,
+ photoIds: string[],
+): Promise<Set<string>> {
+ const uniqueIds = [...new Set(photoIds.filter((id) => id.length > 0))]
+ if (uniqueIds.length === 0) return new Set()
+
+ const { admin, canAccess } = await albumAccess(event)
+ const db = useDB()
+ const accessible = new Set<string>()
+
+ for (
+ let offset = 0;
+ offset < uniqueIds.length;
+ offset += photoIdQueryChunkSize
+ ) {
+ const chunk = uniqueIds.slice(offset, offset + photoIdQueryChunkSize)
+ const existing = db
+ .select({ id: tables.photos.id })
+ .from(tables.photos)
+ .where(inArray(tables.photos.id, chunk))
+ .all()
+ if (existing.length === 0) continue
+
+ const ids = existing.map((photo) => photo.id)
+ if (admin) {
+ for (const id of ids) accessible.add(id)
+ continue
+ }
+
+ const rows = db
+ .select({
+ photoId: tables.albumPhotos.photoId,
+ album: tables.albums,
+ })
+ .from(tables.albumPhotos)
+ .innerJoin(
+ tables.albums,
+ eq(tables.albumPhotos.albumId, tables.albums.id),
+ )
+ .where(inArray(tables.albumPhotos.photoId, ids))
+ .all()
+ const membershipsByPhoto = new Map<string, { album: AlbumAccessTarget }[]>()
+ for (const row of rows) {
+ const memberships = membershipsByPhoto.get(row.photoId)
+ const membership = { album: row.album }
+ if (memberships) memberships.push(membership)
+ else membershipsByPhoto.set(row.photoId, [membership])
+ }
+
+ for (const id of ids) {
+ const memberships = membershipsByPhoto.get(id) ?? []
+ if (!photoAccessDenied(admin, memberships, canAccess)) accessible.add(id)
+ }
+ }
+
+ return accessible
+}
+
+export async function assertPhotoIdAccess(event: H3Event, photoId: string) {
+ const accessible = await filterAccessiblePhotoIds(event, [photoId])
+ if (!accessible.has(photoId)) throw photoNotFound()
+}