Skip to content
This repository has been archived by the owner on Oct 20, 2024. It is now read-only.

Commit

Permalink
Merge pull request #55 from FinFellows/develop
Browse files Browse the repository at this point in the history
[DEPLOY]: 중간 배포
  • Loading branch information
sejineer authored Jan 7, 2024
2 parents b600fb9 + 8f59b4d commit 8ddb75f
Show file tree
Hide file tree
Showing 28 changed files with 417 additions and 94 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,7 @@ public TokenMapping createToken(Authentication authentication) {
.setSubject(Long.toString(userPrincipal.getId()))
.setIssuedAt(new Date())
.setExpiration(accessTokenExpiresIn)
.claim("role", userPrincipal.getRole())
.signWith(key, SignatureAlgorithm.HS512)
.compact();

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
import com.finfellows.global.error.DefaultAuthenticationException;
import com.finfellows.global.payload.ErrorCode;
import com.finfellows.global.payload.Message;
import com.finfellows.global.payload.ResponseCustom;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
Expand Down Expand Up @@ -211,6 +212,7 @@ public AuthRes kakaoLogin(KakaoProfile kakaoProfile) {
return AuthRes.builder()
.accessToken(tokenMapping.getAccessToken())
.refreshToken(token.getRefreshToken())
.role(Role.USER)
.build();
}

Expand Down Expand Up @@ -310,7 +312,11 @@ public ResponseEntity<?> refresh(RefreshTokenReq refreshTokenReq) {
Token updateToken = token.get().updateRefreshToken(tokenMapping.getRefreshToken());
tokenRepository.save(updateToken);

AuthRes authResponse = AuthRes.builder().accessToken(tokenMapping.getAccessToken()).refreshToken(updateToken.getRefreshToken()).build();
AuthRes authResponse = AuthRes.builder()
.accessToken(tokenMapping.getAccessToken())
.refreshToken(updateToken.getRefreshToken())
.role(Role.ADMIN)
.build();

return ResponseEntity.ok(authResponse);
}
Expand All @@ -331,4 +337,10 @@ private boolean valid(String refreshToken) {

return true;
}

public ResponseCustom<?> whoAmI(UserPrincipal userPrincipal) {
Optional<User> user = userRepository.findById(userPrincipal.getId());
DefaultAssert.isOptionalPresent(user);
return ResponseCustom.OK(user);
}
}
7 changes: 6 additions & 1 deletion src/main/java/com/finfellows/domain/auth/dto/AuthRes.java
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
package com.finfellows.domain.auth.dto;

import com.finfellows.domain.user.domain.Role;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Builder;
import lombok.Data;
Expand All @@ -16,10 +17,14 @@ public class AuthRes {
@Schema( type = "string", example ="Bearer", description="권한(Authorization) 값 해더의 명칭을 지정합니다.")
private String tokenType = "Bearer";

@Schema( type = "Role", example = "USER", description = "Role을 출력합니다.")
private Role role;


@Builder
public AuthRes(String accessToken, String refreshToken) {
public AuthRes(String accessToken, String refreshToken, Role role) {
this.accessToken = accessToken;
this.refreshToken = refreshToken;
this.role = role;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
import com.finfellows.domain.auth.dto.KakaoProfile;
import com.finfellows.domain.auth.dto.RefreshTokenReq;
import com.finfellows.domain.auth.dto.TokenMapping;
import com.finfellows.domain.user.domain.User;
import com.finfellows.global.config.security.token.CurrentUser;
import com.finfellows.global.config.security.token.UserPrincipal;
import com.finfellows.global.payload.ErrorResponse;
Expand Down Expand Up @@ -34,14 +35,27 @@ public class AuthController {

private final KakaoService kakaoService;

@Operation(summary = "카카오 code 발급", description = "카카오 API 서버에 접근 권한을 인가하는 code를 발급받습니다.")

// @Operation(summary = "카카오 code 발급", description = "카카오 API 서버에 접근 권한을 인가하는 code를 발급받습니다.")
// @ApiResponses(value = {
// @ApiResponse(responseCode = "200", description = "code 발급 성공", content = {@Content(mediaType = "application/json", schema = @Schema(implementation = AuthRes.class))}),
// @ApiResponse(responseCode = "400", description = "code 발급 실패", content = {@Content(mediaType = "application/json", schema = @Schema(implementation = ErrorResponse.class))}),
// })
// @GetMapping(value = "/login")
// public void socialLoginRedirect() throws IOException {
// kakaoService.accessRequest();
// }

@Operation(summary = "유저 정보 확인", description = "현재 접속 중인 유저의 정보를 확인합니다.")
@ApiResponses(value = {
@ApiResponse(responseCode = "200", description = "code 발급 성공", content = {@Content(mediaType = "application/json", schema = @Schema(implementation = AuthRes.class))}),
@ApiResponse(responseCode = "400", description = "code 발급 실패", content = {@Content(mediaType = "application/json", schema = @Schema(implementation = ErrorResponse.class))}),
@ApiResponse(responseCode = "200", description = "유저 확인 성공", content = { @Content(mediaType = "application/json", schema = @Schema(implementation = User.class) ) } ),
@ApiResponse(responseCode = "400", description = "유저 확인 실패", content = { @Content(mediaType = "application/json", schema = @Schema(implementation = ErrorResponse.class) ) } ),
})
@GetMapping(value = "/login")
public void socialLoginRedirect() throws IOException {
kakaoService.accessRequest();
@GetMapping
public ResponseCustom<?> whoAmI(
@Parameter(description = "AccessToken을 입력해주세요.", required = true) @CurrentUser UserPrincipal userPrincipal
) {
return kakaoService.whoAmI(userPrincipal);
}

@Operation(summary = "카카오 로그인", description = "카카오 로그인을 수행합니다.")
Expand All @@ -62,7 +76,7 @@ public ResponseCustom<?> kakaoCallback(
}


@Operation(summary = "관리자 로그인", description = "관리자 권한으로 로그인을 수행합니다.")
@Operation(summary = "관리자 회원가입", description = "관리자 권한으로 로그인을 수행합니다.")
@ApiResponses(value = {
@ApiResponse(responseCode = "200", description = "로그인 성공", content = {@Content(mediaType = "application/json", schema = @Schema(implementation = AuthRes.class))}),
@ApiResponse(responseCode = "400", description = "로그인 실패", content = {@Content(mediaType = "application/json", schema = @Schema(implementation = ErrorResponse.class))}),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,20 +10,23 @@
@Data
public class PolicyInfoBookmarkRes {
private Long id;
private String url;
private String contentName;
private String content;


@Builder
public PolicyInfoBookmarkRes(Long id, String url) {
this.id = id;
this.url = url;
public PolicyInfoBookmarkRes(String contentName, String content) {
this.contentName = contentName;
this.content = content;
}



public static List<PolicyInfoBookmarkRes> toDto(List<PolicyInfoBookmark> bookmarks) {
return bookmarks.stream()
.map(bookmark -> PolicyInfoBookmarkRes.builder()
.id(bookmark.getPolicyInfo().getId())
.url(bookmark.getPolicyInfo().getUrl())
.contentName(bookmark.getPolicyInfo().getContentName())
.content(bookmark.getPolicyInfo().getContent())
.build())
.collect(Collectors.toList());
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,46 +14,24 @@ public class ChatGptService {

@Value("${chatgpt.api-key}")
private String apiKey;
// private final ObjectMapper objectMapper = new ObjectMapper()
// .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)
// .setPropertyNamingStrategy(PropertyNamingStrategies.SNAKE_CASE );
// public Flux<String> ask(ChatgptQuestionRequest chatGptQuestionRequest) throws JsonProcessingException {
// WebClient client = WebClient.builder()
// .baseUrl(ChatgptConfig.CHAT_URL)
// .defaultHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE)
// .defaultHeader(ChatgptConfig.AUTHORIZATION, ChatgptConfig.BEARER + apiKey)
// .build();
//
// List<ChatGptMessage> messages = new ArrayList<>();
// messages.add(ChatGptMessage.builder()
// .role(ChatgptConfig.ROLE)
// .content(chatGptQuestionRequest.getQuestion())
// .build());
//
// ChatgptRequest chatGptRequest = new ChatgptRequest(
// ChatgptConfig.CHAT_MODEL,
// ChatgptConfig.MAX_TOKEN,
// ChatgptConfig.TEMPERATURE,
// ChatgptConfig.STREAM_TRUE,
// messages
// );
//
// String requestValue = objectMapper.writeValueAsString(chatGptRequest);
//
// Flux<String> eventStream = client.post()
// .bodyValue(requestValue)
// .accept(MediaType.TEXT_EVENT_STREAM)
// .retrieve()
// .bodyToFlux(String.class);
//
// return eventStream;
// }

// 단답 답변
public String getChatResponse(String prompt) {
System.out.print(apiKey);
// ChatGPT에 질문 전송
return chatgptService.sendMessage(prompt);
try{
String prompt_guide=
"너는 지금 청년들의 금융 지식을 향상시켜주기 위한 챗봇이야. 너의 이름은 '금토리'야. 너는 캐릭터의 역할이기 때문에 텍스트 형식으로 답변을 해야 해. 언어는 한국어로 말해야 하고, 말투는 친구한테 말하는 것처럼 반발로 해." +
"그리고 금융에 관련된 답변만 해야 하고, 만약 금융과 관련이 없는 질문이면 '미안해. 금융과 관련되지 않은 질문은 답변해줄 수 없어.'라고 말하면 돼. " +
"질문은 다음과 같아. 실제로 사용자와 대화하듯이 말해야 하고, 바로 질문에 대한 답을 해. 상식적으로 알 수도 있다는 말은 하지 마." +
"'네'라는 대답은 하지마. 인사말도 하지 마. 그리고 최대한 자세하게 답변해. 다시 한 번 말하지만, 반말로 말해. 그리고 문장은 끝까지 완전한 형태로 말 해";
prompt=prompt_guide.concat(prompt);
String response=chatgptService.sendMessage(prompt);
return response;
}
catch (Exception e){
e.printStackTrace();
return "request error";
}
}

}

Original file line number Diff line number Diff line change
@@ -1,6 +1,11 @@
package com.finfellows.domain.chatgpt.presentation;

import com.finfellows.domain.chatgpt.application.ChatGptService;
import com.finfellows.domain.comment.application.CommentService;
import com.finfellows.domain.comment.domain.QComment;
import com.finfellows.global.config.security.token.CurrentUser;
import com.finfellows.global.config.security.token.UserPrincipal;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
Expand All @@ -14,24 +19,21 @@
@Slf4j
public class ChatGptController {
private final ChatGptService chatgptService;

// @PostMapping(value="/ask-stream", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
// public Flux<String> ask(Locale locale,
// HttpServletRequest request,
// HttpServletResponse response,
// @RequestBody ChatgptQuestionRequest chatGptQuestionRequest){
// try {
// return chatgptService.ask(chatGptQuestionRequest);
// }catch (JsonProcessingException je){
// log.error(je.getMessage());
// return Flux.empty();
// }
// }
private final CommentService commentService;

// 단답 테스트
// https://yjkim-dev.tistory.com/56
@PostMapping("")
@PostMapping("/test")
public String test(@RequestBody String question) {
return chatgptService.getChatResponse(question);
}

// 답변 저장 테스트
@PostMapping("")
public String getChatResponse(@CurrentUser UserPrincipal userPrincipal, @RequestBody String question){
String answer= commentService.getChatResponse(question);
commentService.saveComment(userPrincipal.getId(), question, answer);
return answer;
}

}
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
package com.finfellows.domain.comment.application;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JsonNode;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.PropertyNamingStrategies;
import com.finfellows.domain.chatgpt.domain.ChatGptMessage;
Expand All @@ -9,7 +12,11 @@
import com.finfellows.domain.chatgpt.dto.request.ChatgptQuestionRequest;
import com.finfellows.domain.chatgpt.dto.request.ChatgptRequest;
import com.finfellows.domain.chatgpt.dto.response.ChatgptResponse;
import com.finfellows.domain.comment.domain.Comment;
import com.finfellows.domain.comment.domain.repository.CommentRepository;
import com.finfellows.domain.comment.dto.response.CommentResponse;
import com.finfellows.domain.user.domain.User;

import com.finfellows.domain.user.domain.repository.UserRepository;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
Expand All @@ -20,6 +27,8 @@
import org.springframework.web.client.RestTemplate;

import java.util.*;
import java.util.stream.Collectors;


@Service
@RequiredArgsConstructor
Expand All @@ -31,6 +40,7 @@ public class CommentService {
@Autowired
private RestTemplate restTemplate;


@Value("${chatgpt.api-key}")
private String apiKey;
private final ObjectMapper objectMapper = new ObjectMapper()
Expand All @@ -47,7 +57,6 @@ public HttpEntity<ChatgptRequest> buildHttpEntity(ChatgptRequest chatGptRequest)

// gpt 단답
public ChatgptResponse getResponse(HttpEntity<ChatgptRequest> chatGptRequestHttpEntity) {

SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory();
requestFactory.setConnectTimeout(60000);
//답변이 길어질 경우 TimeOut Error가 발생하니 1분정도 설정해줍니다.
Expand Down Expand Up @@ -81,4 +90,65 @@ public ChatgptResponse askQuestion(ChatgptQuestionRequest questionRequest) {
)
);
}

public String getChatResponse(String question){
String responseFromGPT=chatGptService.getChatResponse(question);
return responseFromGPT;
}

public void saveComment(Long userId, String question, String answer) {
Optional<User> optionalUser = userRepository.findById(userId);
User user = optionalUser.orElseThrow(() -> new RuntimeException("User not found"));

question = extractPromptFromJson(question);
answer = answer.replaceAll("\\n", "");
answer = answer.replaceAll("금토리: ", "");
answer = answer.replaceAll("네. ", "");

Comment comment = Comment.builder()
.question(question)
.answer(answer)
.user(user)
.build();
commentRepository.save(comment);
}

// JSON에서 "prompt" 부분 추출하는 메소드
private String extractPromptFromJson(String json) {
try {
ObjectMapper objectMapper = new ObjectMapper();
JsonNode jsonNode = objectMapper.readTree(json);
if (jsonNode.has("prompt")) {
return jsonNode.get("prompt").asText();
}
} catch (JsonProcessingException e) {
System.out.print("텍스트 변환 실패");
}
return json;
}

public List<CommentResponse> getAllComments(Long userId) {
Optional<User> optionalUser = userRepository.findById(userId);
User user = optionalUser.orElseThrow(() -> new RuntimeException("User not found"));

List<Comment> comments = commentRepository.findAllByUserId(userId);

Comment greet = Comment.builder()
.greeting("안녕! 나는 금토리야. 도움이 필요하다면 편하게 말해줘.")
.user(user)
.build();
commentRepository.save(greet);

return comments.stream()
.map(comment -> CommentResponse.builder()
.commentId(comment.getCommentId())
.created_at(comment.getCreatedAt())
.greeting(comment.getGreeting())
.question(comment.getQuestion())
.answer(comment.getAnswer())
.userId(comment.getUser().getId())
.build()
)
.collect(Collectors.toList());
}
}
Loading

0 comments on commit 8ddb75f

Please sign in to comment.