-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathOAuth2UserRegistrationService.java
More file actions
110 lines (92 loc) · 4.56 KB
/
OAuth2UserRegistrationService.java
File metadata and controls
110 lines (92 loc) · 4.56 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
package learningFlow.learningFlow_BE.service.auth.oauth;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.transaction.Transactional;
import learningFlow.learningFlow_BE.security.auth.PrincipalDetails;
import learningFlow.learningFlow_BE.security.jwt.JwtTokenProvider;
import learningFlow.learningFlow_BE.domain.User;
import learningFlow.learningFlow_BE.domain.enums.Role;
import learningFlow.learningFlow_BE.domain.enums.SocialType;
import learningFlow.learningFlow_BE.repository.UserRepository;
import learningFlow.learningFlow_BE.web.dto.user.UserRequestDTO;
import learningFlow.learningFlow_BE.web.dto.user.UserResponseDTO;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import static learningFlow.learningFlow_BE.converter.UserConverter.toUserLoginResponseDTO;
@Service
@RequiredArgsConstructor
@Slf4j
@Transactional
public class OAuth2UserRegistrationService {
private final UserRepository userRepository;
private final JwtTokenProvider jwtTokenProvider;
private final RedisTemplate<String, String> redisTemplate;
// 추가 정보 입력 필요 여부와 필드 정보를 반환하는 메소드
public Map<String, Object> getAdditionalInfoRequirements() {
Map<String, Object> response = new HashMap<>();
response.put("message", "추가 정보 입력이 필요합니다");
response.put("requiredFields", Arrays.asList(
"job", "interestFields", "gender", "preferType"
));
return response;
}
@Transactional
public UserResponseDTO.UserLoginResponseDTO updateAdditionalInfo(
String temporaryToken,
UserRequestDTO.AdditionalInfoDTO additionalInfo,
HttpServletResponse response) {
if (!jwtTokenProvider.validateToken(temporaryToken) || !jwtTokenProvider.isTemporaryToken(temporaryToken)) {
throw new RuntimeException("유효하지 않은 토큰입니다.");
}
Claims claims = jwtTokenProvider.getClaims(temporaryToken);
String email = claims.getSubject();
String name = claims.get("name", String.class);
String providerId = claims.get("providerId", String.class);
SocialType socialType = SocialType.valueOf(claims.get("socialType", String.class));
User newUser = User.builder()
.loginId(socialType.name() + "_" + providerId)
.email(email)
.name(name)
.providerId(providerId)
.pw("OAUTH2_USER")
.socialType(socialType)
.job(additionalInfo.getJob())
.interestFields(additionalInfo.getInterestFields())
.gender(additionalInfo.getGender())
.preferType(additionalInfo.getPreferType())
.role(Role.USER)
.inactive(false)
.build();
User savedUser = userRepository.save(newUser);
//정식으로 JWT 토큰 발급
Authentication authentication = new UsernamePasswordAuthenticationToken(
new PrincipalDetails(savedUser),
null,
Collections.singleton(new SimpleGrantedAuthority("ROLE_" + savedUser.getRole().name()))
);
SecurityContextHolder.getContext().setAuthentication(authentication);
String accessToken = jwtTokenProvider.createAccessToken(authentication);
response.addHeader("Authorization", "Bearer " + accessToken);
log.info("Access 토큰 발급 : {}", accessToken);
String refreshToken = jwtTokenProvider.createRefreshToken(authentication);
response.addHeader("Refresh-Token", refreshToken);
log.info("자동 로그인 활성화, Refresh Token 발급 : {}", refreshToken);
//임시 토큰 블랙리스트에 저장
redisTemplate.opsForValue()
.set("BLACKLIST:" + temporaryToken, "true",
jwtTokenProvider.getRemainingTime(temporaryToken),
TimeUnit.MILLISECONDS);
return toUserLoginResponseDTO(savedUser);
}
}