Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. Weโ€™ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feature/kakao login #16

Merged
merged 7 commits into from
Apr 28, 2022
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 6 additions & 1 deletion build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -21,10 +21,15 @@ repositories {
dependencies {
developmentOnly 'org.springframework.boot:spring-boot-devtools'
implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
// implementation 'org.springframework.boot:spring-boot-starter-security'
// Spring Security
implementation 'org.springframework.boot:spring-boot-starter-security'
implementation 'org.springframework.boot:spring-boot-starter-validation'
implementation 'org.springframework.boot:spring-boot-starter-jdbc'
implementation 'org.springframework.boot:spring-boot-starter-web'
// JSON Parser
implementation group: 'com.googlecode.json-simple', name: 'json-simple', version: '1.1.1'
// implementation 'org.springframework.boot:spring-boot-starter-oauth2-client'
implementation 'org.springframework.session:spring-session-jdbc'
compileOnly 'org.projectlombok:lombok'
runtimeOnly 'com.h2database:h2:1.4.200'
runtimeOnly 'org.mariadb.jdbc:mariadb-java-client'
Expand Down
20 changes: 20 additions & 0 deletions src/main/java/com/ajou/travely/config/CorsConfig.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
package com.ajou.travely.config;

import org.springframework.context.annotation.Bean;
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 CorsConfig implements WebMvcConfigurer {
@Bean
public WebMvcConfigurer corsConfigurer() {
return new WebMvcConfigurer() {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**").allowedOrigins("http://localhost:3000")
.allowCredentials(true);
}
};
}
}
13 changes: 13 additions & 0 deletions src/main/java/com/ajou/travely/config/RestTemplateConfig.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
package com.ajou.travely.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.client.RestTemplate;

@Configuration
public class RestTemplateConfig {
@Bean
public RestTemplate restTemplate() {
return new RestTemplate();
}
}
19 changes: 19 additions & 0 deletions src/main/java/com/ajou/travely/config/SecurityConfig.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
package com.ajou.travely.config;

import lombok.RequiredArgsConstructor;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;

@RequiredArgsConstructor
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable();
http.authorizeRequests()
.antMatchers("/**").permitAll();
}
}
18 changes: 18 additions & 0 deletions src/main/java/com/ajou/travely/controller/auth/AuthController.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
package com.ajou.travely.controller.auth;

import com.ajou.travely.service.AuthService;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequiredArgsConstructor
public class AuthController {
private final AuthService authService;

@GetMapping("/oauth2/authorization/kakao")
public String login(@RequestParam("code") String code) {
return authService.kakaoAuthentication(code);
}
}
13 changes: 13 additions & 0 deletions src/main/java/com/ajou/travely/domain/AuthorizationKakao.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
package com.ajou.travely.domain;

import lombok.Getter;

@Getter
public class AuthorizationKakao {
private String access_token;
private String token_type;
private String refresh_token;
private String expires_in;
private String scope;
private String refresh_token_expires_in;
}
6 changes: 3 additions & 3 deletions src/main/java/com/ajou/travely/domain/Post.java
Original file line number Diff line number Diff line change
Expand Up @@ -13,15 +13,15 @@ public class Post {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "post_id")
private final Long id;
private Long id;

@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "schedule_id")
private final Schedule schedule;
private Schedule schedule;

@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "user_id")
private final User user;
private User user;

@Column(columnDefinition = "TEXT")
private String text;
Expand Down
4 changes: 4 additions & 0 deletions src/main/java/com/ajou/travely/domain/user/User.java
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;

import lombok.Builder;
import lombok.Getter;
import lombok.NoArgsConstructor;

Expand Down Expand Up @@ -39,6 +41,8 @@ public class User {
@Enumerated(EnumType.STRING)
private Mbti mbti;

private Long kakaoId;

private LocalDate birthday;

}
6 changes: 6 additions & 0 deletions src/main/java/com/ajou/travely/repository/UserRepository.java
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,12 @@

import com.ajou.travely.domain.user.User;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;

import java.util.Optional;

public interface UserRepository extends JpaRepository<User, Long> {
@Query("select u from User u where u.kakaoId = :kakaoId")
public Optional<User> findByKakaoId(@Param("kakaoId") Long kakaoId);
}
20 changes: 20 additions & 0 deletions src/main/java/com/ajou/travely/service/AuthService.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
package com.ajou.travely.service;

import com.ajou.travely.domain.AuthorizationKakao;
import lombok.RequiredArgsConstructor;
import org.json.simple.JSONObject;
import org.springframework.stereotype.Service;

@Service
@RequiredArgsConstructor
public class AuthService {
private final Oauth2Service oauth2Service;

public String kakaoAuthentication(String code) {
AuthorizationKakao authorizationKakao = oauth2Service.callTokenApi(code);
JSONObject userInfoFromKakao = oauth2Service.callGetUserByAccessToken(authorizationKakao.getAccess_token());
Long kakaoId = (Long) userInfoFromKakao.get("id");
String result = oauth2Service.setSessionOrRedirectToSignUp(kakaoId);
return result;
}
}
147 changes: 147 additions & 0 deletions src/main/java/com/ajou/travely/service/Oauth2Service.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,147 @@
package com.ajou.travely.service;

import com.ajou.travely.domain.AuthorizationKakao;
import com.ajou.travely.domain.user.User;
import com.ajou.travely.repository.UserRepository;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.RequiredArgsConstructor;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestTemplate;

import java.util.Collection;
import java.util.Optional;

@Service
@RequiredArgsConstructor
public class Oauth2Service {
private final UserRepository userRepository;
private final RestTemplate restTemplate;
private final ObjectMapper objectMapper;
@Value("${auth.kakaoOauth2ClinetId}")
private final String kakaoOauth2ClinetId;
@Value("${auth.frontendRedirectUrl}")
private final String frontendRedirectUrl;

public AuthorizationKakao callTokenApi(String code) {
String grantType = "authorization_code";

HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);

MultiValueMap<String, String> params = new LinkedMultiValueMap<>();
params.add("grant_type", grantType);
params.add("client_id", kakaoOauth2ClinetId);
params.add("redirect_uri", frontendRedirectUrl + "oauth/kakao/callback");
params.add("code", code);

HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<>(params, headers);
System.out.println("request.getBody() = " + request.getBody());
String url = "https://kauth.kakao.com/oauth/token";
try {
ResponseEntity<String> response = restTemplate.postForEntity(url, request, String.class);
System.out.println("response.getBody() = " + response.getBody());
System.out.println("response.getHeaders() = " + response.getHeaders());
AuthorizationKakao authorization = objectMapper.readValue(response.getBody(), AuthorizationKakao.class);

return authorization;
} catch (RestClientException | JsonProcessingException ex) {
ex.printStackTrace();
throw new RestClientException("error");
}
}

public JSONObject callGetUserByAccessToken(String accessToken) {
HttpHeaders headers = new HttpHeaders();
headers.set("Authorization", "Bearer " + accessToken);
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);

MultiValueMap<String, String> params = new LinkedMultiValueMap<>();
HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<>(params, headers);

String url = "https://kapi.kakao.com/v2/user/me";
try {
ResponseEntity<String> response = restTemplate.postForEntity(url, request, String.class);
// SecurityContext context = SecurityContextHolder.getContext();
JSONObject userInfo = StringToJson(response.getBody());
// System.out.println("userInfo.get(\"id\") = " + userInfo.get("id"));
// JSONObject properties = (JSONObject) userInfo.get("properties");
// System.out.println("properties.get(\"nickname\") = " + properties.get("nickname"));
// Long kakaoId = (Long) userInfo.get("id");
// context.setAuthentication(new CustomAuthentication(kakaoId));
return userInfo;
}catch (RestClientException | ParseException ex) {
ex.printStackTrace();
throw new RestClientException("error");
}
}

public String setSessionOrRedirectToSignUp(Long kakaoId) {
Optional<User> user = userRepository.findByKakaoId(kakaoId);
if(user.isPresent()) {
return "ํšŒ์›๊ฐ€์ž…์ด ํ•„์š”ํ•œ ์ƒํƒœ";
} else {
SecurityContext context = SecurityContextHolder.getContext();
User exUser = user.get();
context.setAuthentication(new Authentication() {
@Override
public Collection<? extends GrantedAuthority> getAuthorities() {
return null;
}
// ๊ถŒํ•œ ์ถ”๊ฐ€
@Override
public Object getCredentials() {
return null;
}

@Override
public Object getDetails() {
return kakaoId;
}

@Override
public Object getPrincipal() {
return null;
}

@Override
public boolean isAuthenticated() {
return true;
}

@Override
public void setAuthenticated(boolean isAuthenticated) throws IllegalArgumentException {

}

@Override
public String getName() {
return null;
}
});
return "์„ธ์…˜ ์ €์žฅ ์™„๋ฃŒ";
}
}
public JSONObject StringToJson(String userInfo) throws ParseException {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

๋ฉ”์†Œ๋“œ๋ช…์€ ์†Œ๋ฌธ์ž๋กœ ์‹œ์ž‘ํ•˜๋Š”๊ฒŒ ์ข‹์„ ๊ฒƒ ๊ฐ™์•„์š”!

JSONParser jsonParser = new JSONParser();
Object object = jsonParser.parse(userInfo);
JSONObject jsonObject = (JSONObject) object;
return jsonObject;
}

}
13 changes: 7 additions & 6 deletions src/main/resources/application.yml
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
spring:
datasource:
url: jdbc:mariadb://localhost:3306/travely
username: root
password: password
driver-class-name: org.mariadb.jdbc.Driver
# datasource:
# url: jdbc:mariadb://localhost:3306/travely
# username: root
# password: password
# driver-class-name: org.mariadb.jdbc.Driver

jpa:
hibernate:
Expand All @@ -13,7 +13,8 @@ spring:
show_sql: true
format_sql: true
profiles:
active: default
include:
- "auth"

logging:
level:
Expand Down
37 changes: 37 additions & 0 deletions src/test/java/com/ajou/travely/service/Oauth2ServiceTest.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
package com.ajou.travely.service;

import com.ajou.travely.domain.user.Type;
import com.ajou.travely.domain.user.User;
import com.ajou.travely.repository.UserRepository;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import static org.assertj.core.api.AssertionsForClassTypes.assertThat;
import static org.junit.jupiter.api.Assertions.*;

@SpringBootTest
class Oauth2ServiceTest {
@Autowired
private UserRepository userRepository;
@Autowired
private Oauth2Service oauth2Service;

@Test
void testWhetherUserExists() {
User user = new User();
Long kakaoId = 123456789L;
user.setType(Type.USER);
user.setEmail("[email protected]");
user.setName("ํ…Œ์ŠคํŠธ");
user.setPhoneNumber("01001000100");
user.setSex("MAN");
user.setKakaoId(kakaoId);
userRepository.save(user);

String s1 = oauth2Service.setSessionOrRedirectToSignUp(kakaoId);
String s2 = oauth2Service.setSessionOrRedirectToSignUp(123L);

assertThat(s1).isEqualTo("์„ธ์…˜ ์ €์žฅ ์™„๋ฃŒ");
assertThat(s2).isEqualTo("ํšŒ์›๊ฐ€์ž…์ด ํ•„์š”ํ•œ ์ƒํƒœ");
}
}