-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCustomOAuth2UserService.java
More file actions
150 lines (119 loc) · 4.93 KB
/
CustomOAuth2UserService.java
File metadata and controls
150 lines (119 loc) · 4.93 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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
package com.devpass.global.oauth.service;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import org.springframework.security.oauth2.client.userinfo.DefaultOAuth2UserService;
import org.springframework.security.oauth2.client.userinfo.OAuth2UserRequest;
import org.springframework.security.oauth2.core.OAuth2AuthenticationException;
import org.springframework.security.oauth2.core.user.OAuth2User;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.devpass.domain.user.dto.UserDTO;
import com.devpass.domain.user.entity.User;
import com.devpass.domain.user.repository.UserRepository;
import com.devpass.global.oauth.dto.CustomOAuth2User;
import com.devpass.global.oauth.dto.GitHubResponseDTO;
import com.devpass.global.oauth.dto.OAuth2Response;
import com.devpass.global.oauth.dto.TokenDTO;
import com.devpass.global.oauth.util.CookieUtil;
import com.devpass.global.oauth.util.JWTUtil;
import com.devpass.global.payload.apicode.ErrorStatus;
import com.devpass.global.payload.error.exception.GeneralException;
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.servlet.http.HttpServletResponse;
@Service
public class CustomOAuth2UserService extends DefaultOAuth2UserService {
private final UserRepository userRepository;
private final JWTUtil jwtUtil;
public CustomOAuth2UserService(UserRepository userRepository, JWTUtil jwtUtil) {
this.userRepository = userRepository;
this.jwtUtil = jwtUtil;
}
@Override
@Transactional
public OAuth2User loadUser(OAuth2UserRequest userRequest) throws OAuth2AuthenticationException {
OAuth2User oAuth2User = super.loadUser(userRequest);
System.out.println(oAuth2User);
String registrationId = userRequest.getClientRegistration().getRegistrationId();
OAuth2Response oAuth2Response = null;
if (registrationId.equals("github")) {
oAuth2Response = new GitHubResponseDTO(oAuth2User.getAttributes());
} else {
throw new OAuth2AuthenticationException("Unsupported provider: " + registrationId);
}
String providerId = oAuth2Response.getProviderId();
String email = oAuth2Response.getEmail();
if (email == null || email.isBlank()) {
String accessToken = userRequest.getAccessToken().getTokenValue();
email = fetchPrimaryEmailFromGitHub(accessToken);
}
Optional<User> existData = userRepository.findByProviderId(providerId);
if (existData.isEmpty()) {
User userEntity = User.builder()
.name(oAuth2Response.getName())
.email(email)
.provider(oAuth2Response.getProvider())
.providerId(oAuth2Response.getProviderId())
.build();
userRepository.save(userEntity);
UserDTO userDTO = UserDTO.builder()
.id(userEntity.getId())
.name(oAuth2Response.getName())
.email(oAuth2Response.getEmail())
.provider(oAuth2Response.getProvider())
.providerId(oAuth2Response.getProviderId())
.build();
return new CustomOAuth2User(userDTO);
} else {
User user = existData.get();
user.updateName(oAuth2Response.getName());
user.updateEmail(oAuth2Response.getEmail());
userRepository.save(user);
userRepository.flush();
UserDTO userDTO = UserDTO.builder()
.id(user.getId())
.name(oAuth2Response.getName())
.email(oAuth2Response.getEmail())
.provider(oAuth2Response.getProvider())
.providerId(oAuth2Response.getProviderId())
.build();
return new CustomOAuth2User(userDTO);
}
}
@Transactional
public TokenDTO reissue(Long userId, HttpServletResponse response) {
User user = userRepository.findById(userId)
.orElseThrow(() -> new GeneralException(ErrorStatus.USER_NOT_FOUND));
TokenDTO tokenDTO = jwtUtil.generateTokens(user.getProviderId());
long expiration = jwtUtil.getExpiration(tokenDTO.getRefreshToken()).getTime();
response.addCookie(CookieUtil.createCookie("accessToken", tokenDTO.getAccessToken(), expiration));
return tokenDTO;
}
private String fetchPrimaryEmailFromGitHub(String accessToken) {
try {
URL url = new URL("https://api.github.com/user/emails");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setRequestProperty("Authorization", "Bearer " + accessToken);
connection.setRequestProperty("Accept", "application/vnd.github+json");
int responseCode = connection.getResponseCode();
if (responseCode == 200) {
ObjectMapper objectMapper = new ObjectMapper();
List<Map<String, Object>> emails = objectMapper.readValue(connection.getInputStream(), List.class);
for (Map<String, Object> emailObj : emails) {
Boolean primary = (Boolean) emailObj.get("primary");
Boolean verified = (Boolean) emailObj.get("verified");
if (Boolean.TRUE.equals(primary) && Boolean.TRUE.equals(verified)) {
return emailObj.get("email").toString();
}
}
}
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}