|
| 1 | +import { NextRequest, NextResponse } from "next/server"; |
| 2 | +import * as yup from "yup"; |
| 3 | +import { StatusError } from "@stackframe/stack-shared/dist/utils/errors"; |
| 4 | +import { deprecatedParseRequest, deprecatedSmartRouteHandler } from "@/lib/route-handlers"; |
| 5 | +import { checkApiKeySet, publishableClientKeyHeaderSchema } from "@/lib/api-keys"; |
| 6 | +import { decodeAccessToken, authorizationHeaderSchema } from "@/lib/access-token"; |
| 7 | +import { sendVerificationEmail } from "@/email"; |
| 8 | +import { getClientUser } from "@/lib/users"; |
| 9 | +import { KnownErrors } from "@stackframe/stack-shared"; |
| 10 | + |
| 11 | +const postSchema = yup.object({ |
| 12 | + headers: yup.object({ |
| 13 | + authorization: authorizationHeaderSchema.default(undefined), |
| 14 | + "x-stack-publishable-client-key": publishableClientKeyHeaderSchema.default(""), |
| 15 | + "x-stack-project-id": yup.string().required(), |
| 16 | + }).required(), |
| 17 | + body: yup.object({ |
| 18 | + emailVerificationRedirectUrl: yup.string().required(), |
| 19 | + }).required(), |
| 20 | +}); |
| 21 | + |
| 22 | +const handler = deprecatedSmartRouteHandler(async (req: NextRequest) => { |
| 23 | + const { |
| 24 | + headers: { |
| 25 | + authorization, |
| 26 | + "x-stack-project-id": projectId, |
| 27 | + "x-stack-publishable-client-key": publishableClientKey, |
| 28 | + }, |
| 29 | + body: { |
| 30 | + emailVerificationRedirectUrl |
| 31 | + }, |
| 32 | + } = await deprecatedParseRequest(req, postSchema); |
| 33 | + |
| 34 | + if (!authorization) { |
| 35 | + return NextResponse.json(null); |
| 36 | + } |
| 37 | + |
| 38 | + const pkValid = await checkApiKeySet(projectId, { publishableClientKey }); |
| 39 | + if (!pkValid) { |
| 40 | + throw new StatusError(StatusError.Forbidden); |
| 41 | + } |
| 42 | + |
| 43 | + const decodedAccessToken = await decodeAccessToken(authorization.split(" ")[1]); |
| 44 | + const { userId, projectId: accessTokenProjectId } = decodedAccessToken; |
| 45 | + |
| 46 | + if (accessTokenProjectId !== projectId) { |
| 47 | + throw new StatusError(StatusError.Forbidden); |
| 48 | + } |
| 49 | + |
| 50 | + const user = await getClientUser(projectId, userId); |
| 51 | + if (!user) { |
| 52 | + throw new StatusError(StatusError.NotFound); |
| 53 | + } |
| 54 | + if (user.primaryEmailVerified) { |
| 55 | + throw new KnownErrors.EmailAlreadyVerified(); |
| 56 | + } |
| 57 | + try { |
| 58 | + await sendVerificationEmail(projectId, userId, emailVerificationRedirectUrl); |
| 59 | + } catch (e) { |
| 60 | + console.error(e); |
| 61 | + throw e; |
| 62 | + } |
| 63 | + return NextResponse.json({}); |
| 64 | +}); |
| 65 | +export const POST = handler; |
0 commit comments