Skip to content

Commit

Permalink
[#23]Feat: 구글 소셜로그인 기능 구현
Browse files Browse the repository at this point in the history
  • Loading branch information
EveKristinLee committed Mar 4, 2022
1 parent 71f188a commit 8e3872c
Show file tree
Hide file tree
Showing 21 changed files with 480 additions and 52 deletions.
1 change: 1 addition & 0 deletions backend/.gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ build/
!**/src/main/**/build/
!**/src/test/**/build/
application-aws.properties
chromedriver1
### STS ###
.apt_generated
.classpath
Expand Down
21 changes: 21 additions & 0 deletions backend/src/main/java/moviegoods/movie/configure/ApiKeyConfig.java
Original file line number Diff line number Diff line change
@@ -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;
}


}
Original file line number Diff line number Diff line change
@@ -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<String, Object> 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<String, Object> 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<String> 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 "구글 로그인 요청 처리 실패";
// }
}
Original file line number Diff line number Diff line change
Expand Up @@ -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);
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -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;
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}
Original file line number Diff line number Diff line change
@@ -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;

}
Original file line number Diff line number Diff line change
@@ -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;


}
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
package moviegoods.movie.domain.entity.User;

public enum Authority {
관리자, 일반, normal
관리자, 일반
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
package moviegoods.movie.domain.entity.User;

public enum Method {
일반, 구글, 카카오
}
Original file line number Diff line number Diff line change
Expand Up @@ -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<Post> posts = new ArrayList<>();

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,4 +9,6 @@ public interface UserRepository extends JpaRepository<User, Long> {
Optional<User> findById(Long user_id);
Optional<User> findByEmail(String email);
Optional<User> findByNickname(String nickname);

Optional<Object> findByEmailAndMethod(String email, String method);
}
Original file line number Diff line number Diff line change
Expand Up @@ -216,4 +216,4 @@ public int compare(DirectMessageListResponseDto responseDto1, DirectMessageListR
return result;
}
}
}
}
Loading

0 comments on commit 8e3872c

Please sign in to comment.