argos/notification-service/notification/src/main/java/gr/cite/notification/data/tenant/TenantFilterAspect.java

45 lines
1.5 KiB
Java
Raw Normal View History

2023-12-08 10:25:07 +01:00
package gr.cite.notification.data.tenant;
import gr.cite.notification.common.scope.tenant.TenantScope;
2024-04-04 15:39:40 +02:00
import jakarta.persistence.EntityManager;
2023-12-08 10:25:07 +01:00
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.hibernate.Session;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import javax.management.InvalidApplicationException;
@Aspect
@Component
public class TenantFilterAspect {
private final TenantScope tenantScope;
@Autowired
public TenantFilterAspect(
2024-04-04 15:39:40 +02:00
TenantScope tenantScope
2023-12-08 10:25:07 +01:00
) {
this.tenantScope = tenantScope;
}
@AfterReturning(
2024-04-04 15:39:40 +02:00
pointcut = "bean(entityManagerFactory) && execution(* createEntityManager(..))",
returning = "retVal")
2023-12-08 10:25:07 +01:00
public void getSessionAfter(JoinPoint joinPoint, Object retVal) throws InvalidApplicationException {
2024-04-04 15:39:40 +02:00
if (retVal instanceof EntityManager && tenantScope.isSet()) {
2023-12-08 10:25:07 +01:00
Session session = ((EntityManager) retVal).unwrap(Session.class);
2024-04-04 15:39:40 +02:00
if(!tenantScope.isDefaultTenant()) {
session
.enableFilter(TenantScopedBaseEntity.TENANT_FILTER)
.setParameter(TenantScopedBaseEntity.TENANT_FILTER_TENANT_PARAM, tenantScope.getTenant().toString());
} else {
session
.enableFilter(TenantScopedBaseEntity.DEFAULT_TENANT_FILTER);
}
2023-12-08 10:25:07 +01:00
}
}
}