Skip to content

Commit

Permalink
feat #14 : 카카오 로그인 추가
Browse files Browse the repository at this point in the history
  • Loading branch information
baesunyoung6767 committed Jun 20, 2024
1 parent de513b0 commit aab1b58
Show file tree
Hide file tree
Showing 16 changed files with 166 additions and 7 deletions.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
2 changes: 1 addition & 1 deletion build/resources/main/application.yml
Original file line number Diff line number Diff line change
Expand Up @@ -35,4 +35,4 @@ eureka:
register-with-eureka: true
fetch-registry: true
service-url:
defaultZone: http://sunjoo-server-eureka-eureka-1:8761/eureka/
defaultZone: http://localhost:8761/
1 change: 1 addition & 0 deletions src/main/java/com/sunjoo/auth/domain/UserRepository.java
Original file line number Diff line number Diff line change
Expand Up @@ -9,4 +9,5 @@
public interface UserRepository extends JpaRepository<User, Long> {
Optional<User> findById(String id);
Optional<User> findByUserNo(long userNo);
Optional<User> findByName(String name);
}
Original file line number Diff line number Diff line change
@@ -1,26 +1,32 @@
package com.sunjoo.auth.domain.controller;

import com.sunjoo.auth.domain.dto.KakaoLoginRequestDto;
import com.sunjoo.auth.domain.dto.KakaoLoginResponseDto;
import com.sunjoo.auth.domain.dto.UserRegisterRequestDto;
import com.sunjoo.auth.domain.dto.UserRegisterResponseDto;
import com.sunjoo.auth.domain.service.JwtService;
import com.sunjoo.auth.domain.service.RedisService;
import com.sunjoo.auth.domain.service.UserService;
import com.sunjoo.auth.global.Response;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.*;

import java.sql.SQLException;
import java.util.HashMap;

@RequiredArgsConstructor
@Slf4j
@RestController
public class UserController {
private final UserService userService;
private final JwtService jwtService;
private final RedisService redisService;

@PostMapping("/register")
public ResponseEntity register(@Validated @RequestBody UserRegisterRequestDto registerRequest, BindingResult br) throws SQLException {
Expand All @@ -29,4 +35,26 @@ public ResponseEntity register(@Validated @RequestBody UserRegisterRequestDto re
UserRegisterResponseDto registerResponse = userService.register(registerRequest);
return ResponseEntity.ok(Response.success(registerResponse));
}

@GetMapping("/login/kakao")
public ResponseEntity kakaoLogin(@RequestParam(required = false) String token, HttpServletResponse response) {
try {
KakaoLoginRequestDto kakaoRequest = userService.getKakaoUserInfo(token);

// 카카오 로그인
KakaoLoginResponseDto kakaoResponse = userService.kakaoLogin(kakaoRequest);
String accessToken = jwtService.createAccessToken(kakaoResponse.getUserNo());
String refreshToken = jwtService.createRefreshToken();

jwtService.sendAccessAndRefreshToken(response, accessToken, refreshToken);
redisService.setValues(kakaoResponse.getName(), refreshToken);

// 우리 서버 jwt 넘겨주기
response.setHeader("Authorization", "Bearer " + accessToken);
return ResponseEntity.ok(Response.success(kakaoResponse));
} catch (Exception e) {
e.printStackTrace();
return ResponseEntity.internalServerError().build();
}
}
}
14 changes: 14 additions & 0 deletions src/main/java/com/sunjoo/auth/domain/dto/KakaoLoginRequestDto.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
package com.sunjoo.auth.domain.dto;

import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;

@Getter
@Setter
@AllArgsConstructor
@NoArgsConstructor
public class KakaoLoginRequestDto {
private String name;
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
package com.sunjoo.auth.domain.dto;

import com.sunjoo.auth.domain.User;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;

@Getter
@Setter
@AllArgsConstructor
@NoArgsConstructor
public class KakaoLoginResponseDto {
private long userNo;
private String name;
private String type;

public KakaoLoginResponseDto(User user) {
this.userNo = user.getUserNo();
this.name = user.getName();
this.type = user.getType();
}
}
6 changes: 6 additions & 0 deletions src/main/java/com/sunjoo/auth/domain/service/UserService.java
Original file line number Diff line number Diff line change
@@ -1,8 +1,14 @@
package com.sunjoo.auth.domain.service;

import com.sunjoo.auth.domain.dto.KakaoLoginRequestDto;
import com.sunjoo.auth.domain.dto.KakaoLoginResponseDto;
import com.sunjoo.auth.domain.dto.UserRegisterRequestDto;
import com.sunjoo.auth.domain.dto.UserRegisterResponseDto;

import java.util.HashMap;

public interface UserService {
public UserRegisterResponseDto register(UserRegisterRequestDto registerRequestDto);
public KakaoLoginRequestDto getKakaoUserInfo(String accessToken);
public KakaoLoginResponseDto kakaoLogin(KakaoLoginRequestDto kakaoRequest);
}
74 changes: 74 additions & 0 deletions src/main/java/com/sunjoo/auth/domain/service/UserServiceImpl.java
Original file line number Diff line number Diff line change
@@ -1,7 +1,12 @@
package com.sunjoo.auth.domain.service;

import com.nimbusds.jose.shaded.gson.JsonElement;
import com.nimbusds.jose.shaded.gson.JsonObject;
import com.nimbusds.jose.shaded.gson.JsonParser;
import com.sunjoo.auth.domain.User;
import com.sunjoo.auth.domain.UserRepository;
import com.sunjoo.auth.domain.dto.KakaoLoginRequestDto;
import com.sunjoo.auth.domain.dto.KakaoLoginResponseDto;
import com.sunjoo.auth.domain.dto.UserRegisterRequestDto;
import com.sunjoo.auth.domain.dto.UserRegisterResponseDto;
import com.sunjoo.auth.global.exception.AppException;
Expand All @@ -10,7 +15,16 @@
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.time.LocalDate;
import java.util.HashMap;
import java.util.Optional;

@RequiredArgsConstructor
@Service
Expand All @@ -35,6 +49,66 @@ public UserRegisterResponseDto register(UserRegisterRequestDto registerRequestDt
return new UserRegisterResponseDto(saved);
}

// 카카오 로그인
@Override
public KakaoLoginRequestDto getKakaoUserInfo(String accessToken) {
KakaoLoginRequestDto kakaoRequest = new KakaoLoginRequestDto();
String postURL = "https://kapi.kakao.com/v2/user/me";

try {
URL url = new URL(postURL);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setRequestProperty("Authorization", "Bearer " + accessToken);

int responseCode = conn.getResponseCode();

BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line = "";
StringBuilder result = new StringBuilder();

while((line = br.readLine()) != null) {
result.append(line);
}

JsonElement element = JsonParser.parseString(result.toString());
JsonObject properties = element.getAsJsonObject().get("properties").getAsJsonObject();
JsonObject kakaoAccount = element.getAsJsonObject().get("kakao_account").getAsJsonObject();

String name = properties.getAsJsonObject().get("nickname").getAsString();
kakaoRequest.setName(name);
} catch (Exception e) {
e.printStackTrace();
}
return kakaoRequest;
}

@Override
public KakaoLoginResponseDto kakaoLogin(KakaoLoginRequestDto kakaoRequest) {
KakaoLoginResponseDto kakaoResponse = new KakaoLoginResponseDto();

userRepository.findByName(kakaoRequest.getName()).ifPresentOrElse(
user -> {
kakaoResponse.setUserNo(user.getUserNo());
kakaoResponse.setName(user.getName());
kakaoResponse.setType("KAKAO");
},
() -> {
User newKakaoLogin = userRepository.save(
User.builder()
.name(kakaoRequest.getName())
.type("KAKAO")
.createdAt(LocalDate.now())
.build());
kakaoResponse.setUserNo(newKakaoLogin.getUserNo());
kakaoResponse.setType("KAKAO");
kakaoResponse.setName(newKakaoLogin.getName());
}
);

return kakaoResponse;
}

private void userJoinValid(String id) {
userRepository.findById(id)
.ifPresent(user -> {throw new AppException(ErrorCode.DUPLICATED_USER_ID);});
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -43,11 +43,12 @@ public class SecurityConfig {
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http
.csrf(AbstractHttpConfigurer::disable)
.cors(AbstractHttpConfigurer::disable)
.httpBasic(AbstractHttpConfigurer::disable)
.formLogin(AbstractHttpConfigurer::disable)
.addFilterAfter(jsonIdPasswordAuthenticationFilter(), LogoutFilter.class)
.authorizeHttpRequests((authorize)->authorize
.requestMatchers("/register", "/", "/login").permitAll()
.requestMatchers("/register", "/", "/login/**").permitAll()
// .requestMatchers("/**").access((authentication, context) -> new AuthorizationDecision(hasIpAddress.matches(context.getRequest())))
.anyRequest().authenticated())
// .authorizeHttpRequests((authorize) -> authorize
Expand Down
14 changes: 13 additions & 1 deletion src/main/java/com/sunjoo/auth/global/config/WebConfig.java
Original file line number Diff line number Diff line change
@@ -1,4 +1,16 @@
package com.sunjoo.auth.global.config;

public class WebConfig {
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class WebConfig implements WebMvcConfigurer {

@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedOrigins("*")
.allowedMethods("GET", "POST", "PUT", "DELETE");
}
}

0 comments on commit aab1b58

Please sign in to comment.