Files
familienarchiv/frontend/src/routes/profile/+page.server.ts
Marcel dc6ea080c4 fix(#71-#73): address all review findings from Markus and Sara
BLOCKERs:
- Remove direct AppUserRepository/CommentRepository access from CommentService and
  NotificationService — replaced with UserService.findAllById() and UserService
  (fixes layering contract from CLAUDE.md)
- Switch Optional<JavaMailSender> constructor injection — removes @Autowired(required=false)
  field and ReflectionTestUtils hack in tests
- Add @RequirePermission(READ_ALL) to UserSearchController — prevents user enumeration
  without read access

Data bug:
- Promote actorName from @Transient to persisted VARCHAR column (V18 migration)
- Set actorName in notifyReply and notifyMentions from comment.getAuthorName()

Architecture:
- Add @RequirePermission(READ_ALL) to NotificationController
- Introduce NotificationDTO — controller returns DTO instead of Notification entity,
  eliminating lazy-load N+1 and AppUser field leakage
- Change mentions FetchType to EAGER — fixes LazyInitializationException outside transaction
- Add @Transactional(propagation=REQUIRES_NEW) to notifyReply/notifyMentions so a
  notification failure cannot roll back the parent comment
- N+1 fix: replace per-ID findById loops with single findAllById bulk fetch
- Move collectParticipantIds to CommentService; notifyReply accepts Set<UUID> directly

Security:
- Escape displayName before injecting into renderBody HTML span
- Replace <a href="#"> with <span class="mention"> — no profile page to link to, and
  the anchor's scroll-to-top behaviour is harmful

Tests added/fixed:
- markRead_throwsNotFound, markAllRead_delegatesToRepository, countUnread_delegatesToRepository
- markOneRead_returns401, @RequirePermission 403 coverage for both controllers
- postComment/replyToComment_triggersNotifyMentions_whenMentionedUserIdsProvided
- search_returnsAtMostTenResults now asserts $.length() <= 10
- XSS regression test for escaped displayName in mention.spec.ts

Frontend minors:
- relativeTime() uses Intl.RelativeTimeFormat (locale-aware, not German-hardcoded)
- aria-label uses m.notification_unread() Paraglide key (de/en/es added)
- <div role="button"> replaced with <button> (native Enter+Space handling)
- onDestroy clears debounceTimer in MentionEditor
- setTimeout(100) replaced with await tick() + requestAnimationFrame in CommentThread
- Notification prefs form uses checkbox name attributes + formData.has() pattern

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-03-28 00:31:38 +01:00

81 lines
2.8 KiB
TypeScript

import { fail } from '@sveltejs/kit';
import { env } from '$env/dynamic/private';
import type { PageServerLoad, Actions } from './$types';
import { createApiClient } from '$lib/api.server';
import { getErrorMessage } from '$lib/errors';
const apiBase = () => env.API_INTERNAL_URL || 'http://localhost:8080';
export const load: PageServerLoad = async ({ locals, fetch }) => {
const res = await fetch(`${apiBase()}/api/users/me/notification-preferences`);
const notificationPrefs = res.ok ? await res.json() : null;
return { user: locals.user, notificationPrefs };
};
export const actions: Actions = {
updateProfile: async ({ request, fetch }) => {
const formData = await request.formData();
const body = {
firstName: formData.get('firstName')?.toString().trim() || undefined,
lastName: formData.get('lastName')?.toString().trim() || undefined,
birthDate: (formData.get('birthDate')?.toString() || undefined) as string | undefined,
email: formData.get('email')?.toString().trim() || undefined,
contact: formData.get('contact')?.toString().trim() || undefined
};
const api = createApiClient(fetch);
const result = await api.PUT('/api/users/me', { body });
if (!result.response.ok) {
const code = (result.error as unknown as { code?: string })?.code;
return fail(result.response.status, { updateError: getErrorMessage(code) });
}
return { updateSuccess: true };
},
changePassword: async ({ request, fetch }) => {
const formData = await request.formData();
const currentPassword = formData.get('currentPassword')?.toString() ?? '';
const newPassword = formData.get('newPassword')?.toString() ?? '';
const confirmPassword = formData.get('confirmPassword')?.toString() ?? '';
if (newPassword !== confirmPassword) {
return fail(400, { passwordError: 'PASSWORDS_DO_NOT_MATCH' });
}
const api = createApiClient(fetch);
const result = await api.POST('/api/users/me/password', {
body: { currentPassword, newPassword }
});
if (!result.response.ok) {
const code = (result.error as unknown as { code?: string })?.code;
return fail(result.response.status, { passwordError: getErrorMessage(code) });
}
return { passwordSuccess: true };
},
updateNotificationPrefs: async ({ request, fetch }) => {
const formData = await request.formData();
const body = {
notifyOnReply: formData.has('notifyOnReply'),
notifyOnMention: formData.has('notifyOnMention')
};
const res = await fetch(`${apiBase()}/api/users/me/notification-preferences`, {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(body)
});
if (!res.ok) {
const data = await res.json().catch(() => ({}));
return fail(res.status, { prefsError: getErrorMessage(data?.code) });
}
return { prefsSuccess: true };
}
};