-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCurrentUserService.java
More file actions
53 lines (41 loc) · 1.7 KB
/
Copy pathCurrentUserService.java
File metadata and controls
53 lines (41 loc) · 1.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
package demo.codeexample.auth.application;
import demo.codeexample.auth.CurrentUserLookup;
import demo.codeexample.auth.infrastructure.CustomUserDetails;
import demo.codeexample.user.UserDto;
import demo.codeexample.user.UserLookup;
import lombok.RequiredArgsConstructor;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.oauth2.core.user.OAuth2User;
import org.springframework.stereotype.Service;
import java.util.Optional;
@Service
@RequiredArgsConstructor
public class CurrentUserService implements CurrentUserLookup {
private final UserLookup userLookup;
@Override
public Optional<UserDto> getCurrentUser() {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
if (authentication == null || !authentication.isAuthenticated()) {
return Optional.empty();
}
Object principal = authentication.getPrincipal();
if (principal instanceof CustomUserDetails customUserDetails) {
return userLookup.findByEmail(customUserDetails.getUsername());
}
if (principal instanceof OAuth2User oAuth2User) {
String email = oAuth2User.getAttribute("email");
if (email != null) {
return userLookup.findByEmail(email);
}
return Optional.empty();
}
if (principal instanceof String email && !"anonymousUser".equals(email)) {
return userLookup.findByEmail(email);
}
if (principal instanceof Long userId) {
return userLookup.findById(userId);
}
return Optional.empty();
}
}