Skip to content

Instantly share code, notes, and snippets.

View onurcill's full-sized avatar

Onur Cil onurcill

  • DefineX-ConsultingITechnologyILabs
  • İzmir
View GitHub Profile
@Configuration
@PropertySource({"classpath:dfx-library-multitenancy.properties"})
@ConfigurationProperties(
prefix = "dfx.online.data.repository.scan"
)
public class MultitenancyProperties {
private String path;
public String getPath() {
return path;
public class MultiTenancyRepository<T, I> extends SimpleJpaRepository<T, I> {
private final JpaEntityInformation<T, I> entityInformation;
private final EntityManager entityManager;
public MultiTenancyRepository(
final JpaEntityInformation<T, I> entityInformation, final EntityManager entityManager) {
super(entityInformation, entityManager);
this.entityInformation = entityInformation;
this.entityManager = entityManager;
@Aspect
@Component
public class TenantServiceAspect {
@PersistenceContext public EntityManager entityManager;
@Pointcut("execution(public * org.springframework.data.repository.Repository+.*(..))")
void isRepository() {
/* aspect */
}
@RequiredArgsConstructor
@Getter
@Setter
@MappedSuperclass()
@SuperBuilder
@FilterDef(
name = TenantEntity.TENANT_FILTER_NAME,
parameters = @ParamDef(name = TenantEntity.TENANT_FILTER_ARGUMENT_NAME, type = TenantEntity.TENANT_FILTER_ARGUMENT_TYPE),
defaultCondition =
TenantEntity.TENANT_ID_PROPERTY_NAME + "= :" + TenantEntity.TENANT_FILTER_ARGUMENT_NAME)
@Component
@AllArgsConstructor
public class HibernateInterceptorConfiguration implements HibernatePropertiesCustomizer {
private final EmptyInterceptor tenantInterceptor;
@Override
public void customize(final Map<String, Object> hibernateProperties) {
hibernateProperties.put("hibernate.session_factory.interceptor", this.tenantInterceptor);
}
@Configuration
public class HibernateMultiTenancyInterceptorBean {
@Bean
public EmptyInterceptor hibernateTenantInterceptor() {
return new com.definex.dfx.multitenancy.TenantInterceptor();
}
}
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public final class TenantAssistance {
private static final String CLAIM_ORGANIZATION = "organization";
public static String resolveCurrentTenantIdentifier() {
return Optional.ofNullable(SecurityContextHolder.getContext().getAuthentication())
.filter(authentication -> authentication instanceof JwtAuthenticationToken)
.map(authentication -> (JwtAuthenticationToken) authentication)
.map(JwtAuthenticationToken::getPrincipal)
.filter(jwt -> jwt instanceof Jwt)
public final class TenantInterceptor extends EmptyInterceptor {
@Override
public boolean onSave(
final Object entity,
final Serializable id,
final Object[] state,
final String[] propertyNames,
final Type[] types) {
return this.addTenantIdIfObjectIsTenantEntity(entity, state, propertyNames);