224 lines
6.0 KiB
TypeScript
224 lines
6.0 KiB
TypeScript
/**
|
|
* Netlify Function: Create User With Password
|
|
* POST /create-user-with-password - Cria usuário com senha
|
|
* Usa Edge Function do Supabase (não Admin API)
|
|
* Requer permissão de admin, gestor ou secretaria
|
|
*/
|
|
|
|
import type { Handler, HandlerEvent } from "@netlify/functions";
|
|
|
|
const SUPABASE_URL = "https://yuanqfswhberkoevtmfr.supabase.co";
|
|
const SUPABASE_ANON_KEY =
|
|
"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6Inl1YW5xZnN3aGJlcmtvZXZ0bWZyIiwicm9sZSI6ImFub24iLCJpYXQiOjE3NTQ5NTQzNjksImV4cCI6MjA3MDUzMDM2OX0.g8Fm4XAvtX46zifBZnYVH4tVuQkqUH6Ia9CXQj4DztQ";
|
|
|
|
export const handler: Handler = async (event: HandlerEvent) => {
|
|
const headers = {
|
|
"Access-Control-Allow-Origin": "*",
|
|
"Access-Control-Allow-Headers": "Content-Type, Authorization, apikey",
|
|
"Access-Control-Allow-Methods": "POST, OPTIONS",
|
|
};
|
|
|
|
if (event.httpMethod === "OPTIONS") {
|
|
return {
|
|
statusCode: 200,
|
|
headers,
|
|
body: "",
|
|
};
|
|
}
|
|
|
|
if (event.httpMethod !== "POST") {
|
|
return {
|
|
statusCode: 405,
|
|
headers,
|
|
body: JSON.stringify({ error: "Method Not Allowed" }),
|
|
};
|
|
}
|
|
|
|
try {
|
|
const authHeader =
|
|
event.headers.authorization || event.headers.Authorization;
|
|
|
|
if (!authHeader) {
|
|
console.error("[create-user-with-password] Token não fornecido!");
|
|
return {
|
|
statusCode: 401,
|
|
headers,
|
|
body: JSON.stringify({
|
|
error: "Token de autenticação é obrigatório",
|
|
}),
|
|
};
|
|
}
|
|
|
|
const body = JSON.parse(event.body || "{}");
|
|
|
|
console.log(
|
|
"[create-user-with-password] Recebido:",
|
|
JSON.stringify({ ...body, password: "***" }, null, 2)
|
|
);
|
|
|
|
// Validações
|
|
if (!body.email || !body.password || !body.full_name) {
|
|
return {
|
|
statusCode: 400,
|
|
headers,
|
|
body: JSON.stringify({
|
|
error: "Campos obrigatórios: email, password, full_name",
|
|
}),
|
|
};
|
|
}
|
|
|
|
if (body.password.length < 6) {
|
|
return {
|
|
statusCode: 400,
|
|
headers,
|
|
body: JSON.stringify({
|
|
error: "Senha deve ter no mínimo 6 caracteres",
|
|
}),
|
|
};
|
|
}
|
|
|
|
// 1. Criar usuário via Edge Function do Supabase
|
|
console.log(
|
|
"[create-user-with-password] Chamando Edge Function do Supabase..."
|
|
);
|
|
console.log(
|
|
"[create-user-with-password] URL:",
|
|
`${SUPABASE_URL}/functions/v1/create-user`
|
|
);
|
|
console.log("[create-user-with-password] Payload:", {
|
|
email: body.email,
|
|
has_password: !!body.password,
|
|
full_name: body.full_name,
|
|
});
|
|
|
|
const createUserResponse = await fetch(
|
|
`${SUPABASE_URL}/functions/v1/create-user`,
|
|
{
|
|
method: "POST",
|
|
headers: {
|
|
apikey: SUPABASE_ANON_KEY,
|
|
Authorization: authHeader,
|
|
"Content-Type": "application/json",
|
|
},
|
|
body: JSON.stringify({
|
|
email: body.email,
|
|
password: body.password,
|
|
full_name: body.full_name,
|
|
phone: body.phone || null,
|
|
role: body.role || "user",
|
|
}),
|
|
}
|
|
);
|
|
|
|
console.log(
|
|
"[create-user-with-password] Status da resposta:",
|
|
createUserResponse.status
|
|
);
|
|
console.log(
|
|
"[create-user-with-password] Status text:",
|
|
createUserResponse.statusText
|
|
);
|
|
|
|
// Sempre tenta ler a resposta como JSON
|
|
let responseData;
|
|
try {
|
|
responseData = await createUserResponse.json();
|
|
console.log(
|
|
"[create-user-with-password] Resposta JSON:",
|
|
JSON.stringify(responseData, null, 2)
|
|
);
|
|
} catch (error) {
|
|
const responseText = await createUserResponse.text();
|
|
console.error(
|
|
"[create-user-with-password] Resposta não é JSON:",
|
|
responseText
|
|
);
|
|
console.error("[create-user-with-password] Erro ao parsear JSON:", error);
|
|
return {
|
|
statusCode: 500,
|
|
headers: {
|
|
...headers,
|
|
"Content-Type": "application/json",
|
|
},
|
|
body: JSON.stringify({
|
|
error: "Erro ao processar resposta do Supabase",
|
|
details: responseText,
|
|
}),
|
|
};
|
|
}
|
|
|
|
if (!createUserResponse.ok) {
|
|
console.error(
|
|
"[create-user-with-password] Erro ao criar usuário:",
|
|
JSON.stringify(responseData, null, 2)
|
|
);
|
|
return {
|
|
statusCode: createUserResponse.status,
|
|
headers: {
|
|
...headers,
|
|
"Content-Type": "application/json",
|
|
},
|
|
body: JSON.stringify({
|
|
error:
|
|
responseData.msg || responseData.message || "Erro ao criar usuário",
|
|
details: responseData,
|
|
}),
|
|
};
|
|
}
|
|
|
|
// Verificar se a Edge Function retornou sucesso
|
|
if (!responseData.success) {
|
|
console.error(
|
|
"[create-user-with-password] Edge Function retornou erro:",
|
|
JSON.stringify(responseData, null, 2)
|
|
);
|
|
return {
|
|
statusCode: 400,
|
|
headers: {
|
|
...headers,
|
|
"Content-Type": "application/json",
|
|
},
|
|
body: JSON.stringify({
|
|
error: responseData.error || "Erro ao criar usuário",
|
|
details: responseData,
|
|
}),
|
|
};
|
|
}
|
|
|
|
const userData = responseData.user;
|
|
console.log(
|
|
"[create-user-with-password] Usuário criado com sucesso:",
|
|
userData.id
|
|
);
|
|
console.log(
|
|
"[create-user-with-password] Resposta completa:",
|
|
JSON.stringify(responseData, null, 2)
|
|
);
|
|
|
|
// A Edge Function já cria o perfil e atribui a role automaticamente
|
|
// Retornar sucesso
|
|
return {
|
|
statusCode: 201,
|
|
headers: {
|
|
...headers,
|
|
"Content-Type": "application/json",
|
|
},
|
|
body: JSON.stringify({
|
|
success: true,
|
|
user: userData,
|
|
message: responseData.message || "Usuário criado com sucesso",
|
|
}),
|
|
};
|
|
} catch (error) {
|
|
console.error("[create-user-with-password] Erro:", error);
|
|
return {
|
|
statusCode: 500,
|
|
headers,
|
|
body: JSON.stringify({
|
|
error: "Erro interno no servidor",
|
|
message: error instanceof Error ? error.message : "Erro desconhecido",
|
|
}),
|
|
};
|
|
}
|
|
};
|