Changes
This commit is contained in:
64
src/routes/tenant.ts
Normal file
64
src/routes/tenant.ts
Normal file
@@ -0,0 +1,64 @@
|
||||
import { FastifyInstance } from "fastify";
|
||||
import jwt from "jsonwebtoken";
|
||||
|
||||
export default async function routes(server: FastifyInstance) {
|
||||
server.get("/tenant", async (req) => {
|
||||
if(req.tenant) {
|
||||
return {
|
||||
message: `Hallo vom Tenant ${req.tenant?.name}`,
|
||||
tenant_id: req.tenant?.id,
|
||||
};
|
||||
} else {
|
||||
return {
|
||||
message: `Server ist in MultiTenant Mode. Sie bekommen alles für Sie verfügbare`,
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
|
||||
});
|
||||
|
||||
server.post("/tenant/switch", async (req, reply) => {
|
||||
if (!req.user) {
|
||||
return reply.code(401).send({ error: "Unauthorized" });
|
||||
}
|
||||
|
||||
const body = req.body as { tenant_id: string };
|
||||
console.log(body);
|
||||
|
||||
// prüfen ob user im Tenant Mitglied ist
|
||||
const { data: tenantUser, error } = await server.supabase
|
||||
.from("auth_tenant_users")
|
||||
.select("*")
|
||||
.eq("user_id", req.user.user_id)
|
||||
.eq("tenant_id", body.tenant_id)
|
||||
.single();
|
||||
|
||||
if (error || !tenantUser) {
|
||||
return reply.code(403).send({ error: "Not a member of this tenant" });
|
||||
}
|
||||
|
||||
// neues JWT mit tenant_id ausstellen
|
||||
const token = jwt.sign(
|
||||
{
|
||||
user_id: req.user.user_id,
|
||||
email: req.user.email,
|
||||
tenant_id: body.tenant_id,
|
||||
},
|
||||
process.env.JWT_SECRET!,
|
||||
{ expiresIn: "1h" }
|
||||
);
|
||||
|
||||
reply.setCookie("token", token, {
|
||||
path: "/",
|
||||
httpOnly: true,
|
||||
sameSite: process.env.NODE_ENV === "production" ? "none" : "lax",
|
||||
secure: process.env.NODE_ENV === "production", // lokal: false, prod: true
|
||||
maxAge: 60 * 60 * 3, // 3 Stunden
|
||||
})
|
||||
|
||||
return { token };
|
||||
});
|
||||
|
||||
|
||||
}
|
||||
Reference in New Issue
Block a user