All files / app/api/org/invite route.ts

86.56% Statements 58/67
93.33% Branches 28/30
50% Functions 2/4
86.36% Lines 57/66

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 180 181            1x 1x 1x 1x 1x 1x 1x   1x 1x 1x 1x 1x     1x   1x 9x 9x 9x   9x 1x     8x 8x 1x     7x 1x           6x     6x                 6x 1x     5x 5x 5x 5x 5x     5x 1x             4x 1x             3x 3x         3x 1x             2x 2x 1x             1x 1x     1x     1x       1x     1x                           1x                   1x 1x 1x   1x 1x                         1x                                    
/**
 * POST /api/org/invite
 * Send an invitation to join the organisation
 * @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 { listUsersByTenant } from "@/lib/cognito-admin";
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 { email, role } = body as { email: string; role: "admin" | "member" };
 
    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 });
    }
 
    if (!role || !["admin", "member"].includes(role)) {
      return NextResponse.json(
        { error: "Invalid role. Must be admin or member" },
        { status: 400 }
      );
    }
 
    const cookieStore = await cookies();
 
    // Get current user's session
    const session = await runWithAmplifyServerContext({
      nextServerContext: { cookies: async () => cookieStore },
      operation: async (context) => {
        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 currentUserType = idToken.payload["custom:user_type"] as string | undefined;
    const currentTenantId = idToken.payload["custom:tenant_id"] as string | undefined;
    const currentRole = idToken.payload["custom:role"] as string | undefined;
    const currentUserEmail = idToken.payload.email as string;
 
    // Only org users can access this
    if (currentUserType !== "org" || !currentTenantId) {
      return NextResponse.json(
        { error: "Only organisation users can invite" },
        { status: 403 }
      );
    }
 
    // Only owner or admin can invite
    if (currentRole !== "owner" && currentRole !== "admin") {
      return NextResponse.json(
        { error: "Only owner or admin can invite users" },
        { status: 403 }
      );
    }
 
    // Rate limiting: 10 invitations per hour per user (JCN-25)
    const rateLimitKey = `org-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 }
      );
    }
 
    // Check if user already exists in tenant
    const existingUsers = await listUsersByTenant(currentTenantId);
    if (existingUsers.some(u => u.email.toLowerCase() === email.toLowerCase())) {
      return NextResponse.json(
        { error: "User is already a member of this organisation" },
        { status: 400 }
      );
    }
 
    // 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 name for email
    const { data: tenant } = await client.models.Tenant.get(
      { id: currentTenantId },
      { authMode: "apiKey" }
    );
    const organisationName = tenant?.name || "Organisation";
 
    // Create invitation
    const { data: invitation, errors } = await client.models.TenantInvitation.create(
      {
        id: invitationToken,
        tenantId: currentTenantId,
        email: email.toLowerCase(),
        role,
        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 }
      );
    }
 
    // 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,
        inviterName: currentUserEmail,
        role,
        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,
        status: "pending",
        expiresAt: expiresAt.toISOString(),
      },
    });
  } catch (error) {
    console.error("Error creating invitation:", error);
    return NextResponse.json(
      { error: "Failed to create invitation" },
      { status: 500 }
    );
  }
}