121 lines
3.5 KiB
TypeScript
121 lines
3.5 KiB
TypeScript
/**
|
|
* Netlify Function: Create User
|
|
* POST /create-user - Cria novo usuário no sistema
|
|
* Requer permissão de admin, gestor ou secretaria
|
|
* Envia magic link automaticamente para o email
|
|
*/
|
|
|
|
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",
|
|
"Access-Control-Allow-Methods": "POST, OPTIONS",
|
|
};
|
|
|
|
if (event.httpMethod === "OPTIONS") {
|
|
return {
|
|
statusCode: 200,
|
|
headers,
|
|
body: "",
|
|
};
|
|
}
|
|
|
|
try {
|
|
const authHeader =
|
|
event.headers.authorization || event.headers.Authorization;
|
|
|
|
// create-user pode ser chamado SEM autenticação (para auto-registro)
|
|
// Se houver token, será usado; se não houver, usa apenas anon key
|
|
|
|
if (event.httpMethod === "POST") {
|
|
const body = JSON.parse(event.body || "{}");
|
|
|
|
console.log(
|
|
"[create-user] Recebido body:",
|
|
JSON.stringify(body, null, 2)
|
|
);
|
|
console.log("[create-user] Auth header presente?", !!authHeader);
|
|
|
|
// Validação dos campos obrigatórios
|
|
if (!body.email || !body.full_name) {
|
|
return {
|
|
statusCode: 400,
|
|
headers,
|
|
body: JSON.stringify({
|
|
error: "Campos obrigatórios: email, full_name",
|
|
}),
|
|
};
|
|
}
|
|
|
|
if (!body.role && (!body.roles || body.roles.length === 0)) {
|
|
return {
|
|
statusCode: 400,
|
|
headers,
|
|
body: JSON.stringify({
|
|
error: "É necessário fornecer role ou roles",
|
|
}),
|
|
};
|
|
}
|
|
|
|
// Chama a Edge Function do Supabase para criar usuário
|
|
const fetchHeaders: Record<string, string> = {
|
|
apikey: SUPABASE_ANON_KEY,
|
|
"Content-Type": "application/json",
|
|
// Se houver token de usuário autenticado, usa ele; senão usa anon key
|
|
Authorization: authHeader || `Bearer ${SUPABASE_ANON_KEY}`,
|
|
};
|
|
|
|
console.log("[create-user] Chamando Supabase com headers:", {
|
|
hasAuthHeader: !!authHeader,
|
|
hasApikey: !!fetchHeaders.apikey,
|
|
authType: authHeader ? "User Token" : "Anon Key",
|
|
});
|
|
|
|
const response = await fetch(`${SUPABASE_URL}/functions/v1/create-user`, {
|
|
method: "POST",
|
|
headers: fetchHeaders,
|
|
body: JSON.stringify(body),
|
|
});
|
|
|
|
const data = await response.json();
|
|
|
|
console.log("[create-user] Resposta do Supabase:", {
|
|
status: response.status,
|
|
data: JSON.stringify(data, null, 2),
|
|
});
|
|
|
|
return {
|
|
statusCode: response.status,
|
|
headers: {
|
|
...headers,
|
|
"Content-Type": "application/json",
|
|
},
|
|
body: JSON.stringify(data),
|
|
};
|
|
}
|
|
|
|
return {
|
|
statusCode: 405,
|
|
headers,
|
|
body: JSON.stringify({ error: "Method Not Allowed" }),
|
|
};
|
|
} catch (error) {
|
|
console.error("Erro na API de create user:", error);
|
|
|
|
return {
|
|
statusCode: 500,
|
|
headers,
|
|
body: JSON.stringify({
|
|
error: "Erro interno no servidor",
|
|
message: error instanceof Error ? error.message : "Erro desconhecido",
|
|
}),
|
|
};
|
|
}
|
|
};
|