Skip to content

Commit

Permalink
refact: API 병합 후 코드 수정 (#57)
Browse files Browse the repository at this point in the history
* del: CastPlayService 삭제

* fix: 캐스트 수정 API 반환값 변경
- Cast 엔티티 대신 "수정되었습니다" 문자열

* update: CastService와 CastSearchService 병합

* del: CastSearchService 삭제

* fix: CastController 테스트 메소드 삭제

* fix: Book mark service 수정

* fix: saveCast 이름 수정, 본인 캐스트 검색 안되게 수정, 본인 캐스트 추천 안되게 수정, 캐스트 담아오기 수정

* fix: cast playlist service 수정

* del: stream-test 디렉토리 삭제

* update: FileService와 StreamService 통합

* del: StreamService 삭제

* move: VoiceCode 패키지 변경
- ~/cast/enums 에서 ~/enums로 변경

* fix: subCategory 엔티티 수정, MemberPreferRequestDTO 수정, setMember 수정

* fix: playlist 양방향 매핑 추가, DTO 분리, Tag 설정

* "fix: encoder 수정"

* fix: MemberRepository에 @repository 추가

* "fix: 회원가입 비밀번호 길이 수정"

* fix: SecurityConfig 허용된 url에 swagger-ui.html 추가

* fix: SecurityConfig 모든 url 일시 허용 -> 배포할 떄 삭제!!

* fix: 키워드 받아오기 기능 수정, 플레이리스트 불러오기 이미지 나오게 수정

* fix: MemberService UserService 통합, 기타 기능 추가

* fix: SentenceService::add에서 cast.sentence도 등록하도록 변경

* refact: getObjectApiResponse 메소드명 변경
- handleCastCreation

* refact: CastController에서 ApiResponse로 감싸도록 변경

* refact: CastController에서 ApiResponse로 감싸도록 변경
- CastService에서 ApiResponse로 감싸서 반환하던 메소드 -> 전부 DTO만 반환하도록 변경햇어유

* add: TypeMismatchException 핸들러 추가
pathVariable 등을 Long으로 받겠다 해놓고 String을 입력하면 뜨는 에러입니다
이 익센션에 대한 핸들러가 없어서 일반적인 ApiResponse 외의 형식으로 출력되고 있었는데 수정함

* fix: parsing 구분 문구 추가

* cast service 파일 구조 변환 및 중복 코드 제거

* refact: 파일 구조 변환 및 중복 코드 제거

* fix: 플레이리스트 삭제 - 플리 내 캐스트도 삭제되도록 수정

* fix: 파싱 중복 제거 및 글자 수 제한

* fix: 스크립트 입력 받을 떄 strip() 추가

* refact: CastService 구조 개선

* refact: ProfileSetting 리팩토링

* refact: playlist api refact

* refact: bookmark refact

* fix: tts 문자열 길이 관련 bug fixing

* fix: 스트리밍 api 수정

* fix: CastService::save, update에서 Cast 반환하도록 변경

* fix: CastHomeDTO에 imagePath 필드 추가

* "fix: 로그인 수정 중"

* "fix: 로그인 수정"

* fix: tts 구분자 남기기

* refact: 캐스트 재생 API 쪽 메서드명 변경
- streamCast -> findCast
- fetchCast -> findCast

---------

Co-authored-by: yuuddin <[email protected]>
Co-authored-by: YamYamee <[email protected]>
Co-authored-by: KimChaeWon12 <[email protected]>
Co-authored-by: younheejae <[email protected]>
  • Loading branch information
5 people authored Aug 17, 2024
1 parent 7bdb833 commit 85ac091
Show file tree
Hide file tree
Showing 78 changed files with 1,049 additions and 1,099 deletions.
15 changes: 0 additions & 15 deletions src/main/java/com/umc/owncast/common/config/EncoderConfig.java

This file was deleted.

15 changes: 9 additions & 6 deletions src/main/java/com/umc/owncast/common/config/SecurityConfig.java
Original file line number Diff line number Diff line change
Expand Up @@ -6,11 +6,14 @@
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.configuration.AuthenticationConfiguration;
import org.springframework.security.config.annotation.web.WebSecurityConfigurer;
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.configurers.AbstractHttpConfigurer;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.factory.PasswordEncoderFactories;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
Expand Down Expand Up @@ -48,19 +51,15 @@ public SecurityFilterChain securityFilterChain(HttpSecurity httpSecurity) throws
.sessionCreationPolicy(SessionCreationPolicy.STATELESS)
)
.authorizeHttpRequests(registry -> registry
.requestMatchers("/h2/**", "/favicon.ico", "/error", "/swagger-ui/**", "/v3/api-docs/**", "/api/users/login", "api/users/signup", "api/users/signup/**").permitAll()
.requestMatchers("**").permitAll() // TODO 일시적으로 허용해놓음 -> 배포할 때 삭제
.requestMatchers("/h2/**", "/favicon.ico", "/error", "/swagger-ui/**", "/swagger-ui.html/**", "/v3/api-docs/**", "/api/users/**").permitAll()
)
.addFilterBefore(new JwtFilter(jwtUtil), LoginFilter.class)
.addFilterAt(new LoginFilter(authenticationManager(authenticationConfiguration), loginService), UsernamePasswordAuthenticationFilter.class)
.addFilterBefore(new LogoutFilter(loginService), org.springframework.security.web.authentication.logout.LogoutFilter.class)
.build();
}

@Bean
public BCryptPasswordEncoder bCryptPasswordEncoder() {
return new BCryptPasswordEncoder();
}

CorsConfigurationSource apiConfigurationSource() {
CorsConfiguration configuration = new CorsConfiguration();
configuration.setAllowedOrigins(Arrays.asList("*")); // 이후 수정
Expand All @@ -69,4 +68,8 @@ CorsConfigurationSource apiConfigurationSource() {
source.registerCorsConfiguration("/**", configuration);
return source;
}
@Bean
public PasswordEncoder passwordEncoder() {
return PasswordEncoderFactories.createDelegatingPasswordEncoder();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -6,16 +6,17 @@
import jakarta.servlet.http.HttpServletRequest;
import jakarta.validation.ConstraintViolationException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.HttpStatusCode;
import org.springframework.http.ResponseEntity;
import org.springframework.beans.TypeMismatchException;
import org.springframework.http.*;
import org.springframework.lang.Nullable;
import org.springframework.web.ErrorResponse;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.context.request.ServletWebRequest;
import org.springframework.web.context.request.WebRequest;
import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException;
import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler;

import java.util.LinkedHashMap;
Expand Down Expand Up @@ -47,6 +48,14 @@ protected ResponseEntity<Object> handleMethodArgumentNotValid(
return handleExceptionInternalArgs(e, HttpHeaders.EMPTY, ErrorCode.valueOf("BAD_REQUEST"), request, errors);
}

@Override
protected ResponseEntity<Object> handleTypeMismatch(TypeMismatchException ex, HttpHeaders headers, HttpStatusCode status, WebRequest request) {
Object[] args = new Object[]{ex.getPropertyName(), ex.getValue()};
log.error("TypeMismatchException - Failed to convert '" + args[0] + "' with value: '" + args[1] + "'");
ApiResponse<String> body = ApiResponse.ofFailure(ErrorCode._BAD_REQUEST, "요청 파라미터가 잘못되었습니다");
return this.handleExceptionInternal(ex, body, headers, status, request);
}

@ExceptionHandler(Exception.class)
public ResponseEntity<Object> handleGenericException(Exception e, WebRequest request) {
log.error("Unhandled exception occurred: ", e);
Expand Down
2 changes: 1 addition & 1 deletion src/main/java/com/umc/owncast/common/jwt/JwtUtil.java
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ public class JwtUtil {
private SecretKey secretKey;

public JwtUtil(@Value("${jwt.secret.key}") String secret) {
this.secretKey = new SecretKeySpec(secret.getBytes(StandardCharsets.UTF_8), "HmacSHA256");
this.secretKey = new SecretKeySpec(secret.getBytes(StandardCharsets.UTF_8), Jwts.SIG.HS256.key().build().getAlgorithm());
}

public String getCategory(String token) {
Expand Down
16 changes: 12 additions & 4 deletions src/main/java/com/umc/owncast/common/jwt/LoginFilter.java
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
import com.umc.owncast.common.response.status.SuccessCode;
import com.umc.owncast.domain.enums.Status;
import com.umc.owncast.domain.member.dto.CustomUserDetails;
import com.umc.owncast.domain.member.repository.MemberRepository;
import com.umc.owncast.domain.member.service.MemberMapper;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletInputStream;
Expand All @@ -25,10 +26,12 @@

public class LoginFilter extends UsernamePasswordAuthenticationFilter {

private MemberRepository memberRepository;
private final AuthenticationManager authenticationManager;
private final LoginService loginService;
private final ObjectMapper objectMapper = new ObjectMapper();


public LoginFilter(AuthenticationManager authenticationManager, LoginService loginService) {
this.authenticationManager = authenticationManager;
this.loginService = loginService;
Expand All @@ -44,6 +47,7 @@ static class LoginDTO {

@Override
public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {

LoginDTO loginDTO = new LoginDTO();

try {
Expand All @@ -55,17 +59,19 @@ public Authentication attemptAuthentication(HttpServletRequest request, HttpServ
return null;
}

String LoginId = loginDTO.getLoginId();
String Password = loginDTO.getPassword();
String LoginId= loginDTO.getLoginId();
String Password =loginDTO.getPassword();



UsernamePasswordAuthenticationToken authToken = new UsernamePasswordAuthenticationToken(LoginId, Password);

return authenticationManager.authenticate(authToken);
}

@Override
protected void successfulAuthentication(HttpServletRequest request, HttpServletResponse response, FilterChain chain, Authentication authResult) {
CustomUserDetails customUserDetails = (CustomUserDetails) authResult.getPrincipal();
protected void successfulAuthentication(HttpServletRequest request, HttpServletResponse response, FilterChain chain, Authentication authentication) {
CustomUserDetails customUserDetails = (CustomUserDetails) authentication.getPrincipal();

if (customUserDetails.getStatus() == Status.INACTIVE) {
writeOutput(request, response, HttpServletResponse.SC_FORBIDDEN, ApiResponse.onSuccess(ErrorCode.INACTIVATE_FORBIDDEN));
Expand All @@ -75,9 +81,11 @@ protected void successfulAuthentication(HttpServletRequest request, HttpServletR
Long userId = customUserDetails.getUserId();

String accessToken = loginService.issueAccessToken(userId);
//Cookie refreshTokenCookie = loginService.issueRefreshToken(userId);
String refreshToken = loginService.issueRefreshToken(userId);

response.addHeader("Authorization", accessToken);
//response.addCookie(refreshTokenCookie);
writeOutput(request, response, HttpServletResponse.SC_OK, ApiResponse.of(SuccessCode._OK, MemberMapper.toRefreshToken(refreshToken)));
}

Expand Down
4 changes: 4 additions & 0 deletions src/main/java/com/umc/owncast/common/jwt/LoginService.java
Original file line number Diff line number Diff line change
Expand Up @@ -58,11 +58,14 @@ public void revokeRefreshToken(String refreshToken) {
}

public String validateRefreshToken(Cookie[] cookies) {

String refreshToken = null;

for (Cookie cookie : cookies)
if (cookie.getName().equals("refresh"))
refreshToken = cookie.getValue();


if (refreshToken == null)
throw new GeneralException(ErrorCode.NOT_FOUND_TOKEN);

Expand Down Expand Up @@ -93,4 +96,5 @@ private void saveRefreshToken(Long userId, String refreshToken, Long expirationT

refreshRepository.save(newRefresh);
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ private SecurityUtils() {
}

public static Optional<String> getCurrentUsername() {

final Authentication authentication = SecurityContextHolder.getContext().getAuthentication();

if (authentication == null) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -48,9 +48,15 @@ public enum ErrorCode implements BaseErrorCode {
BOOKMARK_ALREADY_EXIST(HttpStatus.BAD_REQUEST, "BOOKMARK4002", "이미 존재하는 북마크입니다."),
REQUEST_TIMEOUT(HttpStatus.REQUEST_TIMEOUT, "CAST4001", "캐스트 생성시간이 너무 오래 걸립니다."),

//Cast-Playlist 관련 에러
CAST_PLAYLIST_NOT_FOUND(HttpStatus.BAD_REQUEST, "CASTPLAYLIST4001", "해당 캐스트가 저장된 플레이 리스트가 없습니다"),

//Playlist 관련 에러
PLAYLIST_NOT_FOUND(HttpStatus.BAD_REQUEST, "PLAYLIST4001", "해당 플레이리스트가 없습니다."),
PLAYLIST_ALREADY_EXIST(HttpStatus.BAD_REQUEST, "PLAYLIST4002", "이미 존재하는 플레이리스트입니다."),

//Sentence 관련 에러
SENTENCE_NOT_FOUND(HttpStatus.BAD_REQUEST, "SENTENCE4001", "해당 문장이 없습니다."),
// 기타 에러는 아래에 추가
;

Expand Down
Original file line number Diff line number Diff line change
@@ -1,56 +1,58 @@
package com.umc.owncast.domain.bookmark.controller;


import com.umc.owncast.common.response.ApiResponse;
import com.umc.owncast.domain.bookmark.dto.BookMarkDTO;
import com.umc.owncast.domain.bookmark.service.BookMarkServiceImpl;
import com.umc.owncast.domain.bookmark.dto.BookmarkResultDTO;
import com.umc.owncast.domain.bookmark.dto.BookmarkSaveResultDTO;
import com.umc.owncast.domain.bookmark.service.BookmarkService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Tag(name = "북마크 API", description = "북마크 관련 API입니다")
@Slf4j
@RequiredArgsConstructor
@RequestMapping("/api")
@RestController
public class BookmarkController {

private final BookMarkServiceImpl bookmarkService;
private final BookmarkService bookmarkService;

@CrossOrigin
@Operation(summary = "북마크된 문장 불러오기")
@GetMapping("/study/{playlistId}")
public ApiResponse<List<BookMarkDTO.BookMarkResultDTO>> getBookmarks(@PathVariable("playlistId") Long playlistId) {
public ApiResponse<List<BookmarkResultDTO>> getBookmarks(@PathVariable("playlistId") Long playlistId) {
return ApiResponse.onSuccess(bookmarkService.getBookmarks(playlistId));
}

@CrossOrigin
@Operation(summary = "내가 저장한 캐스트의 북마크된 문장 불러오기")
@GetMapping("/study/mycast")
public ApiResponse<List<BookMarkDTO.BookMarkResultDTO>> getMyCastBookmarks() {
public ApiResponse<List<BookmarkResultDTO>> getMyCastBookmarks() {
return ApiResponse.onSuccess(bookmarkService.getMyCastBookmarks());
}

@CrossOrigin
@Operation(summary = "내가 저장한 남의 캐스트의 북마크된 문장 불러오기")
@GetMapping("/study/savedcast")
public ApiResponse<List<BookMarkDTO.BookMarkResultDTO>> getSavedBookmarks() {
public ApiResponse<List<BookmarkResultDTO>> getSavedBookmarks() {
return ApiResponse.onSuccess(bookmarkService.getSavedBookmarks());
}

@CrossOrigin
@Operation(summary = "문장 북마크 하기")
@PostMapping("/bookmark")
public ApiResponse<BookMarkDTO.BookMarkSaveResultDTO> saveBookmark(@RequestParam("sentenceId") Long sentenceId) {
public ApiResponse<BookmarkSaveResultDTO> saveBookmark(@RequestParam("sentenceId") Long sentenceId) {
return ApiResponse.onSuccess(bookmarkService.saveBookmark(sentenceId));
}

@CrossOrigin
@Operation(summary = "문장 북마크 취소하기")
@DeleteMapping("/bookmark")
public ApiResponse<BookMarkDTO.BookMarkSaveResultDTO> deleteBookmark(@RequestParam("sentenceId") Long sentenceId) {
public ApiResponse<BookmarkSaveResultDTO> deleteBookmark(@RequestParam("sentenceId") Long sentenceId) {
return ApiResponse.onSuccess(bookmarkService.deleteBookmark(sentenceId));
}
}
22 changes: 0 additions & 22 deletions src/main/java/com/umc/owncast/domain/bookmark/dto/BookMarkDTO.java

This file was deleted.

Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
package com.umc.owncast.domain.bookmark.dto;

import lombok.Builder;
import lombok.Getter;

@Builder
@Getter
public class BookmarkResultDTO {
Long castId;
String originalSentence;
String translatedSentence;
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
package com.umc.owncast.domain.bookmark.dto;

import lombok.Builder;
import lombok.Getter;

@Builder
@Getter
public class BookmarkSaveResultDTO {
Long bookmarkId;
}
Loading

0 comments on commit 85ac091

Please sign in to comment.