async function handleAuthenticate()

in app/routes/api.auth.tsx [46:157]


async function handleAuthenticate(
  credentials: AuthRequest["credentials"],
  request: Request
) {
  if (!credentials) {
    return json({ error: "No credentials provided" }, { status: 400 });
  }

  try {
    // Validate credentials format
    if (!validateCredentials(credentials)) {
      return json({ error: "Invalid credentials format" }, { status: 400 });
    }

    // Test credentials with API calls
    const testResult = await testCredentials(credentials);
    if (!testResult.isValid) {
      return json({ error: "Invalid API credentials" }, { status: 401 });
    }

    // Create cookie data
    const expiresAt = new Date();
    expiresAt.setTime(expiresAt.getTime() + COOKIE_MAX_AGE * 1000);

    const cookieData = {
      hasOpenAI: false, // OpenAI is now handled as a regular secret, not in auth
      hasHuggingFace: true,
      expiresAt: expiresAt.toISOString(),
      hfUserInfo: testResult.hfUserInfo
        ? btoa(JSON.stringify(testResult.hfUserInfo))
        : null,
      // Store encrypted HuggingFace token only
      enc: btoa(
        JSON.stringify({
          hf: credentials.huggingfaceToken || "",
        })
      ),
    };

    // Create cookie value
    const cookieValue = btoa(JSON.stringify(cookieData));

    // Set cookie with proper headers
    const headers = new Headers();

    // Determine if we should use Secure flag
    const url = new URL(request.url);
    const isSecure = url.protocol === "https:";

    // const cookieOptions = [
    //   `${config.COOKIE_NAME}=${cookieValue}`,
    //   `Max-Age=${COOKIE_MAX_AGE}`,
    //   "Path=/",
    //   // "SameSite=None",
    //   // "HttpOnly=false", // Need to access from client-side
    // ];
    // // const cookieOptions = [
    // //   `${config.COOKIE_NAME}=${cookieValue}`,
    // //   `Max-Age=${COOKIE_MAX_AGE}`,
    // //   "Path=/",
    // //   "SameSite=Lax",
    // //   "HttpOnly=false", // Need to access from client-side
    // // ];

    // if (isSecure) {
    //   cookieOptions.push("Secure");
    // }

    const cookieOptions = [
      `${serverConfig.COOKIE_NAME}=${cookieValue}`,
      `Max-Age=${COOKIE_MAX_AGE}`,
      "Path=/",
      // "SameSite=Lax", // Lax is more compatible than None
      "SameSite=None", // Lax is more compatible than None
      // Don't set HttpOnly to allow client-side access
      "Secure", // Only set Secure in HTTPS environments
      "HttpOnly=true", // Allow client-side access
    ];

    // Only add Secure in production HTTPS environments
    if (isSecure) {
      cookieOptions.push("Secure");
    }

    // // For HTTPS environments
    // if (isSecure) {
    //   cookieOptions.push("Secure");
    //   cookieOptions.push("SameSite=None"); // When Secure is used, SameSite=None allows cross-origin requests
    // } else {
    //   cookieOptions.push("SameSite=Lax"); // For non-HTTPS environments
    // }

    headers.set("Set-Cookie", cookieOptions.join("; "));

    return json(
      {
        success: true,
        authStatus: {
          isAuthenticated: true,
          hasOpenAI: false, // OpenAI is now a regular secret
          hasHuggingFace: true,
          expiresAt,
          hfUserInfo: testResult.hfUserInfo,
        },
      },
      { headers }
    );
  } catch (error) {
    console.error("Authentication failed:", error);
    return json({ error: "Authentication failed" }, { status: 500 });
  }
}