Skip to content

Commit 364ed19

Browse files
committed
Refactor AuthorizedUserAuditorAware to enhance flexibility in retrieving authorized user
- Replaced direct dependency injection of `AuthorizedUser` with `BeanFactory` to improve decoupling - Introduced `getAuthorizedUserIfPresent` method to safely retrieve authorized user from context - Improved handling of scenarios with no active request or session
1 parent acf8fad commit 364ed19

File tree

1 file changed

+16
-3
lines changed

1 file changed

+16
-3
lines changed

src/main/java/org/tb/auth/persistence/AuthorizedUserAuditorAware.java

Lines changed: 16 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -4,22 +4,35 @@
44

55
import java.util.Optional;
66
import lombok.RequiredArgsConstructor;
7+
import org.springframework.beans.factory.BeanFactory;
78
import org.springframework.data.domain.AuditorAware;
89
import org.springframework.stereotype.Component;
10+
import org.springframework.web.context.request.RequestAttributes;
11+
import org.springframework.web.context.request.RequestContextHolder;
912
import org.tb.auth.domain.AuthorizedUser;
1013

1114
@Component
1215
@RequiredArgsConstructor
1316
public class AuthorizedUserAuditorAware implements AuditorAware<String> {
1417

15-
private final AuthorizedUser authorizedUser;
18+
private final BeanFactory beanFactory;
1619

1720
@Override
1821
public Optional<String> getCurrentAuditor() {
19-
if(authorizedUser.isAuthenticated()) {
20-
return Optional.of(authorizedUser.getLoginSign());
22+
var authorizedUser = getAuthorizedUserIfPresent();
23+
if(authorizedUser.isPresent() && authorizedUser.get().isAuthenticated()) {
24+
return Optional.of(authorizedUser.get().getLoginSign());
2125
}
2226
return Optional.of(SYSTEM_SIGN);
2327
}
2428

29+
public Optional<AuthorizedUser> getAuthorizedUserIfPresent() {
30+
RequestAttributes attrs = RequestContextHolder.getRequestAttributes();
31+
if (attrs == null) {
32+
return Optional.empty(); // no request → no session
33+
}
34+
35+
return Optional.of(beanFactory.getBean(AuthorizedUser.class));
36+
}
37+
2538
}

0 commit comments

Comments
 (0)