All files / app/api/admin/tenants/invite-owner route.ts

85.48% Statements 53/62
95.83% Branches 23/24
33.33% Functions 1/3
85.48% Lines 53/62

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 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179              1x 1x 1x 1x 1x 1x 1x   1x 1x 1x 1x     1x   1x 9x 9x 9x   9x 1x     8x 1x     7x 7x 1x     6x     6x                 6x 1x     5x 5x 5x     5x 1x             4x 4x         4x 1x             3x 3x     3x     3x         3x 1x             2x 1x             1x                           1x                 1x             1x 1x 1x   1x 1x                         1x                                    
/**
 * POST /api/admin/tenants/invite-owner
 * Send an invitation to become the owner of a tenant
 * Only accessible by Super Admins
 * @see JCN-24 Email validation
 * @see JCN-25 Rate limiting
 */
import { NextRequest, NextResponse } from "next/server";
import { cookies } from "next/headers";
import { getCurrentUser, fetchAuthSession } from "aws-amplify/auth/server";
import { runWithAmplifyServerContext } from "@/lib/amplify-server-utils";
import { generateClient } from "aws-amplify/data";
import { Amplify } from "aws-amplify";
import outputs from "../../../../../../amplify_outputs.json";
import { type Schema } from "../../../../../../amplify/data/resource";
import { sendInvitationEmail } from "@/lib/email";
import { validateEmail } from "@/lib/validation";
import { checkRateLimit, RATE_LIMITS } from "@/lib/rate-limit";
import { randomUUID } from "crypto";
 
// Configure Amplify for server-side
Amplify.configure(outputs, { ssr: true });
 
export async function POST(request: NextRequest) {
  try {
    const body = await request.json();
    const { tenantId, email } = body as { tenantId: string; email: string };
 
    if (!tenantId) {
      return NextResponse.json({ error: "Tenant ID is required" }, { status: 400 });
    }
 
    if (!email) {
      return NextResponse.json({ error: "Email is required" }, { status: 400 });
    }
 
    const emailValidation = validateEmail(email);
    if (!emailValidation.valid) {
      return NextResponse.json({ error: emailValidation.error }, { status: 400 });
    }
 
    const cookieStore = await cookies();
 
    // Get current user's session
    const session = await runWithAmplifyServerContext({
      nextServerContext: { cookies: async () => cookieStore },
      operation: async (context: Parameters<typeof getCurrentUser>[0]) => {
        const user = await getCurrentUser(context);
        const session = await fetchAuthSession(context);
        return { user, session };
      },
    });
 
    if (!session.session.tokens?.idToken) {
      return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
    }
 
    const idToken = session.session.tokens.idToken;
    const platformRole = idToken.payload["custom:platform_role"] as string | undefined;
    const inviterEmail = idToken.payload.email as string;
 
    // Only super admins can invite owners
    if (platformRole !== "super_admin") {
      return NextResponse.json(
        { error: "Only Super Admins can invite owners" },
        { status: 403 }
      );
    }
 
    // Rate limiting: 10 invitations per hour per user (JCN-25)
    const rateLimitKey = `admin-invite:${session.user.userId}`;
    const rateLimit = checkRateLimit(
      rateLimitKey,
      RATE_LIMITS.invitation.limit,
      RATE_LIMITS.invitation.windowMs
    );
    if (!rateLimit.allowed) {
      return NextResponse.json(
        { error: "Too many invitations. Please try again later." },
        { status: 429 }
      );
    }
 
    // Create invitation token
    const invitationToken = randomUUID();
    const expiresAt = new Date(Date.now() + 7 * 24 * 60 * 60 * 1000); // 7 days
 
    // Create invitation record using API key auth
    const client = generateClient<Schema>();
 
    // Get tenant details
    const { data: tenant, errors: tenantErrors } = await client.models.Tenant.get(
      { id: tenantId },
      { authMode: "apiKey" }
    );
 
    if (tenantErrors || !tenant) {
      return NextResponse.json(
        { error: "Tenant not found" },
        { status: 404 }
      );
    }
 
    // Check tenant is in correct state
    if (tenant.status !== "pending_owner") {
      return NextResponse.json(
        { error: "Tenant already has an owner or is not pending" },
        { status: 400 }
      );
    }
 
    // Create invitation
    const { data: invitation, errors } = await client.models.TenantInvitation.create(
      {
        id: invitationToken,
        tenantId,
        email: email.toLowerCase(),
        role: "owner",
        status: "pending",
        expiresAt: expiresAt.toISOString(),
        invitedBy: session.user.userId,
        createdAt: new Date().toISOString(),
      },
      { authMode: "apiKey" }
    );
 
    Iif (errors) {
      console.error("Error creating invitation:", errors);
      return NextResponse.json(
        { error: "Failed to create invitation" },
        { status: 500 }
      );
    }
 
    // Update tenant status
    await client.models.Tenant.update(
      { id: tenantId, status: "awaiting_owner_signup" },
      { authMode: "apiKey" }
    );
 
    // Send invitation email
    // Derive base URL from request to ensure correct links in any environment
    const protocol = request.headers.get("x-forwarded-proto") || "https";
    const host = request.headers.get("host") || "localhost:3000";
    const baseUrl = `${protocol}://${host}`;
 
    try {
      await sendInvitationEmail({
        to: email,
        organisationName: tenant.name,
        inviterName: inviterEmail,
        role: "owner",
        invitationToken,
        baseUrl,
      });
    } catch (emailError) {
      console.error("Error sending invitation email:", emailError);
      // Continue - invitation is created, email may have failed
    }
 
    return NextResponse.json({
      success: true,
      invitation: {
        id: invitation?.id,
        email,
        role: "owner",
        status: "pending",
        expiresAt: expiresAt.toISOString(),
      },
    });
  } catch (error) {
    console.error("Error inviting owner:", error);
    return NextResponse.json(
      { error: "Failed to send invitation" },
      { status: 500 }
    );
  }
}