gpt4 book ai didi

spring - 如何使 AuditorAware 与 Spring Data Mongo Reactive 一起工作

转载 作者:行者123 更新时间:2023-12-04 14:00:40 27 4
gpt4 key购买 nike

Spring Security 5 提供了一个 ReactiveSecurityContextHolder to fetch the SecurityContext from a Reactive context ,但是当我想实现 AuditorAware并自动获得试镜工作,但它不起作用。 目前我找不到 Reactive AuditorAware 的变体 .

@Bean
public AuditorAware<Username> auditor() {
return () -> ReactiveSecurityContextHolder.getContext()
.map(SecurityContext::getAuthentication)
.log()
.filter(a -> a != null && a.isAuthenticated())
.map(Authentication::getPrincipal)
.cast(UserDetails.class)
.map(auth -> new Username(auth.getName()))
.switchIfEmpty(Mono.empty())
.blockOptional();
}
我已添加 @EnableMongoAuduting在我的 Boot 上 Application类(class)。
在 Mongo 文档类上。我添加了与试听相关的注释。
@CreatedDate
private LocalDateTime createdDate;

@CreatedBy
private Username author;
当我添加帖子时, createdDate已填充,但作者为空。
{"id":"5a49ccdb9222971f40a4ada1","title":"my first post","content":"content of my first post","createdDate":"2018-01-01T13:53:31.234","author":null}
完整代码为 here ,基于 Spring Boot 2.0.0.M7。
更新: Spring Boot 2.4.0-M2/Spring Data Common 2.4.0-M2/Spring Data Mongo 3.1.0-M2 包含一个 ReactiveAuditorAware , 检查 this new sample , 备注 :使用 @EnableReactiveMongoAuditing激活它。

最佳答案

我正在发布另一个解决方案,该解决方案使用输入 id 来支持更新操作:

@Component
@RequiredArgsConstructor
public class AuditCallback implements ReactiveBeforeConvertCallback<AuditableEntity> {

private final ReactiveMongoTemplate mongoTemplate;

private Mono<?> exists(Object id, Class<?> entityClass) {
if (id == null) {
return Mono.empty();
}
return mongoTemplate.findById(id, entityClass);
}

@Override
public Publisher<AuditableEntity> onBeforeConvert(AuditableEntity entity, String collection) {
var securityContext = ReactiveSecurityContextHolder.getContext();
return securityContext
.zipWith(exists(entity.getId(), entity.getClass()))
.map(tuple2 -> {
var auditableEntity = (AuditableEntity) tuple2.getT2();
auditableEntity.setLastModifiedBy(tuple2.getT1().getAuthentication().getName());
auditableEntity.setLastModifiedDate(Instant.now());
return auditableEntity;
})
.switchIfEmpty(Mono.zip(securityContext, Mono.just(entity))
.map(tuple2 -> {
var auditableEntity = (AuditableEntity) tuple2.getT2();
String principal = tuple2.getT1().getAuthentication().getName();
Instant now = Instant.now();
auditableEntity.setLastModifiedBy(principal);
auditableEntity.setCreatedBy(principal);
auditableEntity.setLastModifiedDate(now);
auditableEntity.setCreatedDate(now);
return auditableEntity;
}));
}
}

关于spring - 如何使 AuditorAware 与 Spring Data Mongo Reactive 一起工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48047480/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com