Skip to content

Commit

Permalink
Merge pull request #73 from Collusic/fix/70_discord_message
Browse files Browse the repository at this point in the history
[#70, #72] 디스코드 에러메세지 미전송 이슈 및 쿠키 이슈 해결
  • Loading branch information
sunghyuki authored Jun 16, 2024
2 parents f46c7ad + 8376e9e commit ea03ba8
Show file tree
Hide file tree
Showing 7 changed files with 57 additions and 152 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -37,15 +37,17 @@ public class AuthController {
private final OAuth2ClientManager oAuth2ClientManager;

@PostMapping("/sign-in")
public ResponseEntity<SignInUpResponse> signIn(@RequestBody @Valid SignInRequest request,
public ResponseEntity<SignInUpResponse> signIn(
@RequestBody @Valid SignInRequest requestBody,
HttpServletRequest request,
HttpServletResponse response) {
OAuth2UserInfoResponse userInfo = oAuth2ClientManager.requestUserInfoFromOAuth2Client(
request.getProviderType(), request.getProviderToken());
requestBody.getProviderType(), requestBody.getProviderToken());
TokenResponse tokenResponse = authService.signIn(userInfo);

CookieUtils.addCookie(response, JwtUtil.ACCESS_TOKEN_NAME, tokenResponse.getAccessToken(),
CookieUtils.addCookie(request, response, JwtUtil.ACCESS_TOKEN_NAME, tokenResponse.getAccessToken(),
JwtUtil.ACCESS_TOKEN_EXP);
CookieUtils.addCookie(response, JwtUtil.REFRESH_TOKEN_NAME, tokenResponse.getRefreshToken(),
CookieUtils.addCookie(request, response, JwtUtil.REFRESH_TOKEN_NAME, tokenResponse.getRefreshToken(),
JwtUtil.REFRESH_TOKEN_EXP);

MemberInfo memberInfo = authService.findMemberInfo(userInfo);
Expand All @@ -61,17 +63,19 @@ public ResponseEntity<SignInUpResponse> signIn(@RequestBody @Valid SignInRequest
}

@PostMapping("/sign-up")
public ResponseEntity<SignInUpResponse> signUp(@RequestBody @Valid final SignUpRequest request,
public ResponseEntity<SignInUpResponse> signUp(
@RequestBody @Valid final SignUpRequest requestBody,
HttpServletRequest request,
HttpServletResponse response) {
OAuth2UserInfoResponse userInfoFromProvider = oAuth2ClientManager.requestUserInfoFromOAuth2Client(
request.getProviderType(), request.getProviderToken());
MemberInfo memberInfo = authService.signUp(request, userInfoFromProvider);
requestBody.getProviderType(), requestBody.getProviderToken());
MemberInfo memberInfo = authService.signUp(requestBody, userInfoFromProvider);
TokenResponse tokenResponse = authService.issueToken(memberInfo.getAuthId(),
memberInfo.getProviderType(), memberInfo.getNickname());

CookieUtils.addCookie(response, "accessToken", tokenResponse.getAccessToken(),
CookieUtils.addCookie(request, response, "accessToken", tokenResponse.getAccessToken(),
JwtUtil.ACCESS_TOKEN_EXP);
CookieUtils.addCookie(response, "refreshToken", tokenResponse.getRefreshToken(),
CookieUtils.addCookie(request, response, "refreshToken", tokenResponse.getRefreshToken(),
JwtUtil.REFRESH_TOKEN_EXP);

return ResponseEntity.ok().body(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,11 @@
import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.Arrays;
import java.util.Optional;
import org.apache.tomcat.util.descriptor.web.Constants;

// [reference] https://velog.io/@cutepassions/spring-security-%EC%84%A4%EC%A0%95-3-cookie
public class CookieUtils {
Expand All @@ -18,11 +21,30 @@ public static Optional<Cookie> getCookie(HttpServletRequest request, String name
return Arrays.stream(cookies).filter(cookie -> cookie.getName().equals(name)).findAny();
}

public static void addCookie(HttpServletResponse response, String name, String value, int maxAge) {
public static void addCookie(HttpServletRequest request, HttpServletResponse response, String name, String value, int maxAge) {
Cookie cookie = new Cookie(name, value);

String origin = request.getHeader("Origin");
String domain = null;

if (origin != null) {
try {
URI originUri = new URI(origin);
domain = originUri.getHost();
} catch (URISyntaxException e) {
e.printStackTrace();
}
}

if (domain != null && !domain.equals("localhost")) {
cookie.setDomain(domain);
}

cookie.setSecure(true);
cookie.setPath("/");
cookie.setHttpOnly(true);
cookie.setMaxAge(maxAge);
cookie.setAttribute(Constants.COOKIE_SAME_SITE_ATTR, "None");
response.addCookie(cookie);
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -100,9 +100,9 @@ private Authentication authenticateWithRefreshToken(HttpServletRequest request,

TokenResponse tokenResponse = tokenService.issue(authId, providerType, nickname);

CookieUtils.addCookie(response, JwtUtil.ACCESS_TOKEN_NAME,
CookieUtils.addCookie(request, response, JwtUtil.ACCESS_TOKEN_NAME,
tokenResponse.getAccessToken(), JwtUtil.ACCESS_TOKEN_EXP);
CookieUtils.addCookie(response, JwtUtil.REFRESH_TOKEN_NAME,
CookieUtils.addCookie(request, response, JwtUtil.REFRESH_TOKEN_NAME,
tokenResponse.getRefreshToken(), JwtUtil.REFRESH_TOKEN_EXP);

// TODO authentication 절차 추후 리팩토링 예정
Expand Down
14 changes: 12 additions & 2 deletions src/main/java/com/climingo/climingoApi/message/DiscordClient.java
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,12 @@

import static org.apache.commons.codec.CharEncoding.UTF_8;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.http.entity.ContentType;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.web.client.RestTemplate;

public class DiscordClient {
Expand All @@ -21,10 +23,18 @@ public static DiscordClient getInstance() {
public void send(String url, DiscordMessage discordMessage) {
try {
HttpHeaders headers = new HttpHeaders();
headers.add(HttpHeaders.CONTENT_TYPE, String.valueOf(ContentType.APPLICATION_JSON));
headers.setContentType(MediaType.APPLICATION_JSON);
headers.add(HttpHeaders.ACCEPT_ENCODING, UTF_8);

HttpEntity<String> requestEntity = new HttpEntity<>(discordMessage.toJson(), headers);
// ObjectMapper를 사용하여 DiscordMessage 객체를 JSON 문자열로 변환
ObjectMapper objectMapper = new ObjectMapper();
String jsonMessage = objectMapper.writeValueAsString(discordMessage);

// HttpEntity 객체 생성
HttpEntity<String> requestEntity = new HttpEntity<>(jsonMessage, headers);


// HttpEntity<DiscordMessage> requestEntity = new HttpEntity<>(discordMessage, headers);

RestTemplate restTemplate = new RestTemplate();
restTemplate.exchange(url, HttpMethod.POST, requestEntity, Void.class);
Expand Down
137 changes: 3 additions & 134 deletions src/main/java/com/climingo/climingoApi/message/DiscordMessage.java
Original file line number Diff line number Diff line change
@@ -1,18 +1,15 @@
package com.climingo.climingoApi.message;

import java.awt.Color;
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import lombok.Builder;
import lombok.Getter;

// Reference: https://gist.github.com/k3kdude/fba6f6b37594eae3d6f9475330733bdb#file-discordwebhook-java

@Getter
public class DiscordMessage {

private String content;
Expand All @@ -35,102 +32,13 @@ public DiscordMessage(String content, String username, String avatarUrl, boolean
this.embeds = embeds;
}

public String toJson() {
if (this.content == null && this.embeds.isEmpty()) {
throw new IllegalArgumentException("Set content or add at least one EmbedObject");
}

EmbedObject.JSONObject json = new EmbedObject.JSONObject();

json.put("content", this.content);
json.put("username", this.username);
json.put("avatar_url", this.avatarUrl);
json.put("tts", this.tts);

if (!this.embeds.isEmpty()) {
List<EmbedObject.JSONObject> embedObjects = new ArrayList<>();

for (EmbedObject embed : this.embeds) {
EmbedObject.JSONObject jsonEmbed = new EmbedObject.JSONObject();

jsonEmbed.put("title", embed.getTitle());
jsonEmbed.put("description", embed.getDescription());
jsonEmbed.put("url", embed.getUrl());

if (embed.getColor() != null) {
Color color = embed.getColor();
int rgb = color.getRed();
rgb = (rgb << 8) + color.getGreen();
rgb = (rgb << 8) + color.getBlue();

jsonEmbed.put("color", rgb);
}

EmbedObject.Footer footer = embed.getFooter();
EmbedObject.Image image = embed.getImage();
EmbedObject.Thumbnail thumbnail = embed.getThumbnail();
EmbedObject.Author author = embed.getAuthor();
List<EmbedObject.Field> fields = embed.getFields();

if (footer != null) {
EmbedObject.JSONObject jsonFooter = new EmbedObject.JSONObject();

jsonFooter.put("text", footer.text);
jsonFooter.put("icon_url", footer.iconUrl);
jsonEmbed.put("footer", jsonFooter);
}

if (image != null) {
EmbedObject.JSONObject jsonImage = new EmbedObject.JSONObject();

jsonImage.put("url", image.url);
jsonEmbed.put("image", jsonImage);
}

if (thumbnail != null) {
EmbedObject.JSONObject jsonThumbnail = new EmbedObject.JSONObject();

jsonThumbnail.put("url", thumbnail.url);
jsonEmbed.put("thumbnail", jsonThumbnail);
}

if (author != null) {
EmbedObject.JSONObject jsonAuthor = new EmbedObject.JSONObject();

jsonAuthor.put("name", author.name);
jsonAuthor.put("url", author.url);
jsonAuthor.put("icon_url", author.iconUrl);
jsonEmbed.put("author", jsonAuthor);
}

List<EmbedObject.JSONObject> jsonFields = new ArrayList<>();
for (EmbedObject.Field field : fields) {
EmbedObject.JSONObject jsonField = new EmbedObject.JSONObject();

jsonField.put("name", field.name);
jsonField.put("value", field.value);
jsonField.put("inline", field.inline);

jsonFields.add(jsonField);
}

jsonEmbed.put("fields", jsonFields.toArray());
embedObjects.add(jsonEmbed);
}

json.put("embeds", embedObjects.toArray());
}

return json.toString();
}

@Getter
public static class EmbedObject {

private String title;
private String description;
private String url;
private Color color;
private int color;

private Footer footer;
private Thumbnail thumbnail;
Expand All @@ -151,49 +59,10 @@ void put(String key, Object value) {
map.put(key, value);
}
}

@Override
public String toString() {
StringBuilder builder = new StringBuilder();
Set<Entry<String, Object>> entrySet = map.entrySet();
builder.append("{");

int i = 0;
for (Map.Entry<String, Object> entry : entrySet) {
Object val = entry.getValue();
builder.append(quote(entry.getKey())).append(":");

if (val instanceof String) {
builder.append(quote(String.valueOf(val)));
} else if (val instanceof Integer) {
builder.append(Integer.valueOf(String.valueOf(val)));
} else if (val instanceof Boolean) {
builder.append(val);
} else if (val instanceof JSONObject) {
builder.append(val.toString());
} else if (val.getClass().isArray()) {
builder.append("[");
int len = Array.getLength(val);
for (int j = 0; j < len; j++) {
builder.append(Array.get(val, j).toString())
.append(j != len - 1 ? "," : "");
}
builder.append("]");
}

builder.append(++i == entrySet.size() ? "}" : ",");
}

return builder.toString();
}
}

private static String quote(String string) {
return "\"" + string + "\"";
}

@Builder
public EmbedObject(String title, String description, String url, Color color, Footer footer,
public EmbedObject(String title, String description, String url, int color, Footer footer,
Thumbnail thumbnail, Image image, Author author, List<Field> fields) {
this.title = title;
this.description = description;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,8 @@

import com.climingo.climingoApi.message.DiscordMessage;
import com.climingo.climingoApi.message.DiscordMessage.EmbedObject;
import java.awt.Color;
import java.util.List;
import java.util.Optional;
import lombok.Builder;
import lombok.Getter;

Expand All @@ -20,15 +20,15 @@ public class ErrorAlertMessage {

public DiscordMessage toDiscordMessage() {
EmbedObject embed = EmbedObject.builder()
.color(Color.RED)
.color(16711680)
.build();
embed
.addField("요청 시간", this.requestTime, false)
.addField("REQUEST QUERY",this.requestQuery, false)
.addField("REQUEST ENDPOINT", this.requestUrl, false)
.addField("REQUEST IP", this.requestIp, false)
.addField("REQUEST DATA", this.requestData, false)
.addField("에러 내용", this.errorMessage, false);
.addField("에러 내용", Optional.ofNullable(this.errorMessage).orElse("null"), false);

return DiscordMessage.builder()
.content("서버 에러 발생.. :cry: :pray:")
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ private ErrorAlertMessage createAlertMessage(Exception e, HttpServletRequest req
.requestTime(requestTime)
.requestIp(originalDomain)
.requestUrl("[" + request.getMethod() + "] " + request.getRequestURL())
.requestQuery(request.getQueryString() == null ? "" : request.getQueryString())
.requestQuery(request.getQueryString() == null ? "null" : request.getQueryString())
.requestData(requestBody.toString())
.errorMessage(e.getMessage())
.build();
Expand Down

0 comments on commit ea03ba8

Please sign in to comment.