Skip to content

Commit

Permalink
♻️ refactor: 优化了安全管理器和各核心服务的代码结构和逻辑处理方式
Browse files Browse the repository at this point in the history
  • Loading branch information
vnobo committed Jun 3, 2024
1 parent 763100d commit 3dd7a07
Show file tree
Hide file tree
Showing 13 changed files with 25 additions and 49 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -160,7 +160,8 @@ private Mono<String> processRequestBody(ServerWebExchange exchange, ServerHttpRe
HandlerStrategies.withDefaults().messageReaders());
return serverRequest.bodyToMono(String.class).doOnNext((objectValue) -> {
Object previousCachedBody = exchange.getAttributes().put(CACHED_REQUEST_BODY_ATTR, objectValue);
log.debug("{}Logger filter [processRequestBody] body: {}", exchange.getLogPrefix(), previousCachedBody);
log.debug("{}Logger filter chain [processRequestBody] body: {}",
exchange.getLogPrefix(), previousCachedBody);
});
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -88,24 +88,21 @@ public Mono<User> loadByOauth2(String bindType, String openid) {
.bind("bindType", bindType).bind("openid", openid)
.map((row, metadata) -> this.r2dbcConverter.read(User.class, row, metadata))
.all();
return queryWithCache(bindType + openid, userMono).singleOrEmpty();
return this.queryWithCache(bindType + openid, userMono).singleOrEmpty();
}

public Mono<User> loadByUsername(String username) {
Query query = Query.query(Criteria.where("username").is(username).ignoreCase(true));
var userMono = this.entityTemplate.select(query, User.class);
return queryWithCache(username, userMono).singleOrEmpty();
return this.queryWithCache(username, userMono).singleOrEmpty();
}

@Override
public Mono<UserDetails> findByUsername(String username) {

var userMono = this.loadByUsername(username)
.zipWhen(user -> this.authorities(user.getCode()));

var userMono = this.loadByUsername(username).zipWhen(user -> this.authorities(user.getCode()));
var userDetailsMono = userMono
.flatMap(tuple2 -> buildUserDetails(tuple2.getT1(), new HashSet<>(tuple2.getT2())));

return userDetailsMono.cast(UserDetails.class)
.onErrorResume(throwable -> Mono.error(new AuthenticationServiceException(
throwable.getLocalizedMessage(), throwable)))
Expand All @@ -117,14 +114,14 @@ public Mono<UserDetails> findByUsername(String username) {
private Mono<SecurityDetails> buildUserDetails(User user, Set<GrantedAuthority> authorities) {
SecurityDetails userDetails = SecurityDetails.of(user.getCode(), user.getUsername(), user.getName(),
user.getPassword(), user.getDisabled(), user.getAccountExpired(),
user.getAccountLocked(), user.getCredentialsExpired(), authorities, Map.of("username", user.getUsername()),
"username");
var tuple2Mono = Mono.zip(this.loadGroups(user.getCode()), this.loadTenants(user.getCode()));
return tuple2Mono.flatMap(tuple2 -> {
user.getAccountLocked(), user.getCredentialsExpired(), authorities,
Map.of("username", user.getUsername()), "username");
var tuple2Mono = Mono.zipDelayError(this.loadGroups(user.getCode()), this.loadTenants(user.getCode()));
return tuple2Mono.mapNotNull(tuple2 -> {
userDetails.setGroups(new HashSet<>(tuple2.getT1()));
userDetails.setTenants(new HashSet<>(tuple2.getT2()));
return Mono.defer(() -> Mono.just(userDetails));
}).switchIfEmpty(Mono.defer(() -> Mono.just(userDetails)));
return userDetails;
}).then(Mono.defer(() -> Mono.just(userDetails)));
}

private Mono<List<GroupMemberResponse>> loadGroups(String userCode) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -33,17 +33,9 @@ public Mono<Page<Group>> page(GroupRequest request, Pageable pageable) {
this.groupsService.page(request.securityCode(securityDetails.getTenantCode()), pageable));
}

@PostMapping("add")
@PostMapping("save")
@PreAuthorize("hasRole(@contextUtils.RULE_ADMINISTRATORS)")
public Mono<Group> add(@Valid @RequestBody GroupRequest request) {
Assert.isNull(request.getId(), "When adding a new Group, the ID must be null");
return this.groupsService.operate(request);
}

@PutMapping("modify")
@PreAuthorize("hasRole(@contextUtils.RULE_ADMINISTRATORS)")
public Mono<Group> modify(@Valid @RequestBody GroupRequest request) {
Assert.notNull(request.getId(), "When modifying an existing Group, the ID must not be null");
return this.groupsService.operate(request);
}

Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
package com.platform.boot.security.core.group.authority;

import com.platform.boot.commons.utils.BeanUtils;
import jakarta.validation.constraints.NotNull;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.ToString;
Expand All @@ -18,7 +17,6 @@
@ToString(callSuper = true)
public class GroupAuthorityRequest extends GroupAuthority implements Serializable {

@NotNull(message = "权限[authorities]不能为空!")
private Set<String> authorities;

public GroupAuthority toGroupAuthority() {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,6 @@
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;

import java.io.Serializable;
import java.util.List;
import java.util.Map;
import java.util.Set;
Expand All @@ -22,9 +21,10 @@
@Data
@EqualsAndHashCode(callSuper = true)
@ToString(callSuper = true)
public class GroupMemberRequest extends GroupMember implements Serializable {
public class GroupMemberRequest extends GroupMember {

private Set<String> users;

private String username;

public GroupMember toGroupMember() {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -70,12 +70,6 @@ public Mono<GroupMember> save(GroupMember groupMember) {
}
}

/**
* Deletes a tenant.
*
* @param request the tenant request
* @return a Mono of void
*/
public Mono<Void> delete(GroupMemberRequest request) {
return this.memberRepository.delete(request.toGroupMember()).doAfterTerminate(() -> this.cache.clear());
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@
import lombok.EqualsAndHashCode;
import lombok.ToString;

import java.io.Serializable;
import java.util.List;
import java.util.Map;

Expand All @@ -17,7 +16,7 @@
@Data
@EqualsAndHashCode(callSuper = true)
@ToString(callSuper = true)
public class TenantRequest extends Tenant implements Serializable {
public class TenantRequest extends Tenant {

private Map<String, Object> query;

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -33,17 +33,9 @@ public Mono<Page<Tenant>> page(TenantRequest request, Pageable pageable) {
return this.tenantsService.page(request, pageable);
}

@PostMapping("add")
@PostMapping("save")
@PreAuthorize("hasRole(@contextUtils.RULE_ADMINISTRATORS)")
public Mono<Tenant> add(@Valid @RequestBody TenantRequest request) {
Assert.isNull(request.getId(), "When adding a new Tenant, the ID must be null");
return this.tenantsService.operate(request);
}

@PutMapping("modify")
@PreAuthorize("hasRole(@contextUtils.RULE_ADMINISTRATORS)")
public Mono<Tenant> modify(@Valid @RequestBody TenantRequest request) {
Assert.notNull(request.getId(), "When modifying an existing Tenant, the ID must not be null");
public Mono<Tenant> operate(@Valid @RequestBody TenantRequest request) {
return this.tenantsService.operate(request);
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@
public class TenantsService extends AbstractDatabase {

private final TenantsRepository tenantsRepository;

private final TenantMembersRepository membersRepository;

public Flux<Tenant> search(TenantRequest request, Pageable pageable) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,9 @@
public class TenantMemberRequest extends TenantMember {

private Set<String> users;

private String username;

private String securityCode;

public TenantMemberRequest securityCode(String securityCode) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,6 @@ public Mono<Page<TenantMemberResponse>> page(TenantMemberRequest request, Pageab
.map(tuple2 -> new PageImpl<>(tuple2.getT1(), pageable, tuple2.getT2()));
}


@Transactional(rollbackFor = Exception.class)
public Mono<TenantMember> operate(TenantMemberRequest request) {
var tenantMemberMono = this.entityTemplate.selectOne(Query.query(request.toCriteria()), TenantMember.class)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -28,12 +28,13 @@ public Flux<UserAuthority> search(UserAuthorityRequest request) {

public Mono<UserAuthority> operate(UserAuthorityRequest request) {
var dataMono = this.entityTemplate.selectOne(Query.query(request.toCriteria()), UserAuthority.class);
return dataMono.switchIfEmpty(Mono.defer(() -> this.save(request.toAuthority())))
.doAfterTerminate(() -> this.cache.clear());
dataMono = dataMono.switchIfEmpty(Mono.defer(() -> this.save(request.toAuthority())));
return dataMono.doAfterTerminate(() -> this.cache.clear());
}

public Mono<Void> delete(UserAuthorityRequest request) {
return this.userAuthoritiesRepository.delete(request.toAuthority()).doAfterTerminate(() -> this.cache.clear());
return this.userAuthoritiesRepository.delete(request.toAuthority())
.doAfterTerminate(() -> this.cache.clear());
}

public Mono<UserAuthority> save(UserAuthority userAuthority) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ public class CsrfWebFilter implements WebFilter, Ordered {

@Override
public @NonNull Mono<Void> filter(ServerWebExchange exchange, @NonNull WebFilterChain chain) {
log.debug("{}Csrf filter chain continue next.", exchange.getLogPrefix());
log.debug("{}Csrf filter chain [CsrfWebFilter] next.", exchange.getLogPrefix());
Mono<CsrfToken> csrfTokenMono = exchange.getAttribute(CsrfToken.class.getName());
if (csrfTokenMono != null) {
return csrfTokenMono.flatMap(csrfToken -> Mono.defer(() -> chain.filter(exchange))
Expand Down

0 comments on commit 3dd7a07

Please sign in to comment.