Files
nextstep/src/app/api/auth/register/route.ts
Tony0410 1bb88288f4 fix: login loop and repeated medication notifications
- Fix login loop: secure cookie detection now uses x-forwarded-proto/origin
  headers to correctly identify HTTPS requests through Tailscale Funnel
- Add credentials: include to login/register fetch calls
- Verify session after login/registration before redirecting to prevent race conditions
- Fix repeated medication reminders: isDue() now matches exact minute instead of
  5-minute tolerance window, preventing duplicate notifications when sender runs
  every minute
- Add tests for cookie security and notification scheduling
- Extract isDue() to separate module for better testability
2026-03-15 12:17:42 +00:00

76 lines
2.0 KiB
TypeScript

import { NextRequest, NextResponse } from 'next/server'
import { prisma } from '@/lib/db/prisma'
import { hashPassword, createSession, getSessionCookieConfig } from '@/lib/auth'
import { registerSchema } from '@/lib/validation'
import { withRateLimit } from '@/lib/auth/middleware'
async function handler(req: NextRequest) {
try {
const body = await req.json()
const result = registerSchema.safeParse(body)
if (!result.success) {
return NextResponse.json(
{ error: 'Invalid input', details: result.error.flatten() },
{ status: 400 }
)
}
const { email, password, name } = result.data
// Check if user exists
const existing = await prisma.user.findUnique({
where: { email: email.toLowerCase() },
})
if (existing) {
return NextResponse.json(
{ error: 'An account with this email already exists' },
{ status: 409 }
)
}
// Create user
const passwordHash = await hashPassword(password)
const user = await prisma.user.create({
data: {
email: email.toLowerCase(),
passwordHash,
name,
},
select: {
id: true,
email: true,
name: true,
},
})
// Create session
const userAgent = req.headers.get('user-agent') || undefined
const ipAddress = req.headers.get('x-forwarded-for')?.split(',')[0]
const token = await createSession(user.id, userAgent, ipAddress)
const cookieConfig = getSessionCookieConfig(token, {
forwardedProto: req.headers.get('x-forwarded-proto'),
origin: req.headers.get('origin'),
referer: req.headers.get('referer'),
})
const response = NextResponse.json({
user,
message: 'Account created successfully',
})
response.cookies.set(cookieConfig)
return response
} catch (error) {
console.error('Registration error:', error)
return NextResponse.json(
{ error: 'Registration failed' },
{ status: 500 }
)
}
}
export const POST = withRateLimit(handler)