package net.northking.cctp.common.jpa.interceptor;

import net.northking.cctp.common.persistence.rule.TenantRule;
import net.northking.cctp.common.security.authentication.NKSecurityContext;

/**
 * 租户JPA拦截器，实现租户之间的数据隔离
 *
 * @author xiusong.xie
 * @since 2.4
 */
public class TenantJpaInterceptor extends BasicJpaInterceptor
{

  public static final TenantJpaInterceptor Instance = new TenantJpaInterceptor();

  private TenantJpaInterceptor()
  {
  }

  /**
   * 租户之间数据隔离，用户只能操作所属租户下的数据
   *
   * @param entity 数据实体
   */
  @Override
  public void beforeInsert(Object entity)
  {
    if (entity instanceof TenantRule)
    {
      String tenantId = NKSecurityContext.getTenantId();
      ((TenantRule) entity).setTenantId(tenantId);
    }
  }

}
