From 8e3872c1c9605bb084267607aa2eeb08a7f585d5 Mon Sep 17 00:00:00 2001 From: EveKristinLee Date: Sat, 5 Mar 2022 02:35:26 +0900 Subject: [PATCH] =?UTF-8?q?[#23]Feat:=20=EA=B5=AC=EA=B8=80=20=EC=86=8C?= =?UTF-8?q?=EC=85=9C=EB=A1=9C=EA=B7=B8=EC=9D=B8=20=EA=B8=B0=EB=8A=A5=20?= =?UTF-8?q?=EA=B5=AC=ED=98=84?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- backend/.gitignore | 1 + .../movie/configure/ApiKeyConfig.java | 21 ++ .../movie/configure/GoogleConfigUtils.java | 149 ++++++++++++++ .../movie/controller/SignInController.java | 41 +++- .../movie/controller/SignUpController.java | 5 +- .../dto/Manager/ManagerResponseDto.java | 6 +- .../domain/dto/signin/SignInRequestDto.java | 5 + .../domain/dto/signup/SignUpRequestDto.java | 4 + .../movie/domain/entity/User/Authority.java | 2 +- .../movie/domain/entity/User/Method.java | 5 + .../movie/domain/entity/User/User.java | 4 + .../domain/entity/User/UserRepository.java | 2 + .../movie/service/ChatRoomService.java | 2 +- .../moviegoods/movie/service/ChatService.java | 26 ++- .../movie/service/ManagerService.java | 23 ++- .../movie/service/MyPageService.java | 9 +- .../movie/service/SignInService.java | 194 ++++++++++++++++-- .../movie/service/SignUpService.java | 19 +- .../src/main/resources/application.properties | 8 +- backend/src/main/resources/application.yml | 4 +- .../src/main/resources/serviceAccountKey.json | 2 + 21 files changed, 480 insertions(+), 52 deletions(-) create mode 100644 backend/src/main/java/moviegoods/movie/configure/ApiKeyConfig.java create mode 100644 backend/src/main/java/moviegoods/movie/configure/GoogleConfigUtils.java create mode 100644 backend/src/main/java/moviegoods/movie/domain/entity/User/Method.java diff --git a/backend/.gitignore b/backend/.gitignore index 7497494..636cd33 100644 --- a/backend/.gitignore +++ b/backend/.gitignore @@ -5,6 +5,7 @@ build/ !**/src/main/**/build/ !**/src/test/**/build/ application-aws.properties +chromedriver1 ### STS ### .apt_generated .classpath diff --git a/backend/src/main/java/moviegoods/movie/configure/ApiKeyConfig.java b/backend/src/main/java/moviegoods/movie/configure/ApiKeyConfig.java new file mode 100644 index 0000000..d73a033 --- /dev/null +++ b/backend/src/main/java/moviegoods/movie/configure/ApiKeyConfig.java @@ -0,0 +1,21 @@ +package moviegoods.movie.configure; + +import com.google.api.client.util.Value; +import lombok.Data; +import lombok.NoArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.stereotype.Component; + +@Data +@NoArgsConstructor +@Component +public class ApiKeyConfig { + @Value("${KakaoRestApiKey}") + private String KakaoApiKey; + + public String getKakaoApiKey() { + return KakaoApiKey; + } + + +} diff --git a/backend/src/main/java/moviegoods/movie/configure/GoogleConfigUtils.java b/backend/src/main/java/moviegoods/movie/configure/GoogleConfigUtils.java new file mode 100644 index 0000000..fa2a6cc --- /dev/null +++ b/backend/src/main/java/moviegoods/movie/configure/GoogleConfigUtils.java @@ -0,0 +1,149 @@ +package moviegoods.movie.configure; + +import com.google.gson.JsonElement; +import com.google.gson.JsonParser; +import org.springframework.beans.factory.annotation.Value; +import lombok.Getter; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.stereotype.Component; +import org.springframework.web.client.RestTemplate; + +import java.io.*; +import java.net.HttpURLConnection; +import java.net.URL; +import java.util.HashMap; +import java.util.Map; +import java.util.stream.Collectors; + +@Getter +@Component +public class GoogleConfigUtils { + @Value("${sns.google.url}") + private String GOOGLE_SNS_BASE_URL; + + @Value("${sns.google.client.id}") + private String GOOGLE_SNS_CLIENT_ID; + + @Value("${sns.google.callback.url}") + private String GOOGLE_SNS_CALLBACK_URL; + + @Value("${sns.google.client.secret}") + private String GOOGLE_SNS_CLIENT_SECRET; + + @Value("${sns.google.token.url}") + private String GOOGLE_SNS_TOKEN_BASE_URL; + +// public String requestAccessTokenUsingURL(String code) { +// try { +// URL url = new URL(GOOGLE_SNS_TOKEN_BASE_URL); +// HttpURLConnection conn = (HttpURLConnection) url.openConnection(); +// conn.setRequestMethod("POST"); +// conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); +// conn.setDoOutput(true); +// +// Map params = new HashMap<>(); +// params.put("code", code); +// params.put("client_id", GOOGLE_SNS_CLIENT_ID); +// params.put("client_secret", GOOGLE_SNS_CLIENT_SECRET); +// params.put("redirect_uri", GOOGLE_SNS_CALLBACK_URL); +// params.put("grant_type", "authorization_code"); +// +// String parameterString = params.entrySet().stream() +// .map(x -> x.getKey() + "=" + x.getValue()) +// .collect(Collectors.joining("&")); +// +// BufferedOutputStream bous = new BufferedOutputStream(conn.getOutputStream()); +// bous.write(parameterString.getBytes()); +// bous.flush(); +// bous.close(); +// +// BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream())); +// +// StringBuilder sb = new StringBuilder(); +// String line; +// +// while ((line = br.readLine()) != null) { +// sb.append(line); +// } +// +// if(conn.getResponseCode() == 200) { +// return sb.toString(); +// } +// return "구글 로그인 요청 처리 실패"; +// }catch (IOException e) { +// throw new IllegalArgumentException("알 수 없는 구글 로그인 Access Token 요청 URL 입니다 :: " + GOOGLE_SNS_TOKEN_BASE_URL); +// } +// } +// +// +// public String getKaKaoAccessToken(String code){ +// +// String access_Token=""; +// String refresh_Token =""; +// +// String reqURL = "https://kauth.kakao.com/oauth/token"; +// +// try{ +// URL url = new URL(reqURL); +// HttpURLConnection conn = (HttpURLConnection) url.openConnection(); +// +// conn.setRequestMethod("POST"); +// conn.setDoOutput(true); +// +// BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(conn.getOutputStream())); +// StringBuilder sb = new StringBuilder(); +// sb.append("grant_type=authorization_code"); +// sb.append("&client_id=e64599af67aac20483ad02a14a8c5058"); // TODO REST_API_KEY 입력 +// sb.append("&redirect_uri=http://localhost:3000/signin/oauth2/code/kakao"); // TODO 인가코드 받은 redirect_uri 입력 +// sb.append("&code=" + code); +// bw.write(sb.toString()); +// bw.flush(); +// +// int responseCode = conn.getResponseCode(); +// System.out.println("responseCode : " + responseCode); +// +// BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream())); +// String line = ""; +// String result = ""; +// +// while ((line = br.readLine()) != null) { +// result += line; +// } +// +// JsonParser parser = new JsonParser(); +// JsonElement element = parser.parse(result); +// +// access_Token = element.getAsJsonObject().get("access_token").getAsString(); +// refresh_Token = element.getAsJsonObject().get("refresh_token").getAsString(); +// +// br.close(); +// bw.close(); +// }catch (IOException e) { +// e.printStackTrace(); +// } +// +// return access_Token; +// } +// +// public String googleRequestAccessToken(String code) { +// RestTemplate restTemplate = new RestTemplate(); +// +// Map params = new HashMap<>(); +// params.put("code", code); +// params.put("client_id", "435089655733-6v1fo661d0dda2ue3ql61420dtquril1.apps.googleusercontent.com"); +// params.put("client_secret", "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"); +// params.put("redirect_uri", "http://localhost:8080/signin/auth/google/callback"); +// params.put("grant_type", "authorization_code"); +// +// ResponseEntity responseEntity = +// restTemplate.postForEntity("https://accounts.google.com/o/oauth2/v2/auth", params, String.class); +// +// log.info("responseEntity.getBody = {}", responseEntity.getBody().toString()); +// +// if(responseEntity.getStatusCode() == HttpStatus.OK) { +// return responseEntity.getBody(); +// } +// return "구글 로그인 요청 처리 실패"; +// } +} \ No newline at end of file diff --git a/backend/src/main/java/moviegoods/movie/controller/SignInController.java b/backend/src/main/java/moviegoods/movie/controller/SignInController.java index 4e95f23..02f20c1 100644 --- a/backend/src/main/java/moviegoods/movie/controller/SignInController.java +++ b/backend/src/main/java/moviegoods/movie/controller/SignInController.java @@ -2,36 +2,65 @@ import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; +import moviegoods.movie.domain.dto.booleanResult.ResultResponseDto; import moviegoods.movie.domain.dto.signin.SignInRequestDto; import moviegoods.movie.domain.dto.signin.SignInResponseDto; +import moviegoods.movie.domain.dto.signup.SignUpDuplicateCheckRequestDto; +import moviegoods.movie.domain.dto.signup.SignUpRequestDto; +import moviegoods.movie.domain.entity.Event.Event; +import moviegoods.movie.domain.entity.User.Method; +import moviegoods.movie.domain.entity.User.User; +import moviegoods.movie.domain.entity.User.UserRepository; import moviegoods.movie.service.SignInService; +import moviegoods.movie.service.SignUpService; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.*; +import javax.persistence.EntityManager; import javax.servlet.http.HttpServletRequest; +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.io.OutputStream; +import java.net.HttpURLConnection; +import java.net.URL; +import java.util.HashMap; +import java.util.List; @Slf4j @RestController @RequiredArgsConstructor +@RequestMapping("/signin") public class SignInController { private final SignInService signInService; - @PostMapping("/signin") - public SignInResponseDto login(@RequestBody SignInRequestDto requestDto, HttpServletRequest httpServletRequest, Model model) { + @PostMapping + public SignInResponseDto login(@RequestBody SignInRequestDto requestDto, HttpServletRequest httpServletRequest) { - return signInService.login(requestDto, httpServletRequest, model); + return signInService.login(requestDto, httpServletRequest); } @ResponseBody - @GetMapping("app/users/kakao") - public void kakaoCallback(@RequestParam String code){ + @GetMapping("/oauth2/code/kakao") + public SignInRequestDto kakaoCallback(@RequestParam String code, HttpServletRequest httpServletRequest){ - System.out.println(code); + String access_Token = signInService.getKaKaoAccessToken(code); + SignInRequestDto userInfo = signInService.getUserInfo(access_Token); + + return userInfo; } + @GetMapping("/auth/google") + public void googleLogin() { + signInService.googleRequest(); + } + @GetMapping("/auth/google/callback") + public String googleCallback(@RequestParam String code) { + return signInService.googleRequestAccessToken(code); + } } \ No newline at end of file diff --git a/backend/src/main/java/moviegoods/movie/controller/SignUpController.java b/backend/src/main/java/moviegoods/movie/controller/SignUpController.java index 162648c..dcace9e 100644 --- a/backend/src/main/java/moviegoods/movie/controller/SignUpController.java +++ b/backend/src/main/java/moviegoods/movie/controller/SignUpController.java @@ -6,6 +6,7 @@ import moviegoods.movie.domain.dto.booleanResult.ResultResponseDto; import moviegoods.movie.domain.dto.signup.SignUpDuplicateCheckRequestDto; import moviegoods.movie.domain.dto.signup.SignUpRequestDto; +import moviegoods.movie.domain.entity.User.Method; import moviegoods.movie.domain.entity.User.User; import moviegoods.movie.domain.entity.User.UserRepository; import moviegoods.movie.service.SignUpService; @@ -25,13 +26,13 @@ public class SignUpController { @PostMapping public ResultResponseDto signup(@RequestBody SignUpRequestDto requestDto){ - ResultResponseDto resultResponseDto = signUpService.saveUser(requestDto); + ResultResponseDto resultResponseDto = signUpService.saveUser(requestDto, Method.일반); return resultResponseDto; } @PostMapping("/duplicate-check") public ResultResponseDto duplicateCheck(@RequestBody SignUpDuplicateCheckRequestDto requestDto){ - ResultResponseDto resultResponseDto = signUpService.duplicateCheck(requestDto); + ResultResponseDto resultResponseDto = signUpService.duplicateCheck(requestDto,Method.일반); return resultResponseDto; } diff --git a/backend/src/main/java/moviegoods/movie/domain/dto/Manager/ManagerResponseDto.java b/backend/src/main/java/moviegoods/movie/domain/dto/Manager/ManagerResponseDto.java index aab692f..40f9658 100644 --- a/backend/src/main/java/moviegoods/movie/domain/dto/Manager/ManagerResponseDto.java +++ b/backend/src/main/java/moviegoods/movie/domain/dto/Manager/ManagerResponseDto.java @@ -15,4 +15,8 @@ public class ManagerResponseDto { private LocalDateTime written_date; private String nickname; private Long user_id; -} + private Long reported_user_id; + private String reported_nickname; + private String reported_content; + private Boolean is_complete; +} \ No newline at end of file diff --git a/backend/src/main/java/moviegoods/movie/domain/dto/signin/SignInRequestDto.java b/backend/src/main/java/moviegoods/movie/domain/dto/signin/SignInRequestDto.java index 17258f5..7745ed3 100644 --- a/backend/src/main/java/moviegoods/movie/domain/dto/signin/SignInRequestDto.java +++ b/backend/src/main/java/moviegoods/movie/domain/dto/signin/SignInRequestDto.java @@ -1,14 +1,19 @@ package moviegoods.movie.domain.dto.signin; import lombok.AllArgsConstructor; +import lombok.Builder; import lombok.Data; import lombok.NoArgsConstructor; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; @Data @NoArgsConstructor @AllArgsConstructor +@Component public class SignInRequestDto { private String email; private String password; + private String method; } diff --git a/backend/src/main/java/moviegoods/movie/domain/dto/signup/SignUpRequestDto.java b/backend/src/main/java/moviegoods/movie/domain/dto/signup/SignUpRequestDto.java index d505ef5..fe1334c 100644 --- a/backend/src/main/java/moviegoods/movie/domain/dto/signup/SignUpRequestDto.java +++ b/backend/src/main/java/moviegoods/movie/domain/dto/signup/SignUpRequestDto.java @@ -1,15 +1,19 @@ package moviegoods.movie.domain.dto.signup; import lombok.AllArgsConstructor; +import lombok.Builder; import lombok.Data; import lombok.NoArgsConstructor; +import org.springframework.stereotype.Component; @Data @NoArgsConstructor @AllArgsConstructor +@Component public class SignUpRequestDto { private String email; private String nickname; private String password; + } diff --git a/backend/src/main/java/moviegoods/movie/domain/entity/User/Authority.java b/backend/src/main/java/moviegoods/movie/domain/entity/User/Authority.java index ebb77c0..e34760e 100644 --- a/backend/src/main/java/moviegoods/movie/domain/entity/User/Authority.java +++ b/backend/src/main/java/moviegoods/movie/domain/entity/User/Authority.java @@ -1,5 +1,5 @@ package moviegoods.movie.domain.entity.User; public enum Authority { - 관리자, 일반, normal + 관리자, 일반 } \ No newline at end of file diff --git a/backend/src/main/java/moviegoods/movie/domain/entity/User/Method.java b/backend/src/main/java/moviegoods/movie/domain/entity/User/Method.java new file mode 100644 index 0000000..7b259dd --- /dev/null +++ b/backend/src/main/java/moviegoods/movie/domain/entity/User/Method.java @@ -0,0 +1,5 @@ +package moviegoods.movie.domain.entity.User; + +public enum Method { + 일반, 구글, 카카오 +} diff --git a/backend/src/main/java/moviegoods/movie/domain/entity/User/User.java b/backend/src/main/java/moviegoods/movie/domain/entity/User/User.java index 80f9f5a..ac9964e 100644 --- a/backend/src/main/java/moviegoods/movie/domain/entity/User/User.java +++ b/backend/src/main/java/moviegoods/movie/domain/entity/User/User.java @@ -57,6 +57,10 @@ public class User { @Column(columnDefinition = "tinyint default 1") private Byte status; + @NotNull + @Enumerated(EnumType.STRING) + private Method method; + @OneToMany(mappedBy = "user", cascade = CascadeType.ALL) private List posts = new ArrayList<>(); diff --git a/backend/src/main/java/moviegoods/movie/domain/entity/User/UserRepository.java b/backend/src/main/java/moviegoods/movie/domain/entity/User/UserRepository.java index 7c31d7f..943605e 100644 --- a/backend/src/main/java/moviegoods/movie/domain/entity/User/UserRepository.java +++ b/backend/src/main/java/moviegoods/movie/domain/entity/User/UserRepository.java @@ -9,4 +9,6 @@ public interface UserRepository extends JpaRepository { Optional findById(Long user_id); Optional findByEmail(String email); Optional findByNickname(String nickname); + + Optional findByEmailAndMethod(String email, String method); } diff --git a/backend/src/main/java/moviegoods/movie/service/ChatRoomService.java b/backend/src/main/java/moviegoods/movie/service/ChatRoomService.java index c90bca4..0ff9bca 100644 --- a/backend/src/main/java/moviegoods/movie/service/ChatRoomService.java +++ b/backend/src/main/java/moviegoods/movie/service/ChatRoomService.java @@ -216,4 +216,4 @@ public int compare(DirectMessageListResponseDto responseDto1, DirectMessageListR return result; } } -} +} \ No newline at end of file diff --git a/backend/src/main/java/moviegoods/movie/service/ChatService.java b/backend/src/main/java/moviegoods/movie/service/ChatService.java index 453e9ac..0984200 100644 --- a/backend/src/main/java/moviegoods/movie/service/ChatService.java +++ b/backend/src/main/java/moviegoods/movie/service/ChatService.java @@ -55,22 +55,26 @@ public void saveMessage(User loginUser, DirectMessage message) throws IOExceptio Chat_Room chat_room=chatRoomRepository.findById(message.getChat_room_id()).get(); String content = message.getContent(); + Message saveEntity; - Content_Detail content_detail = contentDetailService.saveContentDetail(content); - Message saveEntity = Message.builder().user(user).content_detail(content_detail).chat_room(chat_room).build(); + String firebaseUrl=""; + if(message.getImage_url()==null){ + Content_Detail content_detail = contentDetailService.saveContentDetail(content); + saveEntity = Message.builder().user(user).content_detail(content_detail).chat_room(chat_room).build(); -// String firebaseUrl=""; -// if(message.getImage_url()==null){ -// content_detail.setContent(message.getContent()); -// }else { -// MultipartFile image_url=message.getImage_url(); -// String nameFile= UUID.randomUUID().toString(); -// fireBaseService.uploadFiles(image_url,nameFile); -// firebaseUrl+="https://firebasestorage.googleapis.com/v0/b/stroagetest-f0778.appspot.com/o/"+nameFile+"?alt=media"; + }else { + + MultipartFile image_url=message.getImage_url(); + String nameFile= UUID.randomUUID().toString(); + log.info("nameFile={}", nameFile); + fireBaseService.uploadFiles(image_url,nameFile); + firebaseUrl+="https://firebasestorage.googleapis.com/v0/b/stroagetest-f0778.appspot.com/o/"+nameFile+"?alt=media"; + + saveEntity = Message.builder().user(user).image_url(firebaseUrl).chat_room(chat_room).build(); // // message1.setImage_url(firebaseUrl); -// } + } // //content_detail.setMessage(message1); diff --git a/backend/src/main/java/moviegoods/movie/service/ManagerService.java b/backend/src/main/java/moviegoods/movie/service/ManagerService.java index f270046..3081c1f 100644 --- a/backend/src/main/java/moviegoods/movie/service/ManagerService.java +++ b/backend/src/main/java/moviegoods/movie/service/ManagerService.java @@ -28,15 +28,24 @@ public List show() { List reports = reportRepository.findAll(); for (Report report : reports) { Content_Detail content_detail = report.getContent_detail(); - String content = content_detail.getContent(); - LocalDateTime written_date = content_detail.getWritten_date(); + String content = content_detail.getContent(); //신고내용 + LocalDateTime written_date = content_detail.getWritten_date(); //신고시간 + User user = report.getUser(); //신고한 사용자 + Long user_id = user.getUser_id(); //신고자 아이디 + String nickname = user.getNickname(); //신고자 닉네임 Transaction transaction = report.getTransaction(); - User user = transaction.getUser(); - String nickname = user.getNickname(); - Long user_id = user.getUser_id(); + User reportedUser = transaction.getUser(); //신고당한 사용자 + String reported_nickname = reportedUser.getNickname(); //신고당한 사용자 닉네임 + Long reported_user_id = reportedUser.getUser_id(); //신고당한 사용자 아이디 + String reported_content = transaction.getContent_detail().getContent(); //신고당한 내용 - reportsList.add(new ManagerResponseDto(content, written_date, nickname, user_id)); + Boolean is_complete = false; + if(reportedUser.getStatus() == 0) { + is_complete = true; + } + + reportsList.add(new ManagerResponseDto(content, written_date, nickname, user_id, reported_user_id, reported_nickname, reported_content, is_complete)); } Comp comp = new Comp(); @@ -80,4 +89,4 @@ public int compare(ManagerResponseDto responseDto1, ManagerResponseDto responseD return result; } } -} +} \ No newline at end of file diff --git a/backend/src/main/java/moviegoods/movie/service/MyPageService.java b/backend/src/main/java/moviegoods/movie/service/MyPageService.java index 56f61d4..8020b1e 100644 --- a/backend/src/main/java/moviegoods/movie/service/MyPageService.java +++ b/backend/src/main/java/moviegoods/movie/service/MyPageService.java @@ -32,11 +32,14 @@ public MyPageResponseSearch search(User loginUser,MyPageRequestSearch mprs){ if (loginUser != null) { user_id = loginUser.getUser_id(); } + User user = userRepository.getById(user_id); + log.info("user_id={}", user_id); + log.info("user_profile={}", loginUser.getProfile_url()); MyPageUser myPageUserDto=new MyPageUser(); - myPageUserDto.setNickname(loginUser.getNickname()); - myPageUserDto.setProfile_url(loginUser.getProfile_url()); - myPageUserDto.setReliability(loginUser.getReliability()); + myPageUserDto.setNickname(user.getNickname()); + myPageUserDto.setProfile_url(user.getProfile_url()); + myPageUserDto.setReliability(user.getReliability()); myPageResponseSearch.setUser(myPageUserDto); diff --git a/backend/src/main/java/moviegoods/movie/service/SignInService.java b/backend/src/main/java/moviegoods/movie/service/SignInService.java index 9d69c0e..ce2f829 100644 --- a/backend/src/main/java/moviegoods/movie/service/SignInService.java +++ b/backend/src/main/java/moviegoods/movie/service/SignInService.java @@ -1,25 +1,37 @@ package moviegoods.movie.service; +import com.google.gson.JsonObject; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; +import moviegoods.movie.configure.ApiKeyConfig; +import moviegoods.movie.configure.GoogleConfigUtils; import moviegoods.movie.domain.dto.signin.SignInRequestDto; import moviegoods.movie.domain.dto.signin.SignInResponseDto; +import moviegoods.movie.domain.dto.signup.SignUpRequestDto; +import moviegoods.movie.domain.entity.User.Method; import moviegoods.movie.domain.entity.User.User; -import moviegoods.movie.domain.entity.User.UserRepository; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.stereotype.Service; import moviegoods.movie.configure.SessionConfig.*; +import javax.persistence.EntityManager; +import javax.persistence.NoResultException; import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import com.google.gson.JsonParser; import com.google.gson.JsonElement; -import org.springframework.stereotype.Service; -import org.springframework.ui.Model; +import org.springframework.web.client.RestTemplate; import java.io.*; import java.net.HttpURLConnection; import java.net.URL; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; @Slf4j @@ -27,16 +39,29 @@ @RequiredArgsConstructor public class SignInService { - private final UserRepository userRepository; private final PasswordEncoder passwordEncoder; + private final SignUpService signUpService; + private final EntityManager em; + private final HttpServletResponse response; + private final GoogleConfigUtils googleConfigUtils; - public SignInResponseDto login(SignInRequestDto requestDto, HttpServletRequest request, Model model) { + public SignInResponseDto login(SignInRequestDto requestDto, HttpServletRequest request) { + SignInResponseDto signInResponseDto; String password = requestDto.getPassword(); String email = requestDto.getEmail(); + String method = requestDto.getMethod(); + + String searchJpql = "select u from user u where u.email = '" + email + "' and u.method = '" + method + "'"; + User user; + try{ + user = em.createQuery(searchJpql, User.class).getSingleResult(); + + }catch (NoResultException e){ + signInResponseDto = new SignInResponseDto(null,null,false); + return signInResponseDto; + } - User user = userRepository.findByEmail(email).orElse(null); String existPassword = user.getPassword(); - SignInResponseDto signInResponseDto; if(passwordEncoder.matches(password, existPassword)) { HttpSession session = request.getSession(); @@ -54,8 +79,10 @@ public SignInResponseDto login(SignInRequestDto requestDto, HttpServletRequest r } public String getKaKaoAccessToken(String code){ + String access_Token=""; String refresh_Token =""; + String reqURL = "https://kauth.kakao.com/oauth/token"; try{ @@ -68,8 +95,8 @@ public String getKaKaoAccessToken(String code){ BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(conn.getOutputStream())); StringBuilder sb = new StringBuilder(); sb.append("grant_type=authorization_code"); - sb.append("&client_id="); // TODO REST_API_KEY 입력 - sb.append("&redirect_uri=http://localhost:8080/app/users/kakao"); // TODO 인가코드 받은 redirect_uri 입력 + sb.append("&client_id=e64599af67aac20483ad02a14a8c5058"); // TODO REST_API_KEY 입력 + sb.append("&redirect_uri=http://localhost:3000/signin/oauth2/code/kakao"); // TODO 인가코드 받은 redirect_uri 입력 sb.append("&code=" + code); bw.write(sb.toString()); bw.flush(); @@ -84,7 +111,6 @@ public String getKaKaoAccessToken(String code){ while ((line = br.readLine()) != null) { result += line; } - System.out.println("response body : " + result); JsonParser parser = new JsonParser(); JsonElement element = parser.parse(result); @@ -92,9 +118,6 @@ public String getKaKaoAccessToken(String code){ access_Token = element.getAsJsonObject().get("access_token").getAsString(); refresh_Token = element.getAsJsonObject().get("refresh_token").getAsString(); - System.out.println("access_token : " + access_Token); - System.out.println("refresh_token : " + refresh_Token); - br.close(); bw.close(); }catch (IOException e) { @@ -104,5 +127,150 @@ public String getKaKaoAccessToken(String code){ return access_Token; } + public SignInRequestDto getUserInfo(String access_Token) { + + String reqURL = "https://kapi.kakao.com/v2/user/me"; + SignInRequestDto signInRequestDto = new SignInRequestDto(); + + try { + URL url = new URL(reqURL); + HttpURLConnection conn = (HttpURLConnection) url.openConnection(); + conn.setRequestMethod("GET"); + + conn.setRequestProperty("Authorization", "Bearer " + access_Token); + + BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream())); + + String line = ""; + String result = ""; + + while ((line = br.readLine()) != null) { + result += line; + } + + JsonParser parser = new JsonParser(); + JsonElement element = parser.parse(result); + + JsonObject properties = element.getAsJsonObject().get("properties").getAsJsonObject(); + JsonObject kakao_account = element.getAsJsonObject().get("kakao_account").getAsJsonObject(); + + String nickname = properties.getAsJsonObject().get("nickname").getAsString(); + String email = kakao_account.getAsJsonObject().get("email").getAsString(); + String password = email + "kakao"; + + SignUpRequestDto signUpRequestDto = new SignUpRequestDto(); + signUpRequestDto.setNickname(nickname); + signUpRequestDto.setEmail(email); + signUpRequestDto.setPassword(password); + String searchJpql = "select u from user u where u.email = '" + email + "' and u.method = '카카오'"; + List user = em.createQuery(searchJpql, User.class).getResultList(); + + if (user.size() == 0) { + signUpService.saveUser(signUpRequestDto, Method.카카오); + } + + signInRequestDto.setEmail(email); + signInRequestDto.setPassword(password); + signInRequestDto.setMethod("카카오"); + + } catch (IOException e) { + e.printStackTrace(); + } + return signInRequestDto; + } + + public void googleRequest() { + String baseUrl = "https://accounts.google.com/o/oauth2/v2/auth"; + + Map params = new HashMap<>(); + params.put("scope", "profile"); + params.put("response_type", "code"); + params.put("client_id", "435089655733-6v1fo661d0dda2ue3ql61420dtquril1.apps.googleusercontent.com"); + params.put("redirect_uri", "http://localhost:8080/signin/auth/google/callback"); + + String parameterString = params.entrySet().stream() + .map(x -> x.getKey() + "=" + x.getValue()) + .collect(Collectors.joining("&")); + + String redirectUrl = baseUrl + "?" + parameterString; + + try { + response.sendRedirect(redirectUrl); + }catch (IOException e) { + e.printStackTrace(); + } + } + + public String googleRequestAccessToken(String code) { + String access_Token = ""; + String refresh_Token =""; + + String reqURL = "https://oauth2.googleapis.com/token"; + try { + URL url = new URL(reqURL); + HttpURLConnection conn = (HttpURLConnection) url.openConnection(); + + conn.setRequestMethod("POST"); + //conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); + conn.setDoOutput(true); + + BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(conn.getOutputStream())); + StringBuilder sb = new StringBuilder(); + sb.append("code=" + code); + sb.append("&client_id=435089655733-6v1fo661d0dda2ue3ql61420dtquril1.apps.googleusercontent.com"); + sb.append("&client_secret=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"); + sb.append("&redirect_uri=http://localhost:8080/signin/auth/google/callback"); + sb.append("grant_type=authorization_code"); + bw.write(sb.toString()); + bw.flush(); + + int responseCode = conn.getResponseCode(); + System.out.println("responseCode : " + responseCode); + +// Map params = new HashMap<>(); +// params.put("code", code); +// params.put("client_id", "435089655733-6v1fo661d0dda2ue3ql61420dtquril1.apps.googleusercontent.com"); +// params.put("client_secret", "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"); +// params.put("redirect_uri", "http://localhost:8080/signin/auth/google/callback"); +// params.put("grant_type", "authorization_code"); +// +// String parameterString = params.entrySet().stream() +// .map(x -> x.getKey() + "=" + x.getValue()) +// .collect(Collectors.joining("&")); + +// BufferedOutputStream bous = new BufferedOutputStream(conn.getOutputStream()); +// bous.write(parameterString.getBytes()); +// bous.flush(); +// bous.close(); + + BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream())); + + String line = ""; + String result = ""; + + while ((line = br.readLine()) != null) { + result += line; + } + + JsonParser parser = new JsonParser(); + JsonElement element = parser.parse(result); + + access_Token = element.getAsJsonObject().get("access_token").getAsString(); + refresh_Token = element.getAsJsonObject().get("refresh_token").getAsString(); + +// if(conn.getResponseCode() == 200) { +// return sb.toString(); +// } +// return "구글 로그인 요청 처리 실패"; + log.info("access_token = {}", access_Token); + br.close(); + bw.close(); + }catch (IOException e) { + throw new IllegalArgumentException("알 수 없는 구글 로그인 Access Token 요청 URL 입니다 :: " + "https://oauth2.googleapis.com/token"); + } + //return googleConfigUtils.requestAccessTokenUsingURL(code); + return access_Token; + + } } \ No newline at end of file diff --git a/backend/src/main/java/moviegoods/movie/service/SignUpService.java b/backend/src/main/java/moviegoods/movie/service/SignUpService.java index fffe66d..65138be 100644 --- a/backend/src/main/java/moviegoods/movie/service/SignUpService.java +++ b/backend/src/main/java/moviegoods/movie/service/SignUpService.java @@ -6,11 +6,15 @@ import moviegoods.movie.domain.dto.signup.SignUpDuplicateCheckRequestDto; import moviegoods.movie.domain.dto.signup.SignUpRequestDto; import moviegoods.movie.domain.entity.User.Authority; +import moviegoods.movie.domain.entity.User.Method; import moviegoods.movie.domain.entity.User.User; import moviegoods.movie.domain.entity.User.UserRepository; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.stereotype.Service; +import static moviegoods.movie.domain.entity.User.Method.일반; +import static moviegoods.movie.domain.entity.User.Method.카카오; + @Slf4j @Service @@ -23,27 +27,32 @@ public class SignUpService { private static Long basicReliability = 0L; private static Byte basicStatus = 1; - public ResultResponseDto saveUser(SignUpRequestDto requestDto) { + public ResultResponseDto saveUser(SignUpRequestDto requestDto, Method method) { String email = requestDto.getEmail(); String nickname = requestDto.getNickname(); String password = requestDto.getPassword(); String encodedPassword = passwordEncoder.encode(password); - User saveEntity = User.builder().authority(Authority.일반).email(email).status(basicStatus).reliability(basicReliability).nickname(nickname).password(encodedPassword).profile_url(basicUrl).build(); - + User saveEntity = new User(); + if (method==일반) { + saveEntity = User.builder().authority(Authority.일반).email(email).status(basicStatus).reliability(basicReliability).nickname(nickname).password(encodedPassword).profile_url(basicUrl).method(일반).build(); + } + if (method==카카오) { + saveEntity = User.builder().authority(Authority.일반).email(email).status(basicStatus).reliability(basicReliability).nickname(nickname).password(encodedPassword).profile_url(basicUrl).method(카카오).build(); + } ResultResponseDto resultResponseDto = new ResultResponseDto(); userRepository.save(saveEntity); resultResponseDto.setResult(true); return resultResponseDto; } - public ResultResponseDto duplicateCheck(SignUpDuplicateCheckRequestDto requestDto) { + public ResultResponseDto duplicateCheck(SignUpDuplicateCheckRequestDto requestDto,Method method) { String email = requestDto.getEmail(); String nickname = requestDto.getNickname(); User user = new User(); if (email != null) { - user = userRepository.findByEmail(email).orElse(null); + user = (User) userRepository.findByEmailAndMethod(email,method.toString()).orElse(null); } if (nickname != null) { user = userRepository.findByNickname(nickname).orElse(null); diff --git a/backend/src/main/resources/application.properties b/backend/src/main/resources/application.properties index 3ac4c15..71019af 100644 --- a/backend/src/main/resources/application.properties +++ b/backend/src/main/resources/application.properties @@ -10,4 +10,10 @@ spring.jpa.properties.hibernate.show-sql=true logging.level.org.hibernate.type.descriptor.sql=DEBUG session.setMaxInactiveInterval(1800); logging.level.org.hibernate.SQL=DEBUG -server.servlet.session.tracking-modes=cookie \ No newline at end of file +server.servlet.session.tracking-modes=cookie + +sns.google.url=https://accounts.google.com/o/oauth2/v2/auth +sns.google.client.id=435089655733-6v1fo661d0dda2ue3ql61420dtquril1.apps.googleusercontent.com +sns.google.client.secret=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 +sns.google.callback.url=http://localhost:8080/signin/auth/google/callback +sns.google.token.url=https://oauth2.googleapis.com/token \ No newline at end of file diff --git a/backend/src/main/resources/application.yml b/backend/src/main/resources/application.yml index fc55256..13a5516 100644 --- a/backend/src/main/resources/application.yml +++ b/backend/src/main/resources/application.yml @@ -4,4 +4,6 @@ spring: pathmatch: - matching-strategy: ant_path_matcher \ No newline at end of file + matching-strategy: ant_path_matcher + + diff --git a/backend/src/main/resources/serviceAccountKey.json b/backend/src/main/resources/serviceAccountKey.json index 4f3546f..e2ecc97 100644 --- a/backend/src/main/resources/serviceAccountKey.json +++ b/backend/src/main/resources/serviceAccountKey.json @@ -9,4 +9,6 @@ "token_uri": "https://oauth2.googleapis.com/token", "auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs", "client_x509_cert_url": "https://www.googleapis.com/robot/v1/metadata/x509/firebase-adminsdk-eylqz%40stroagetest-f0778.iam.gserviceaccount.com" + } +