Skip to content

Commit

Permalink
Fix: Front url 전달 코드 정리
Browse files Browse the repository at this point in the history
  • Loading branch information
nampongo committed Mar 15, 2024
1 parent ad69927 commit 8d00d48
Show file tree
Hide file tree
Showing 5 changed files with 12 additions and 146 deletions.
Original file line number Diff line number Diff line change
@@ -1,9 +1,7 @@
package com.senity.waved.base.security;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.senity.waved.base.jwt.TokenDto;
import com.senity.waved.base.jwt.TokenProvider;
import com.senity.waved.base.redis.Redis;
import com.senity.waved.base.redis.RedisUtil;
import com.senity.waved.domain.member.entity.Member;
import com.senity.waved.domain.member.repository.MemberRepository;
Expand All @@ -20,15 +18,13 @@
import org.springframework.web.util.UriComponentsBuilder;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Optional;

@Slf4j
@Component
@RequiredArgsConstructor
public class OAuth2MemberSuccessHandler extends SimpleUrlAuthenticationSuccessHandler {

@Value("${custom.site.baseUrl}")
@Value("${custom.oauth2.authorized-redirect-url}")
private String REDIRECT_URI;
private final MemberRepository memberRepository;
private final TokenProvider tokenProvider;
Expand All @@ -50,19 +46,12 @@ public void onAuthenticationSuccess(HttpServletRequest request, HttpServletRespo
}
redisUtil.save(userEmail, token.getRefreshToken());*/

/* response.setHeader("Authorization", "Bearer " + token.getAccessToken());
response.setContentType("application/json;charset=UTF-8");
PrintWriter out = response.getWriter();
out.print(new ObjectMapper().writeValueAsString(token));
out.flush();*/

String url = makeRedirectUrl(token.getAccessToken(), token.getRefreshToken(), token.getHasInfo());
response.sendRedirect(url);
}

private String makeRedirectUrl(String access, String refresh, Boolean hasInfo) {
return UriComponentsBuilder.fromUriString("http://localhost:3000/oauth")
return UriComponentsBuilder.fromUriString(REDIRECT_URI)
.queryParam("accessToken", access)
.queryParam("refreshToken", refresh)
.queryParam("hasInfo", hasInfo)
Expand Down
Original file line number Diff line number Diff line change
@@ -1,43 +1,24 @@
package com.senity.waved.domain.member.controller;

import com.senity.waved.base.jwt.TokenDto;
import com.senity.waved.base.jwt.TokenProvider;
import com.senity.waved.domain.member.dto.GithubInfoDto;
import com.senity.waved.domain.member.dto.ProfileEditDto;
import com.senity.waved.domain.member.dto.response.ProfileInfoResponseDto;
import com.senity.waved.domain.member.entity.AuthLevel;
import com.senity.waved.domain.member.entity.Member;
import com.senity.waved.domain.member.service.MemberService;
import com.senity.waved.domain.review.dto.response.ReviewResponseDto;
import jakarta.servlet.http.HttpServletRequest;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.domain.Page;
import org.springframework.http.*;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.oauth2.client.OAuth2AuthorizedClient;
import org.springframework.security.oauth2.client.annotation.RegisteredOAuth2AuthorizedClient;
import org.springframework.security.oauth2.client.userinfo.OAuth2UserRequest;
import org.springframework.security.oauth2.core.OAuth2AccessToken;
import org.springframework.security.oauth2.core.OAuth2AuthenticationException;
import org.springframework.security.oauth2.core.user.DefaultOAuth2User;
import org.springframework.security.oauth2.core.user.OAuth2User;
import org.springframework.web.bind.annotation.*;


import org.springframework.security.oauth2.client.OAuth2AuthorizedClientService;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.client.RestTemplate;

import java.net.URI;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.UUID;

@Slf4j
@RestController
@RequiredArgsConstructor
Expand Down Expand Up @@ -116,58 +97,4 @@ public Page<ReviewResponseDto> getReviews(
) {
return memberService.getReviewsPaged(user.getUsername(), pageNumber, pageSize);
}

@GetMapping("/customlogin")
public TokenDto getTokens() {

// OAuth2AccessToken accessToken = authorizedClient.getAccessToken();

// 액세스 토큰을 사용하여 Google API 호출을 위한 HTTP 요청을 생성합니다.
// HttpHeaders headers = new HttpHeaders();
// headers.setBearerAuth(accessToken.getTokenValue());
// RequestEntity<Void> request = new RequestEntity<>(headers, HttpMethod.GET, URI.create("https://www.googleapis.com/oauth2/v3/userinfo"));


RequestEntity<Void> request = new RequestEntity<>(new HttpHeaders(), HttpMethod.GET, URI.create("https://127.0.0.1/oauth2/authorization/google"));
// Google API로부터 사용자 정보를 가져옵니다.
ResponseEntity<String> response = restTemplate.exchange(request, String.class);
System.out.println(response);

String user = "";
//return memberService.getNewTokens(user.getUsername());
return memberService.getNewTokens(user);
}

@GetMapping("/login")
public TokenDto getTokens(@RegisteredOAuth2AuthorizedClient("google") OAuth2AuthorizedClient authorizedClient) {
OAuth2AccessToken accessToken = authorizedClient.getAccessToken();

// 액세스 토큰을 사용하여 Google API 호출을 위한 HTTP 요청을 생성합니다.
HttpHeaders headers = new HttpHeaders();
headers.setBearerAuth(accessToken.getTokenValue());
RequestEntity<Void> request = new RequestEntity<>(headers, HttpMethod.GET, URI.create("https://www.googleapis.com/oauth2/v3/userinfo"));

// Google API로부터 사용자 정보를 가져옵니다.
ResponseEntity<String> response = restTemplate.exchange(request, String.class);

String user = "";
//return memberService.getNewTokens(user.getUsername());
return memberService.getNewTokens(user);
}

@GetMapping("/user")
public ResponseEntity<String> getUserInfo(@RegisteredOAuth2AuthorizedClient("google") OAuth2AuthorizedClient authorizedClient) {
// Google OAuth 2.0로부터 액세스 토큰을 가져옵니다.
OAuth2AccessToken accessToken = authorizedClient.getAccessToken();

// 액세스 토큰을 사용하여 Google API 호출을 위한 HTTP 요청을 생성합니다.
HttpHeaders headers = new HttpHeaders();
headers.setBearerAuth(accessToken.getTokenValue());
RequestEntity<Void> request = new RequestEntity<>(headers, HttpMethod.GET, URI.create("https://www.googleapis.com/oauth2/v3/userinfo"));

// Google API로부터 사용자 정보를 가져옵니다.
ResponseEntity<String> response = restTemplate.exchange(request, String.class);

return response;
}
}
Original file line number Diff line number Diff line change
@@ -1,12 +1,10 @@
package com.senity.waved.domain.member.service;

import com.senity.waved.base.jwt.TokenDto;
import com.senity.waved.domain.member.dto.GithubInfoDto;
import com.senity.waved.domain.member.dto.ProfileEditDto;
import com.senity.waved.domain.member.dto.response.ProfileInfoResponseDto;
import com.senity.waved.domain.review.dto.response.ReviewResponseDto;
import org.springframework.data.domain.Page;
import org.springframework.security.core.Authentication;

public interface MemberService {
String resolveRefreshToken(String refreshToken);
Expand All @@ -24,6 +22,4 @@ public interface MemberService {
void deleteGithubInfo(String email);

Page<ReviewResponseDto> getReviewsPaged(String email, int pageNumber, int pageSize);

TokenDto getNewTokens(String email);
}
Original file line number Diff line number Diff line change
@@ -1,12 +1,9 @@
package com.senity.waved.domain.member.service;

import com.senity.waved.base.jwt.TokenDto;
import com.senity.waved.base.jwt.TokenProvider;
import com.senity.waved.base.redis.RedisUtil;
import com.senity.waved.domain.member.dto.GithubInfoDto;
import com.senity.waved.domain.member.dto.ProfileEditDto;
import com.senity.waved.domain.member.dto.response.ProfileInfoResponseDto;
import com.senity.waved.domain.member.entity.AuthLevel;
import com.senity.waved.domain.member.entity.Member;
import com.senity.waved.domain.member.exception.InvalidRefreshTokenException;
import com.senity.waved.domain.member.exception.WrongGithubInfoException;
Expand All @@ -22,19 +19,11 @@
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.oauth2.core.OAuth2AuthenticationException;
import org.springframework.security.oauth2.core.user.DefaultOAuth2User;
import org.springframework.security.oauth2.core.user.OAuth2User;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.IOException;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;

@Service
Expand All @@ -43,7 +32,6 @@ public class MemberServiceImpl implements MemberService {

private final MemberRepository memberRepository;
private final RedisUtil redisUtil;
private final TokenProvider tokenProvider;
private GitHub github;

@Transactional(readOnly = true)
Expand Down Expand Up @@ -150,43 +138,4 @@ private Member getMemberByEmail(String email) {
return memberRepository.findByEmail(email)
.orElseThrow(() -> new MemberNotFoundException("회원 정보를 찾을 수 없습니다."));
}


//
//
//

@Transactional
public TokenDto getNewTokens(String email) {
System.out.println("-----token email : " + email);
Member member = memberRepository.findByEmail(email).orElseGet(() -> createNewMember(email, generateRandomNickname()));

return new TokenDto(tokenProvider.createAccessToken(email),
tokenProvider.createRefreshToken(email), member.getHasInfo());
}

private Member createNewMember(String email, String nickname) {
AuthLevel authLevel = AuthLevel.MEMBER;
List<String> adminMembers = Arrays.asList("[email protected]", "[email protected]"
, "[email protected]", "[email protected]", "[email protected]");

if (adminMembers.contains(email)) {
authLevel = AuthLevel.ADMIN;
}

Member newMember = Member.builder()
.email(email)
.nickname(nickname)
.authLevel(authLevel)
.hasInfo(false)
.build();

return memberRepository.save(newMember);
}

private String generateRandomNickname() {
UUID uuid = UUID.randomUUID();
String hash = Integer.toHexString(uuid.hashCode());
return "서퍼" + hash.substring(0, Math.min(hash.length(), 6));
}
}
15 changes: 10 additions & 5 deletions src/main/resources/application.yml
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
server:
port: 9000

spring:
data:
redis:
Expand All @@ -16,14 +17,15 @@ spring:
active: prod
include: secret
datasource:
url: '${custom.db.url}'
username: '${custom.db.username}'
password: '${custom.db.password}'
driver-class-name: com.mysql.cj.jdbc.Driver
hikari:
maximum-pool-size: '${custom.hikari.maximum-pool-size}'
idle-timeout: '${custom.hikari.idle-timeout}'
max-lifetime: '${custom.hikari.max-lifetime}'
driver-class-name: com.mysql.cj.jdbc.Driver
url: '${custom.db.url}'
username: '${custom.db.username}'
password: '${custom.db.password}'
minimum-idle: '${custom.hikari.minimum-idle}'
jpa:
hibernate:
ddl-auto: update
Expand All @@ -45,11 +47,14 @@ spring:
registration:
google:
client-name: Google
# redirect-uri: '${custom.site.baseUrl}/login/oauth2/code/google'
scope:
- email
- profile

app:
oauth2:
authorized-redirect-uri: '${custom.oauth2.authorized-redirect-uri}'

logging:
level:
root: INFO
Expand Down

0 comments on commit 8d00d48

Please sign in to comment.