mirror of
https://git.imnavajas.es/jjimenez/erp-imprimelibros.git
synced 2026-01-13 08:58:48 +00:00
guardando presupuestos anonimos
This commit is contained in:
@ -3,41 +3,45 @@ package com.imprimelibros.erp.config;
|
||||
|
||||
import java.util.Optional;
|
||||
|
||||
import jakarta.persistence.EntityManager;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.data.domain.AuditorAware;
|
||||
import org.springframework.data.jpa.repository.config.EnableJpaAuditing;
|
||||
import org.springframework.security.core.context.SecurityContextHolder;
|
||||
import org.springframework.security.core.userdetails.UserDetails;
|
||||
|
||||
import com.imprimelibros.erp.users.User;
|
||||
import com.imprimelibros.erp.users.UserDao;
|
||||
import com.imprimelibros.erp.users.UserDetailsImpl; // tu implementación
|
||||
|
||||
@Configuration
|
||||
@EnableJpaAuditing(auditorAwareRef = "auditorAware")
|
||||
public class JpaAuditConfig {
|
||||
|
||||
@Bean
|
||||
public AuditorAware<User> auditorAware(UserDao userDao) {
|
||||
public AuditorAware<User> auditorAware(EntityManager em) {
|
||||
return () -> {
|
||||
var auth = SecurityContextHolder.getContext().getAuthentication();
|
||||
if (auth == null || !auth.isAuthenticated())
|
||||
return Optional.empty();
|
||||
var ctx = SecurityContextHolder.getContext();
|
||||
if (ctx == null) return Optional.empty();
|
||||
|
||||
var auth = ctx.getAuthentication();
|
||||
if (auth == null || !auth.isAuthenticated()) return Optional.empty();
|
||||
|
||||
Object principal = auth.getPrincipal();
|
||||
Long userId = null;
|
||||
|
||||
if (principal instanceof User u)
|
||||
return Optional.of(u);
|
||||
|
||||
if (principal instanceof UserDetails ud) {
|
||||
return userDao.findByUserNameIgnoreCase(ud.getUsername());
|
||||
// Tu UserDetailsImpl ya tiene el id
|
||||
if (principal instanceof UserDetailsImpl udi) {
|
||||
userId = udi.getId();
|
||||
}
|
||||
|
||||
if (principal instanceof String username && !"anonymousUser".equals(username)) {
|
||||
return userDao.findByUserNameIgnoreCase(username);
|
||||
// Si a veces pones el propio User como principal:
|
||||
else if (principal instanceof User u && u.getId() != null) {
|
||||
userId = u.getId();
|
||||
}
|
||||
// ⚠️ NO hagas consultas aquí (nada de userDao.findBy...).
|
||||
if (userId == null) return Optional.empty();
|
||||
|
||||
return Optional.empty();
|
||||
// Devuelve una referencia gestionada (NO hace SELECT ni fuerza flush)
|
||||
return Optional.of(em.getReference(User.class, userId));
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user