Skip to content

Commit

Permalink
feat : 피그마 로그인, 유저 정보 가져오기 구현
Browse files Browse the repository at this point in the history
  • Loading branch information
cowboysj committed Nov 13, 2024
1 parent 13b2033 commit 090d0f2
Show file tree
Hide file tree
Showing 8 changed files with 97 additions and 64 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@ public TokenPairResponse googleSocialLogin(String code) {
}

public UserInfoResponse figmaSocialLogin(String code) {
// final Member currentMember = memberUtil.getCurrentMember();
String accessToken = figmaService.getAccessToken(code);
return figmaService.getUserInfo(accessToken);
}
Expand Down
124 changes: 61 additions & 63 deletions src/main/java/gigedi/dev/domain/auth/application/FigmaService.java
Original file line number Diff line number Diff line change
@@ -1,93 +1,91 @@
package gigedi.dev.domain.auth.application;

import java.time.Duration;
import static gigedi.dev.global.common.constants.SecurityConstants.FIGMA_GET_ID_TOKEN_URL;
import static gigedi.dev.global.common.constants.SecurityConstants.FIGMA_GET_USER_INFO_URL;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.reactive.function.client.WebClient;

import com.fasterxml.jackson.databind.ObjectMapper;

import gigedi.dev.domain.auth.dto.response.FigmaTokenResponse;
import gigedi.dev.domain.auth.dto.response.FigmaUserResponse;
import gigedi.dev.domain.auth.dto.response.UserInfoResponse;
import gigedi.dev.global.error.exception.CustomException;
import gigedi.dev.global.error.exception.ErrorCode;
import gigedi.dev.infra.config.oauth.FigmaProperties;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;

@Service
@Slf4j
@RequiredArgsConstructor
public class FigmaService {

@Value("${figma.client.id}")
private String clientId;

@Value("${figma.client.secret}")
private String clientSecret;

@Value("${figma.redirect.uri}")
private String redirectUri;

private final RestTemplate restTemplate = new RestTemplate();
private final WebClient webClient = WebClient.create();
private final FigmaProperties figmaProperties;
private final RestTemplate restTemplate;

public String getAccessToken(String code) {
String responseBody =
webClient
.post()
.uri("https://www.figma.com/api/oauth/token")
.header("Content-Type", "application/x-www-form-urlencoded")
.bodyValue(
"client_id="
+ "OSEOcfCVk52Uci4uNnFRb9"
+ "&client_secret="
+ "zCW4KZz6VnxAnqDdfrs7OdiMvzUHKo"
+ "&redirect_uri="
+ "http://localhost:3000"
+ "&code="
+ code
+ "&grant_type=authorization_code")
.retrieve()
.bodyToMono(String.class)
.timeout(Duration.ofSeconds(10))
.doOnError(
error ->
System.out.println(
"Error retrieving access token: "
+ error.getMessage()))
.block();
try {
MultiValueMap<String, String> formData = new LinkedMultiValueMap<>();
formData.add("client_id", figmaProperties.getId());
formData.add("client_secret", figmaProperties.getSecret());
formData.add("redirect_uri", figmaProperties.getRedirectUri());
formData.add("code", code);
formData.add("grant_type", "authorization_code");
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);

System.out.println("Response Body: " + responseBody); // 응답 내용 확인
ResponseEntity<String> response =
restTemplate.exchange(
FIGMA_GET_ID_TOKEN_URL,
HttpMethod.POST,
new org.springframework.http.HttpEntity<>(formData, headers),
String.class);

try {
// 응답 JSON을 FigmaTokenResponse로 파싱
String responseBody = response.getBody();
ObjectMapper objectMapper = new ObjectMapper();
FigmaTokenResponse figmaTokenResponse =
objectMapper.readValue(responseBody, FigmaTokenResponse.class);

return figmaTokenResponse.getAccessToken();

} catch (Exception e) {
System.out.println("Error parsing JSON to FigmaTokenResponse: " + e.getMessage());
throw new RuntimeException("Failed to parse response to FigmaTokenResponse", e);
log.error("Figma 로그인 중 예외 발생 : " + e.getMessage(), e);
throw new CustomException(ErrorCode.FIGMA_LOGIN_FAILED);
}
}

public UserInfoResponse getUserInfo(String accessToken) {
return webClient
.get()
.uri("https://api.figma.com/v1/me")
.header("Authorization", "Bearer " + accessToken)
.retrieve()
.bodyToMono(FigmaUserResponse.class)
.map(
figmaUserResponse ->
new UserInfoResponse(
figmaUserResponse.getHandle(),
figmaUserResponse.getEmail(),
figmaUserResponse.getImg_url(),
figmaUserResponse.getId()))
.doOnError(
error -> {
System.out.println("Error retrieving user info: " + error.getMessage());
throw new RuntimeException("Failed to retrieve user info", error);
})
.block();
String userInfoUrl = FIGMA_GET_USER_INFO_URL;
HttpHeaders headers = new HttpHeaders();
headers.setBearerAuth(accessToken);

HttpEntity<String> entity = new HttpEntity<>(headers);

try {
ResponseEntity<FigmaUserResponse> response =
restTemplate.exchange(
userInfoUrl, HttpMethod.GET, entity, FigmaUserResponse.class);
FigmaUserResponse figmaUserResponse = response.getBody();
if (figmaUserResponse == null) {
throw new CustomException(ErrorCode.FIGMA_USER_INFO_NOT_FOUND);
}

return new UserInfoResponse(
figmaUserResponse.getHandle(),
figmaUserResponse.getEmail(),
figmaUserResponse.getImg_url(),
figmaUserResponse.getId());
} catch (Exception e) {
log.error("Figma 유저 정보 조회 중 예외 발생 : " + e.getMessage(), e);
throw new CustomException(ErrorCode.FIGMA_USER_INFO_FAILED);
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,9 @@ public final class SecurityConstants {
public static final String GOOGLE_WITHDRAWAL_URL =
"https://accounts.google.com/o/oauth2/revoke?token=";

public static final String FIGMA_GET_ID_TOKEN_URL = "https://www.figma.com/api/oauth/token";
public static final String FIGMA_GET_USER_INFO_URL = "https://api.figma.com/v1/me";

public static final String TOKEN_ROLE_NAME = "role";
public static final String TOKEN_PREFIX = "Bearer ";
public static final String NONE = "";
Expand Down
5 changes: 5 additions & 0 deletions src/main/java/gigedi/dev/global/config/RestClientConfig.java
Original file line number Diff line number Diff line change
Expand Up @@ -21,4 +21,9 @@ public RestClient restClient() {

return RestClient.create(restTemplate);
}

@Bean
public RestTemplate restTemplate() {
return new RestTemplate();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,9 @@ public enum ErrorCode {

// Figma
FIGMA_NOT_FOUND(HttpStatus.NOT_FOUND, "해당 Figma 정보를 찾을 수 없습니다."),
FIGMA_LOGIN_FAILED(HttpStatus.BAD_REQUEST, "Figma 로그인 과정에서 오류가 발생했습니다."),
FIGMA_USER_INFO_FAILED(HttpStatus.BAD_REQUEST, "피그마 유저 정보를 불러오는 데 실패했습니다."),
FIGMA_USER_INFO_NOT_FOUND(HttpStatus.BAD_REQUEST, "해당 피그마 유저 정보가 없습니다."),

// 추가
GOOGLE_LOGIN_FAILED(HttpStatus.BAD_REQUEST, "구글 로그인 과정에서 오류가 발생했습니다."),
Expand Down
3 changes: 2 additions & 1 deletion src/main/java/gigedi/dev/infra/config/PropertiesConfig.java
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,9 @@
import org.springframework.context.annotation.Configuration;

import gigedi.dev.infra.config.jwt.JwtProperties;
import gigedi.dev.infra.config.oauth.FigmaProperties;
import gigedi.dev.infra.config.oauth.GoogleProperties;

@Configuration
@EnableConfigurationProperties({GoogleProperties.class, JwtProperties.class})
@EnableConfigurationProperties({GoogleProperties.class, JwtProperties.class, FigmaProperties.class})
public class PropertiesConfig {}
16 changes: 16 additions & 0 deletions src/main/java/gigedi/dev/infra/config/oauth/FigmaProperties.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
package gigedi.dev.infra.config.oauth;

import org.springframework.boot.context.properties.ConfigurationProperties;

import lombok.Getter;
import lombok.Setter;

@Getter
@Setter
@ConfigurationProperties(prefix = "oauth.figma.client")
public class FigmaProperties {
private String id;
private String secret;
private String redirectUri;
private String grantType;
}
6 changes: 6 additions & 0 deletions src/main/resources/application-security.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,12 @@ oauth:
secret: ${GOOGLE_CLIENT_SECRET}
redirectUri: ${GOOGLE_REDIRECT_URI}
grantType: ${GOOGLE_GRANT_TYPE}
figma:
client:
id: ${FIGMA_CLIENT_ID}
secret: ${FIGMA_CLIENT_SECRET}
redirectUri: ${FIGMA_REDIRECT_URI}
grantType: ${FIGMA_GRANT_TYPE}

jwt:
access-token-secret: ${JWT_ACCESS_TOKEN}
Expand Down

0 comments on commit 090d0f2

Please sign in to comment.