All files / Bandstand/src/app/api/account/password route.ts

0% Statements 0/46
0% Branches 0/1
0% Functions 0/1
0% Lines 0/46

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53                                                                                                         
export const dynamic = 'force-dynamic'
 
import {z} from 'zod'
import {prisma} from '@/lib/db'
import {requireUser} from '@/lib/guard'
import {MIN_PASSWORD_LENGTH, hashPassword, verifyPassword} from '@/lib/password'
import {logActivity} from '@/lib/songs'
import {route} from '@/lib/route'
 
const Body = z.object({
  // Not needed when setting a first password (Google sign-in members)
  current: z.string().optional(),
  next: z.string().min(MIN_PASSWORD_LENGTH).max(200),
})
 
// Change your own password. Signs out your other devices.
export const POST = route(async (req: Request) => {
  const {user} = await requireUser()
  const parsed = Body.safeParse(await req.json())
  if (!parsed.success)
    return Response.json(
      {
        error: `New password must be at least ${MIN_PASSWORD_LENGTH} characters.`,
      },
      {status: 400},
    )
  if (
    user.passwordHash &&
    !(await verifyPassword(parsed.data.current ?? '', user.passwordHash))
  )
    return Response.json({error: 'Current password is wrong.'}, {status: 403})
  const passwordHash = await hashPassword(parsed.data.next)
  await prisma.$transaction(async (tx) => {
    await tx.user.update({
      where: {id: user.id},
      data: {
        passwordHash,
        passwordSetAt: new Date(),
        sessionVersion: {increment: 1},
      },
    })
    await logActivity(tx, {
      bandId: null,
      userId: user.id,
      action: 'account.password',
      targetType: 'user',
      targetId: user.id,
      summary: 'changed their password',
    })
  })
  return new Response(null, {status: 204})
})