feat: gebruikersprofiel met avatar, bio en uitgebreide beschrijving
- Schema: bio (160), bio_detail (2000) en avatar_data (bytea) op User - POST /api/profile/avatar: validatie MIME-type + max 12 MB vóór verwerking, Sharp resize naar max 700x700 (fit inside), output WebP q85, opgeslagen als bytea in Neon - GET /api/profile/avatar: serveert avatar met Cache-Control private 1u - updateProfileAction: slaat bio en bio_detail op via Server Action + Zod - ProfileEditor client component: avatar preview, upload met client-side validatie, bio-velden met tekenlimieten - Settings page: profiel-sectie bovenaan, uitgeschakeld voor demo-gebruiker - next.config: sharp als serverExternalPackage Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
parent
45011a3347
commit
1ff894a6c0
7 changed files with 300 additions and 1 deletions
40
actions/profile.ts
Normal file
40
actions/profile.ts
Normal file
|
|
@ -0,0 +1,40 @@
|
|||
'use server'
|
||||
|
||||
import { revalidatePath } from 'next/cache'
|
||||
import { cookies } from 'next/headers'
|
||||
import { getIronSession } from 'iron-session'
|
||||
import { z } from 'zod'
|
||||
import { prisma } from '@/lib/prisma'
|
||||
import { SessionData, sessionOptions } from '@/lib/session'
|
||||
|
||||
async function getSession() {
|
||||
return getIronSession<SessionData>(await cookies(), sessionOptions)
|
||||
}
|
||||
|
||||
const profileSchema = z.object({
|
||||
bio: z.string().max(160).optional(),
|
||||
bio_detail: z.string().max(2000).optional(),
|
||||
})
|
||||
|
||||
export async function updateProfileAction(_prevState: unknown, formData: FormData) {
|
||||
const session = await getSession()
|
||||
if (!session.userId) return { error: 'Niet ingelogd' }
|
||||
if (session.isDemo) return { error: 'Niet beschikbaar in demo-modus' }
|
||||
|
||||
const parsed = profileSchema.safeParse({
|
||||
bio: (formData.get('bio') as string) || undefined,
|
||||
bio_detail: (formData.get('bio_detail') as string) || undefined,
|
||||
})
|
||||
if (!parsed.success) return { error: parsed.error.flatten().fieldErrors }
|
||||
|
||||
await prisma.user.update({
|
||||
where: { id: session.userId },
|
||||
data: {
|
||||
bio: parsed.data.bio ?? null,
|
||||
bio_detail: parsed.data.bio_detail ?? null,
|
||||
},
|
||||
})
|
||||
|
||||
revalidatePath('/settings')
|
||||
return { success: true }
|
||||
}
|
||||
|
|
@ -4,13 +4,17 @@ import { SessionData, sessionOptions } from '@/lib/session'
|
|||
import { prisma } from '@/lib/prisma'
|
||||
import { RoleManager } from '@/components/settings/role-manager'
|
||||
import { LeaveProductButton } from '@/components/settings/leave-product-button'
|
||||
import { ProfileEditor } from '@/components/settings/profile-editor'
|
||||
import Link from 'next/link'
|
||||
|
||||
export default async function SettingsPage() {
|
||||
const session = await getIronSession<SessionData>(await cookies(), sessionOptions)
|
||||
|
||||
const [user, userRoles, memberships] = await Promise.all([
|
||||
prisma.user.findUnique({ where: { id: session.userId }, select: { username: true } }),
|
||||
prisma.user.findUnique({
|
||||
where: { id: session.userId },
|
||||
select: { username: true, bio: true, bio_detail: true, avatar_data: true, updated_at: true },
|
||||
}),
|
||||
prisma.userRole.findMany({ where: { user_id: session.userId } }),
|
||||
prisma.productMember.findMany({
|
||||
where: { user_id: session.userId },
|
||||
|
|
@ -24,6 +28,25 @@ export default async function SettingsPage() {
|
|||
<div className="p-6 max-w-2xl mx-auto w-full space-y-6">
|
||||
<h1 className="text-xl font-medium text-foreground">Instellingen</h1>
|
||||
|
||||
<div className="bg-surface-container-low border border-border rounded-xl p-5 space-y-4">
|
||||
<div>
|
||||
<h2 className="text-sm font-medium text-foreground">Profiel</h2>
|
||||
<p className="text-xs text-muted-foreground mt-0.5">
|
||||
Zichtbaar voor teamleden die je toevoegen aan een product backlog.
|
||||
</p>
|
||||
</div>
|
||||
{session.isDemo ? (
|
||||
<p className="text-sm text-muted-foreground">Niet beschikbaar in demo-modus.</p>
|
||||
) : (
|
||||
<ProfileEditor
|
||||
bio={user?.bio ?? null}
|
||||
bioDetail={user?.bio_detail ?? null}
|
||||
hasAvatar={!!user?.avatar_data}
|
||||
avatarVersion={user?.updated_at?.getTime() ?? 0}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="bg-surface-container-low border border-border rounded-xl p-5 space-y-3">
|
||||
<h2 className="text-sm font-medium text-foreground">Account</h2>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
|
|
|
|||
73
app/api/profile/avatar/route.ts
Normal file
73
app/api/profile/avatar/route.ts
Normal file
|
|
@ -0,0 +1,73 @@
|
|||
import { cookies } from 'next/headers'
|
||||
import { getIronSession } from 'iron-session'
|
||||
import sharp from 'sharp'
|
||||
import { prisma } from '@/lib/prisma'
|
||||
import { SessionData, sessionOptions } from '@/lib/session'
|
||||
|
||||
const MAX_BYTES = 12 * 1024 * 1024
|
||||
const ALLOWED_TYPES = new Set(['image/jpeg', 'image/png', 'image/webp'])
|
||||
|
||||
async function getSession() {
|
||||
return getIronSession<SessionData>(await cookies(), sessionOptions)
|
||||
}
|
||||
|
||||
export async function POST(request: Request) {
|
||||
const session = await getSession()
|
||||
if (!session.userId) {
|
||||
return Response.json({ error: 'Niet ingelogd' }, { status: 401 })
|
||||
}
|
||||
if (session.isDemo) {
|
||||
return Response.json({ error: 'Niet beschikbaar in demo-modus' }, { status: 403 })
|
||||
}
|
||||
|
||||
const formData = await request.formData()
|
||||
const file = formData.get('avatar') as File | null
|
||||
if (!file || file.size === 0) {
|
||||
return Response.json({ error: 'Geen bestand ontvangen' }, { status: 400 })
|
||||
}
|
||||
|
||||
if (!ALLOWED_TYPES.has(file.type)) {
|
||||
return Response.json({ error: 'Alleen JPEG, PNG en WebP zijn toegestaan' }, { status: 400 })
|
||||
}
|
||||
|
||||
if (file.size > MAX_BYTES) {
|
||||
return Response.json({ error: 'Bestand is groter dan 12 MB' }, { status: 400 })
|
||||
}
|
||||
|
||||
const input = Buffer.from(await file.arrayBuffer())
|
||||
|
||||
const processed = await sharp(input)
|
||||
.resize(700, 700, { fit: 'inside', withoutEnlargement: true })
|
||||
.webp({ quality: 85 })
|
||||
.toBuffer()
|
||||
|
||||
await prisma.user.update({
|
||||
where: { id: session.userId },
|
||||
data: { avatar_data: new Uint8Array(processed) },
|
||||
})
|
||||
|
||||
return Response.json({ ok: true })
|
||||
}
|
||||
|
||||
export async function GET() {
|
||||
const session = await getSession()
|
||||
if (!session.userId) {
|
||||
return new Response(null, { status: 401 })
|
||||
}
|
||||
|
||||
const user = await prisma.user.findUnique({
|
||||
where: { id: session.userId },
|
||||
select: { avatar_data: true },
|
||||
})
|
||||
|
||||
if (!user?.avatar_data) {
|
||||
return new Response(null, { status: 404 })
|
||||
}
|
||||
|
||||
return new Response(user.avatar_data, {
|
||||
headers: {
|
||||
'Content-Type': 'image/webp',
|
||||
'Cache-Control': 'private, max-age=3600',
|
||||
},
|
||||
})
|
||||
}
|
||||
155
components/settings/profile-editor.tsx
Normal file
155
components/settings/profile-editor.tsx
Normal file
|
|
@ -0,0 +1,155 @@
|
|||
'use client'
|
||||
|
||||
import { useActionState, useRef, useState } from 'react'
|
||||
import Image from 'next/image'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Input } from '@/components/ui/input'
|
||||
import { Textarea } from '@/components/ui/textarea'
|
||||
import { updateProfileAction } from '@/actions/profile'
|
||||
|
||||
interface ProfileEditorProps {
|
||||
bio: string | null
|
||||
bioDetail: string | null
|
||||
hasAvatar: boolean
|
||||
avatarVersion: number
|
||||
}
|
||||
|
||||
const ALLOWED = ['image/jpeg', 'image/png', 'image/webp']
|
||||
const MAX_BYTES = 12 * 1024 * 1024
|
||||
|
||||
export function ProfileEditor({ bio, bioDetail, hasAvatar, avatarVersion }: ProfileEditorProps) {
|
||||
const [state, formAction, isPending] = useActionState(updateProfileAction, null)
|
||||
const [avatarSrc, setAvatarSrc] = useState<string | null>(
|
||||
hasAvatar ? `/api/profile/avatar?v=${avatarVersion}` : null
|
||||
)
|
||||
const [uploadError, setUploadError] = useState<string | null>(null)
|
||||
const [uploading, setUploading] = useState(false)
|
||||
const fileRef = useRef<HTMLInputElement>(null)
|
||||
|
||||
async function handleFile(e: React.ChangeEvent<HTMLInputElement>) {
|
||||
const file = e.target.files?.[0]
|
||||
if (!file) return
|
||||
|
||||
setUploadError(null)
|
||||
|
||||
if (!ALLOWED.includes(file.type)) {
|
||||
setUploadError('Alleen JPEG, PNG en WebP zijn toegestaan')
|
||||
return
|
||||
}
|
||||
if (file.size > MAX_BYTES) {
|
||||
setUploadError('Bestand is groter dan 12 MB')
|
||||
return
|
||||
}
|
||||
|
||||
const reader = new FileReader()
|
||||
reader.onload = (ev) => setAvatarSrc(ev.target?.result as string)
|
||||
reader.readAsDataURL(file)
|
||||
|
||||
setUploading(true)
|
||||
try {
|
||||
const fd = new FormData()
|
||||
fd.append('avatar', file)
|
||||
const res = await fetch('/api/profile/avatar', { method: 'POST', body: fd })
|
||||
const data = await res.json()
|
||||
if (!res.ok) {
|
||||
setUploadError(data.error ?? 'Upload mislukt')
|
||||
setAvatarSrc(hasAvatar ? `/api/profile/avatar?v=${avatarVersion}` : null)
|
||||
}
|
||||
} finally {
|
||||
setUploading(false)
|
||||
if (fileRef.current) fileRef.current.value = ''
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="space-y-5">
|
||||
<div className="flex items-center gap-5">
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => fileRef.current?.click()}
|
||||
disabled={uploading}
|
||||
className="relative w-20 h-20 rounded-full bg-surface-container border border-border overflow-hidden flex items-center justify-center hover:opacity-80 transition-opacity shrink-0 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary"
|
||||
aria-label="Profielfoto wijzigen"
|
||||
>
|
||||
{avatarSrc ? (
|
||||
<Image src={avatarSrc} alt="Profielfoto" fill className="object-cover" unoptimized />
|
||||
) : (
|
||||
<span className="text-3xl select-none text-muted-foreground">?</span>
|
||||
)}
|
||||
{uploading && (
|
||||
<div className="absolute inset-0 bg-background/70 flex items-center justify-center">
|
||||
<span className="text-xs text-foreground font-medium">Laden…</span>
|
||||
</div>
|
||||
)}
|
||||
</button>
|
||||
|
||||
<div className="space-y-1.5">
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={() => fileRef.current?.click()}
|
||||
disabled={uploading}
|
||||
>
|
||||
{uploading ? 'Uploaden…' : 'Foto wijzigen'}
|
||||
</Button>
|
||||
<p className="text-xs text-muted-foreground">JPEG, PNG of WebP — max 12 MB</p>
|
||||
{uploadError && <p className="text-xs text-error">{uploadError}</p>}
|
||||
</div>
|
||||
|
||||
<input
|
||||
ref={fileRef}
|
||||
type="file"
|
||||
accept="image/jpeg,image/png,image/webp"
|
||||
className="hidden"
|
||||
onChange={handleFile}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<form action={formAction} className="space-y-4">
|
||||
<div className="space-y-1.5">
|
||||
<label htmlFor="bio" className="text-xs font-medium text-foreground">
|
||||
Korte omschrijving
|
||||
</label>
|
||||
<Input
|
||||
id="bio"
|
||||
name="bio"
|
||||
defaultValue={bio ?? ''}
|
||||
placeholder="Bijv. Full-stack developer bij Acme"
|
||||
maxLength={160}
|
||||
disabled={isPending}
|
||||
/>
|
||||
<p className="text-xs text-muted-foreground">Max. 160 tekens</p>
|
||||
</div>
|
||||
|
||||
<div className="space-y-1.5">
|
||||
<label htmlFor="bio_detail" className="text-xs font-medium text-foreground">
|
||||
Uitgebreide beschrijving
|
||||
</label>
|
||||
<Textarea
|
||||
id="bio_detail"
|
||||
name="bio_detail"
|
||||
defaultValue={bioDetail ?? ''}
|
||||
placeholder="Vertel meer over jezelf, je werkwijze of je projecten…"
|
||||
maxLength={2000}
|
||||
rows={5}
|
||||
disabled={isPending}
|
||||
/>
|
||||
<p className="text-xs text-muted-foreground">Max. 2000 tekens</p>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center gap-3">
|
||||
<Button type="submit" size="sm" disabled={isPending}>
|
||||
{isPending ? 'Opslaan…' : 'Opslaan'}
|
||||
</Button>
|
||||
{state && 'success' in state && (
|
||||
<p className="text-xs text-success">Profiel opgeslagen.</p>
|
||||
)}
|
||||
{state && 'error' in state && typeof state.error === 'string' && (
|
||||
<p className="text-xs text-error">{state.error}</p>
|
||||
)}
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
|
@ -2,6 +2,7 @@ import type { NextConfig } from "next"
|
|||
import pkg from "./package.json"
|
||||
|
||||
const nextConfig: NextConfig = {
|
||||
serverExternalPackages: ['sharp'],
|
||||
env: {
|
||||
NEXT_PUBLIC_APP_VERSION: pkg.version,
|
||||
NEXT_PUBLIC_BUILD_DATE: new Date().toISOString(),
|
||||
|
|
|
|||
|
|
@ -0,0 +1,4 @@
|
|||
-- AlterTable
|
||||
ALTER TABLE "users" ADD COLUMN "avatar_data" BYTEA,
|
||||
ADD COLUMN "bio" VARCHAR(160),
|
||||
ADD COLUMN "bio_detail" VARCHAR(2000);
|
||||
|
|
@ -45,6 +45,9 @@ model User {
|
|||
username String @unique
|
||||
password_hash String
|
||||
is_demo Boolean @default(false)
|
||||
bio String? @db.VarChar(160)
|
||||
bio_detail String? @db.VarChar(2000)
|
||||
avatar_data Bytes?
|
||||
created_at DateTime @default(now())
|
||||
updated_at DateTime @updatedAt
|
||||
roles UserRole[]
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue