pummmp.fun/app/api/user/onboarding/route.ts
2026-07-04 12:49:09 -07:00

79 lines
2.8 KiB
TypeScript

import { NextResponse } from 'next/server'
import { getServerSession } from 'next-auth'
import { authOptions } from '@/lib/auth'
import { connectToDatabase } from '@/lib/mongodb'
import { ObjectId } from 'mongodb'
import { isReservedUsername } from '@/lib/validations'
export async function POST(req: Request) {
try {
const session = await getServerSession(authOptions)
if (!session) {
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
}
const { username } = await req.json();
// validation
if (!username || typeof username !== 'string') {
return NextResponse.json({ error: 'Username is required' }, { status: 400 })
}
if (username.length < 3 || username.length > 20) {
return NextResponse.json({ error: 'Username must be between 3 and 20 characters' }, { status: 400 })
}
const usernameRegex = /^[a-zA-Z0-9_-]+$/
if (!usernameRegex.test(username)) {
return NextResponse.json({ error: 'Username can only contain letters, numbers, underscores, and dashes' }, { status: 400 })
}
if (isReservedUsername(username)) {
return NextResponse.json({ error: 'This username is reserved' }, { status: 400 })
}
// database checks
const { db } = await connectToDatabase();
// check if onboarding flag is true
const currentUser = await db.collection('users').findOne({ _id: new ObjectId(session.user.id) })
if (!currentUser) {
return NextResponse.json({ error: 'User not found' }, { status: 404 })
}
if (!currentUser.isOnboarding) {
return NextResponse.json({ error: 'Onboarding already completed' }, { status: 400 })
}
// check if username is taken (case insensitive)
const existingUser = await db.collection('users').findOne({
name: { $regex: new RegExp(`^${username}$`, 'i') }
})
// ! if a user exists with this name AND it's not the current user (unlikely if they are onboarding, but good safety)
if (existingUser && existingUser._id.toString() !== session.user.id) {
return NextResponse.json({ error: 'Username is already taken' }, { status: 409 })
}
// then we update the name, and remove the `isOnboarding` flag
const result = await db.collection('users').updateOne(
{ _id: new ObjectId(session.user.id) },
{
$set: {
name: username,
isOnboarding: false
}
}
)
if (result.modifiedCount === 0) {
// ? did we fail to find the user?
return NextResponse.json({ error: 'Failed to update profile' }, { status: 500 })
}
return NextResponse.json({ success: true, username })
} catch (error) {
console.error('Onboarding API Error:', error)
return NextResponse.json({ error: 'Internal Server Error' }, { status: 500 })
}
}