Skip to content

Commit

Permalink
fix: 로그인 수정
Browse files Browse the repository at this point in the history
  • Loading branch information
Ojimin committed Jun 7, 2024
1 parent 4a489b7 commit d7ab95d
Show file tree
Hide file tree
Showing 3 changed files with 55 additions and 35 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.HttpStatusCode;
import org.springframework.http.ResponseEntity;
Expand All @@ -19,27 +20,30 @@
@RestController
//@RequestMapping(value = "/login/oauth2", produces = "application/json")
@RequiredArgsConstructor
@Slf4j
public class OAuthController {
private final OAuthService oauthService;

/**
* 인가코드 받기 - back
*/
@Operation(summary = "인가코드 받기-백엔드 테스트", description = "PathVariable로 registratino id를, 쿼리스트링으로 code를 받습니다")
@ApiResponse(responseCode = "200", description = "성공")
@GetMapping("/login/oauth2/code/{registrationId}")
public void googleLoginBack(@PathVariable(value = "registrationId") String registrationId, @RequestParam(value = "code")String code) {
oauthService.socialLogin(code, registrationId);
}
// /**
// * 인가코드 받기 - back
// */
// @Operation(summary = "인가코드 받기-백엔드 테스트", description = "PathVariable로 registratino id를, 쿼리스트링으로 code를 받습니다")
// @ApiResponse(responseCode = "200", description = "성공")
// @GetMapping("/login/oauth2/code/{registrationId}")
// public void googleLoginBack(@PathVariable(value = "registrationId") String registrationId, @RequestParam(value = "code")String code) {
// oauthService.socialLogin(code, registrationId);
// }

/**
* 프론트한테 인가코드 받기
*/
@Operation(summary = "인가코드 받기-프론트", description = "PathVariable로 registratino id를, 쿼리스트링으로 code를 받습니다")
@ApiResponse(responseCode = "200", description = "성공")
@GetMapping("/login/code/{registrationId}")
public ResponseEntity<LoginResponseDto.GetLoginDto> googleLogin(@PathVariable(value = "registrationId") String registrationId, @RequestParam(value = "code")String code) {
LoginResponseDto.GetLoginDto loginResponse = oauthService.socialLogin(code, registrationId);
@GetMapping("/login/oauth2/code/google")
public ResponseEntity<LoginResponseDto.GetLoginDto> googleLogin(@RequestParam(value = "code")String code) {
System.out.println("인가코드 받음:"+ code);
log.info("인가코드 받음:"+ code);
LoginResponseDto.GetLoginDto loginResponse = oauthService.front_socialLogin(code);
return ResponseEntity.status(HttpStatus.OK).body(loginResponse);
}

Expand Down
60 changes: 38 additions & 22 deletions src/main/java/vom/spring/global/oauth/service/OAuthService.java
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

import com.fasterxml.jackson.databind.JsonNode;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.env.Environment;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
Expand All @@ -15,10 +16,28 @@
import vom.spring.global.oauth.dto.LoginRequestDto;
import vom.spring.global.oauth.dto.LoginResponseDto;

import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;

@Service
@RequiredArgsConstructor
public class OAuthService {
private final Environment env;
// private final Environment env;
@Value("${oauth2.google.client-id}")
private String clientId;

@Value("${oauth2.google.client-secret}")
private String clientSecret;

@Value("${oauth2.google.redirect-uri}")
private String redirectUri;

@Value("${oauth2.google.token-uri}")
private String tokenUri;

@Value("${oauth2.google.resource-uri}")
private String resourceUri;

private final RestTemplate restTemplate = new RestTemplate();
private final MemberRepository memberRepository;
private final JwtTokenProvider jwtTokenProvider;
Expand All @@ -43,9 +62,10 @@ public LoginResponseDto.GetLoginDto socialLogin(String code, String registration
//회원가입이 되어있지 않은경우
if (!isRegistered) {
Member newMember = new Member(email);
Member savedMember = memberRepository.save(newMember);
return LoginResponseDto.GetLoginDto.builder()
.isRegistered(false)
.memberId(newMember.getId())
.memberId(savedMember.getId())
.build();
}
//회원가입이 되어있는 경우
Expand All @@ -54,20 +74,18 @@ public LoginResponseDto.GetLoginDto socialLogin(String code, String registration
.isRegistered(true)
.memberId(member.getId())
.build();
// System.out.println("id = " + id);
// System.out.println("email = " + email);
// System.out.println("nickname = " + nickname);
}

@Transactional
public LoginResponseDto.GetLoginDto front_socialLogin(LoginRequestDto.LoginCodeDto request, String registrationId) {
public LoginResponseDto.GetLoginDto front_socialLogin(String code) {
//로그인 시도
//해당 이메일로 유저 조회
//이미 있는 유저이면 true담아서 보내고
//아니면 false 담아 보낸 후 회원가입 시도
// System.out.println("인가code = " + code);
System.out.println("인가code = " + code);
// System.out.println("registrationId = " + registrationId);
String accessToken = getAccessToken(request.getAuth_code(), registrationId);
String registrationId = "google";
String accessToken = getAccessToken(code, registrationId);
// System.out.println("accessToken = " +accessToken);
JsonNode userResourceNode = getUserResource(accessToken, registrationId);
// System.out.println("userResourceNode = " + userResourceNode);
Expand All @@ -79,10 +97,11 @@ public LoginResponseDto.GetLoginDto front_socialLogin(LoginRequestDto.LoginCodeD
//회원가입이 되어있지 않은경우
if (!isRegistered) {
Member newMember = new Member(email);
String token = issueToken(newMember);
Member savedMember = memberRepository.save(newMember);
String token = issueToken(savedMember);
return LoginResponseDto.GetLoginDto.builder()
.isRegistered(false)
.memberId(newMember.getId())
.memberId(savedMember.getId())
.accessToken(token)
.build();
}
Expand All @@ -94,27 +113,24 @@ public LoginResponseDto.GetLoginDto front_socialLogin(LoginRequestDto.LoginCodeD
.memberId(member.getId())
.accessToken(token)
.build();
// System.out.println("id = " + id);
// System.out.println("email = " + email);
// System.out.println("nickname = " + nickname);
}

//google access token 발급
private String getAccessToken(String authorizationCode, String registrationId) {
String clientId = env.getProperty("oauth2." + registrationId + ".client-id");
String clientSecret = env.getProperty("oauth2." + registrationId + ".client-secret");
String redirectUri = env.getProperty("oauth2." + registrationId + ".redirect-uri");
String tokenUri = env.getProperty("oauth2." + registrationId + ".token-uri");

// String clientId = env.getProperty("oauth2." + registrationId + ".client-id");
// String clientSecret = env.getProperty("oauth2." + registrationId + ".client-secret");
// String redirectUri = env.getProperty("oauth2." + registrationId + ".redirect-uri");
// String tokenUri = env.getProperty("oauth2." + registrationId + ".token-uri");
String decode = URLDecoder.decode(authorizationCode, StandardCharsets.UTF_8);
MultiValueMap<String, String> params = new LinkedMultiValueMap<>();
params.add("code", authorizationCode);
params.add("grant_type", "authorization_code");
params.add("code", decode);
params.add("client_id", clientId);
params.add("client_secret", clientSecret);
params.add("redirect_uri", redirectUri);
params.add("grant_type", "authorization_code");

HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
headers.add("Content-type", "application/x-www-form-urlencoded");

HttpEntity entity = new HttpEntity(params, headers);

Expand All @@ -125,7 +141,7 @@ private String getAccessToken(String authorizationCode, String registrationId) {

//유저정보 받기
private JsonNode getUserResource(String accessToken, String registrationId) {
String resourceUri = env.getProperty("oauth2." + registrationId + ".resource-uri");
// String resourceUri = env.getProperty("oauth2." + registrationId + ".resource-uri");
HttpHeaders headers = new HttpHeaders();
headers.set("Authorization", "Bearer " + accessToken);
HttpEntity entity = new HttpEntity(headers);
Expand Down
2 changes: 1 addition & 1 deletion src/main/resources/application-dev.yml
Original file line number Diff line number Diff line change
Expand Up @@ -59,4 +59,4 @@ springdoc:

jwt :
secret: ${JWT_SECRET}
expiration_time: 2592000 #30일
expiration_time: 2678400000 #31일

0 comments on commit d7ab95d

Please sign in to comment.