Files
FEDEO/src/routes/admin.ts
2025-08-31 18:29:29 +02:00

94 lines
2.6 KiB
TypeScript

import { FastifyInstance } from "fastify";
export default async function adminRoutes(server: FastifyInstance) {
server.post("/admin/add-user-to-tenant", async (req, reply) => {
const body = req.body as {
user_id: string;
tenant_id: string;
role?: string;
mode?: "single" | "multi";
};
if (!body.user_id || !body.tenant_id) {
return reply.code(400).send({ error: "user_id and tenant_id required" });
}
// Default: "multi"
const mode = body.mode ?? "multi";
if (mode === "single") {
// Erst alle alten Verknüpfungen löschen
await server.supabase
.from("auth_tenant_users")
.delete()
.eq("user_id", body.user_id);
}
const { error } = await server.supabase
.from("auth_tenant_users")
.insert({
tenant_id: body.tenant_id,
user_id: body.user_id,
role: body.role ?? "member",
});
if (error) {
return reply.code(400).send({ error: error.message });
}
// Neuen Eintrag setzen
return { success: true, mode };
});
/**
* Alle Tenants eines Users abfragen
*/
server.get("/admin/user-tenants/:user_id", async (req, reply) => {
const { user_id } = req.params as { user_id: string };
if (!user_id) {
return reply.code(400).send({ error: "user_id required" });
}
const {data:user, error: userError} = await server.supabase.from("auth_users").select("*,tenants(*)").eq("id", user_id).single();
console.log(userError)
console.log(user)
if(!user) {
return reply.code(400).send({ error: "faulty user_id presented" });
} else {
return { user_id, tenants: user.tenants };
}
});
/**
* Alle User eines Tenants abfragen
* TODO: Aktuell nur Multi Tenant
*/
/*server.get("/admin/tenant-users/:tenant_id", async (req, reply) => {
const { tenant_id } = req.params as { tenant_id: string };
if (!tenant_id) {
return reply.code(400).send({ error: "tenant_id required" });
}
const { data, error } = await server.supabase
.from("auth_tenant_users")
.select(`
user_id,
role,
users ( id, email, created_at )
`)
.eq("tenant_id", tenant_id);
if (error) {
return reply.code(400).send({ error: error.message });
}
return { tenant_id, users: data };
});*/
}