2017-11-09 5 views
2

@Before 메서드를 실행하고 사용자 로그인에서 일부 ID로 모든 쿼리를 가로 채는 @Aspect 클래스가 있습니다. 하지만 문제는 사용자가 로그인 할 때마다 @Before 메소드의 ID가 모든 기록 된 사용자에 대해 변경되므로 현재 사용자를 변경하기 만하면됩니다.봄 @ 모든 사용자 로그인을 변경하기 전에

간단한 프로세스 : 사용자가 로그인 할 때 @Aspect 클래스는 모든 ID를 가로 채기 위해 ID를 얻습니다. 그러나이 ID는 로그인 한 모든 사용자에 대해 변경됩니다. 어쩌면 세션에 문제가있어 야할지 모르겠다.

가로 세로 클래스 :

@Aspect 
@Component 
@Transactional(propagation = Propagation.REQUIRED) 
public class TenancyAspect { 

    @Autowired 
    private EntityManager manager; 

    @Autowired 
    private AppUserDetailsService appUserDetailsService; 

    @Before("execution(* com.tc.tcqualidade.repository.*.*(..)) " 
      +"&& !execution(* com.tc.tcqualidade.repository.UsuarioRepository.porEmailEStatus(..))" 
      +"&& !execution(* com.tc.tcqualidade.repository.UsuarioRepository.permissoes(..))") 
    public void definirTenant() { 
     String tenantid = appUserDetailsService.getTenantId(); 

     if (tenantid != null) { 
      manager.unwrap(Session.class).enableFilter("tenant").setParameter("id", tenantid); 
     } 

    } 

} 

로그인 클래스 : @Autowired를 사용할 때이 같은 동작을 본 적이

@Service 
public class AppUserDetailsService implements UserDetailsService { 

    private String tenantId = null; 

    @Autowired 
    private UsuarioRepository usuarioRepository; 

    @Override 
    public UserDetails loadUserByUsername(String email) throws UsernameNotFoundException { 
     Optional<Usuario> usuarioOptional = usuarioRepository.porEmailEStatus(email); 
     Usuario usuario = usuarioOptional.orElseThrow(() -> new UsernameNotFoundException("Usuário e/ou senha incorretos")); 

     tenantId = usuario.getEmpresa().getId().toString(); 

     return new UsuarioSistema(usuario, getPermissoes(usuario)); 
    } 

    private Collection<? extends GrantedAuthority> getPermissoes(Usuario usuario) { 
     Set<SimpleGrantedAuthority> authorities = new HashSet<>(); 

     List<String> permissoes = usuarioRepository.permissoes(usuario); 
     permissoes.forEach(p -> authorities.add(new SimpleGrantedAuthority(p.toUpperCase()))); 

     return authorities; 
    } 

    public String getTenantId(){ 
     return tenantId; 
    } 

} 
+1

"사용자가 로그인 할 때마다"어떻게해야합니까? 내 말은 당신이 아마 당신의 질문에 당신의 전체 과정에 대한 세부 사항을 추가해야한다는 것을 의미합니다. –

+0

안녕하세요, 질문을 업데이트했습니다. –

답변

1

. 당신이 말하지 않는 한 Spring은 각 접근에 대해 새로운 인스턴스를 생성하지 않으므로 모든 접근에서 객체가 공유된다. 로그인 한 사용자가 로그인 한 모든 사용자가 해당 사용자의 ID로 변경되도록합니다. 서비스 세션 중 하나를 범위로 지정해야 할 수 있습니다.

@Service 
@Scope(value="session", proxyMode= ScopedProxyMode.TARGET_CLASS) 
+0

안녕하세요! Aspect 클래스에서 이것을 시도했지만, 작동하지 않았다. 이제는 Service 클래스에서 작동한다. 고마워, 친구! –