Skip to content

Commit

Permalink
Merge branch 'develop' into test
Browse files Browse the repository at this point in the history
  • Loading branch information
gerry-mandering committed Apr 26, 2024
2 parents 3c73011 + 178bdf5 commit a638395
Show file tree
Hide file tree
Showing 39 changed files with 429 additions and 93 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Excepti
.csrf(AbstractHttpConfigurer :: disable)
.cors(cors -> cors.configurationSource(corsConfiguration()))
.sessionManagement(httpSecuritySessionManagementConfigurer -> {
httpSecuritySessionManagementConfigurer.sessionCreationPolicy(SessionCreationPolicy.NEVER);
httpSecuritySessionManagementConfigurer.sessionCreationPolicy(SessionCreationPolicy.STATELESS);
}) // 세션 생성 X
.authorizeHttpRequests(authorizationManagerRequestMatcherRegistry ->
authorizationManagerRequestMatcherRegistry.anyRequest().permitAll()) //모든 요청 인증없이 허용
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -43,11 +43,11 @@ public void onAuthenticationSuccess(HttpServletRequest request, HttpServletRespo
tokenRepository.save(token);


response.addCookie(createCookie("accessToken", accessToken, JwtConstants.ACCESS_EXP_TIME, true, false));
response.addCookie(createCookie("accessToken", accessToken, JwtConstants.ACCESS_EXP_TIME, false, false));

response.addCookie(createCookie("refreshToken", refreshToken, JwtConstants.REFRESH_EXP_TIME, true, false));
response.addCookie(createCookie("refreshToken", refreshToken, JwtConstants.REFRESH_EXP_TIME, false, false));

String clientUrl = "http://localhost:3000/genre";
String clientUrl = "http://localhost:3000/genre_select";
response.sendRedirect(clientUrl);
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,9 +21,7 @@

@Slf4j
public class JwtVerifyFilter extends OncePerRequestFilter {

// 상품 이미지가 보이지 않기에 상품 이미지를 출력하는 /api/items/view 경로를 추가
private static final String[] whitelist = {"/signUp", "/login" , "/refresh", "/", "/index.html"};
private static final String[] whitelist = {"/signUp", "/login" , "/refresh", "/tracks/**", "/playlists/**", "/tags/**", "/genres/**"};

private static void checkAuthorizationHeader(String header) {
if(header == null) {
Expand All @@ -36,9 +34,8 @@ private static void checkAuthorizationHeader(String header) {
// 필터를 거치지 않을 URL 을 설정하고, true 를 return 하면 현재 필터를 건너뛰고 다음 필터로 이동
@Override
protected boolean shouldNotFilter(HttpServletRequest request) throws ServletException {
return true;
// String requestURI = request.getRequestURI();
// return PatternMatchUtils.simpleMatch(whitelist, requestURI);
String requestURI = request.getRequestURI();
return !PatternMatchUtils.simpleMatch(whitelist, requestURI);
}

@Override
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,8 @@

public class JwtConstants {
public static final String key = "DG3K2NG9lK3T2FLfnO283HO1NFLAy9FGJ23UM9Rv923YRV923HT";
public static final int ACCESS_EXP_TIME = 10; // 10분
public static final int REFRESH_EXP_TIME = 60 * 24; // 24시간
public static final int ACCESS_EXP_TIME = 600; // 10분
public static final int REFRESH_EXP_TIME = 600 * 24; // 24시간

public static final String JWT_HEADER = "Authorization";
public static final String JWT_TYPE = "Bearer ";
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import javax.crypto.SecretKey;
import java.nio.charset.StandardCharsets;
Expand Down Expand Up @@ -50,13 +51,15 @@ public static String generateToken(Map<String, Object> valueMap, int validTime)
public static Authentication getAuthentication(String token) {
Map<String, Object> claims = validateToken(token);

String email = (String) claims.get("email");
String name = (String) claims.get("name");
String role = (String) claims.get("role");
String userId = (String) claims.get("userId");
String name = (String) claims.get("name");
String email = (String) claims.get("email");
String userIdString = (String) claims.get("userId");
UserRole userRole = UserRole.valueOf(role);

User user = User.builder().userEmail(email).userName(name).role(userRole).build();
Long userId = Long.parseLong(userIdString);

User user = User.builder().role(userRole).userName(name).userEmail(email).userId(userId).build();
Set<SimpleGrantedAuthority> authorities = Collections.singleton(new SimpleGrantedAuthority(user.getRole().getValue()));
UserDetailPrincipal principalDetail = new UserDetailPrincipal(user, authorities);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,14 +18,13 @@ public OpenAPI openAPI() {
Components components = new Components().addSecuritySchemes(jwt, new SecurityScheme()
.name(jwt)
.type(SecurityScheme.Type.HTTP)
.scheme("bearer")
.scheme("Bearer")
.bearerFormat("JWT")
);
return new OpenAPI()
.components(new Components())
.info(apiInfo())
.addSecurityItem(securityRequirement)
.components(components);
.addSecurityItem(securityRequirement);
}
private Info apiInfo() {
return new Info()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,12 +7,14 @@
import org.springframework.data.domain.Pageable;
import org.springframework.data.web.PageableDefault;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.web.bind.annotation.RequestMapping;

import com.example.dreamvalutbackend.domain.genre.controller.response.GenreResponseDto;
import com.example.dreamvalutbackend.domain.genre.controller.response.GenreWithTracksOverviewResponseDto;
import com.example.dreamvalutbackend.domain.genre.controller.response.GenreWithTracksResponseDto;
import com.example.dreamvalutbackend.domain.genre.service.GenreService;
import com.example.dreamvalutbackend.domain.user.domain.UserDetailPrincipal;

import io.swagger.v3.oas.annotations.Operation;
import lombok.RequiredArgsConstructor;
Expand Down Expand Up @@ -44,7 +46,9 @@ public ResponseEntity<List<GenreResponseDto>> listAllGenres() {
@GetMapping("/{genre_id}/tracks")
@Operation(summary = "특정 장르의 모든 곡 가져오기")
public ResponseEntity<GenreWithTracksResponseDto> getGenreWithTracks(@PathVariable("genre_id") Long genreId,
@PageableDefault(page = 0, size = 30, sort = "id", direction = Sort.Direction.DESC) Pageable pageable) {
return ResponseEntity.ok(genreService.getGenreWithTracks(genreId, pageable));
@PageableDefault(page = 0, size = 30, sort = "id", direction = Sort.Direction.DESC) Pageable pageable,
@AuthenticationPrincipal UserDetailPrincipal userDetailPrincipal) {
Long userId = userDetailPrincipal.getUserId();
return ResponseEntity.ok(genreService.getGenreWithTracks(genreId, pageable, userId));
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@

import com.example.dreamvalutbackend.domain.common.BaseTimeEntity;
import com.example.dreamvalutbackend.domain.track.domain.Track;
import com.example.dreamvalutbackend.domain.user.domain.User;

import jakarta.persistence.*;
import lombok.AccessLevel;
Expand All @@ -29,6 +30,10 @@ public class Genre extends BaseTimeEntity {
@Column(nullable = false)
private String genreImage;

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

// @OneToMany(mappedBy = "genre", cascade = CascadeType.ALL, orphanRemoval = true, fetch = FetchType.LAZY)
// private List<Track> tracks = new ArrayList<>();

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
import com.example.dreamvalutbackend.domain.genre.controller.response.GenreWithTracksResponseDto;
import com.example.dreamvalutbackend.domain.genre.domain.Genre;
import com.example.dreamvalutbackend.domain.genre.repository.GenreRepository;
import com.example.dreamvalutbackend.domain.like.repository.LikeRepository;
import com.example.dreamvalutbackend.domain.track.controller.response.TrackOverviewResponseDto;
import com.example.dreamvalutbackend.domain.track.controller.response.TrackResponseDto;
import com.example.dreamvalutbackend.domain.track.domain.Track;
Expand All @@ -31,6 +32,7 @@ public class GenreService {
private final GenreRepository genreRepository;
private final TrackRepository trackRepository;
private final TrackDetailRepository trackDetailRepository;
private final LikeRepository likeRepository;

@Transactional(readOnly = true)
public Page<GenreWithTracksOverviewResponseDto> getGenresWithTracksOverview(Pageable pageable) {
Expand Down Expand Up @@ -60,7 +62,7 @@ public List<GenreResponseDto> listAllGenres() {
}

@Transactional(readOnly = true)
public GenreWithTracksResponseDto getGenreWithTracks(Long genreId, Pageable pageable) {
public GenreWithTracksResponseDto getGenreWithTracks(Long genreId, Pageable pageable, Long userId) {
// genreId로 해당하는 장르 가져오기
Genre genre = genreRepository.findById(genreId)
.orElseThrow(() -> new IllegalArgumentException("Genre not found"));
Expand All @@ -72,7 +74,9 @@ public GenreWithTracksResponseDto getGenreWithTracks(Long genreId, Pageable page
Page<TrackResponseDto> trackResponseDtos = tracks.map(track -> {
TrackDetail trackDetail = trackDetailRepository.findById(track.getId())
.orElseThrow(() -> new IllegalArgumentException("Track detail not found"));
return TrackResponseDto.toDto(track, trackDetail);
Long likes = likeRepository.countByTrackId(track.getId());
Boolean likesFlag = likeRepository.existsByUserIdAndTrackId(userId, track.getId());
return TrackResponseDto.toDto(track, trackDetail, likes, likesFlag);
});

return GenreWithTracksResponseDto.toDto(genre, trackResponseDtos);
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
package com.example.dreamvalutbackend.domain.like.controller;

import org.springframework.http.ResponseEntity;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import com.example.dreamvalutbackend.domain.like.controller.request.LikeCreateRequestDto;
import com.example.dreamvalutbackend.domain.like.controller.request.LikeDeleteRequestDto;
import com.example.dreamvalutbackend.domain.like.controller.response.LikeResponseDto;
import com.example.dreamvalutbackend.domain.like.service.LikeService;
import com.example.dreamvalutbackend.domain.user.domain.UserDetailPrincipal;

import lombok.RequiredArgsConstructor;
@RestController
@RequiredArgsConstructor
public class LikeController {

private final LikeService likeService;

@PostMapping("/tracks/{trackId}/likes")
public ResponseEntity<LikeResponseDto> createLike(@PathVariable Long trackId, @AuthenticationPrincipal
UserDetailPrincipal userDetailPrincipal) {
LikeCreateRequestDto requestDto = LikeCreateRequestDto.builder()
.userId(userDetailPrincipal.getUserId())
.trackId(trackId)
.build();

LikeResponseDto responseDto = likeService.addLike(requestDto);

return ResponseEntity.ok(responseDto);
}

@DeleteMapping("/tracks/{trackId}/disLikes")
public ResponseEntity<LikeResponseDto> deleteLike(@PathVariable Long trackId, @AuthenticationPrincipal
UserDetailPrincipal userDetailPrincipal){
LikeDeleteRequestDto requestDto = LikeDeleteRequestDto.builder()
.userId(userDetailPrincipal.getUserId())
.trackId(trackId)
.build();

likeService.deleteLike(requestDto);

return ResponseEntity.noContent().build(); //반환 내용이 없어서 204
}






}
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
package com.example.dreamvalutbackend.domain.like.controller.request;

import jakarta.validation.constraints.NotNull;
import lombok.AccessLevel;
import lombok.Builder;
import lombok.Getter;
import lombok.NoArgsConstructor;

@Getter
@NoArgsConstructor(access = AccessLevel.PROTECTED)
public class LikeCreateRequestDto {
@NotNull
private Long userId;
@NotNull
private Long trackId;

@Builder
public LikeCreateRequestDto(Long userId, Long trackId) {
this.userId = userId;
this.trackId = trackId;
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
package com.example.dreamvalutbackend.domain.like.controller.request;

import jakarta.validation.constraints.NotNull;
import lombok.AccessLevel;
import lombok.Builder;
import lombok.Getter;
import lombok.NoArgsConstructor;

@Getter
@NoArgsConstructor(access = AccessLevel.PROTECTED)
public class LikeDeleteRequestDto {
@NotNull
private Long userId;
@NotNull
private Long trackId;

@Builder
public LikeDeleteRequestDto(Long userId, Long trackId) {
this.userId = userId;
this.trackId = trackId;
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
package com.example.dreamvalutbackend.domain.like.controller.response;

import com.example.dreamvalutbackend.domain.like.domain.Like;

import lombok.Builder;
import lombok.Getter;

@Getter
public class LikeResponseDto {
private Long id;
private Long userId;
private Long trackId;

@Builder
public LikeResponseDto(Long id, Long userId, Long trackId) {
this.id = id;
this.userId = userId;
this.trackId = trackId;
}

public static LikeResponseDto toDto(Like like) {
return LikeResponseDto.builder()
.id(like.getId())
.userId(like.getUser().getUserId())
.trackId(like.getTrack().getId())
.build();
}
}
Original file line number Diff line number Diff line change
@@ -1,10 +1,12 @@
package com.example.dreamvalutbackend.domain.track.domain;
package com.example.dreamvalutbackend.domain.like.domain;

import com.example.dreamvalutbackend.domain.common.BaseTimeEntity;
import com.example.dreamvalutbackend.domain.track.domain.Track;
import com.example.dreamvalutbackend.domain.user.domain.User;

import jakarta.persistence.*;
import lombok.AccessLevel;
import lombok.Builder;
import lombok.Getter;
import lombok.NoArgsConstructor;

Expand All @@ -26,4 +28,10 @@ public class Like extends BaseTimeEntity {
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "track_id")
private Track track;

@Builder
public Like(User user, Track track) {
this.user = user;
this.track = track;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
package com.example.dreamvalutbackend.domain.like.repository;

import java.util.Optional;

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;

import com.example.dreamvalutbackend.domain.like.domain.Like;
import com.example.dreamvalutbackend.domain.track.domain.Track;
import com.example.dreamvalutbackend.domain.user.domain.User;

public interface LikeRepository extends JpaRepository<Like, Long> {
Optional<Like> findByUserAndTrack(User user, Track track);

Long countByTrackId(Long trackId);

@Query("SELECT count(l) > 0 FROM Like l WHERE l.user.userId = :userId AND l.track.id = :trackId")
Boolean existsByUserIdAndTrackId(Long userId, Long trackId);
}
Loading

0 comments on commit a638395

Please sign in to comment.