Skip to content

Commit

Permalink
Merge pull request #89 from kakao-tech-campus-2nd-step3/develop
Browse files Browse the repository at this point in the history
Develop - Master 병합
  • Loading branch information
yooonwodyd authored Nov 7, 2024
2 parents 3b565d1 + 3136eae commit eff003f
Show file tree
Hide file tree
Showing 24 changed files with 316 additions and 148 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
package com.helpmeCookies.global.ApiResponse;

import jakarta.annotation.Nullable;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
import org.springframework.http.HttpStatus;

@Getter
@AllArgsConstructor
@RequiredArgsConstructor
public class ApiResponse<T> {

private final int code;
private final String message;
private T data;

public static<T> ApiResponse<T> success(SuccessCode successCode, T data) {
return new ApiResponse<T>(successCode.getCode(), successCode.getMessage(),data);
}

public static ApiResponse<Void> success(SuccessCode successCode) {
return new ApiResponse<>(successCode.getCode(), successCode.getMessage(),null);
}

public static ApiResponse<Void> error(HttpStatus errorCode, String message) {
return new ApiResponse<>(errorCode.value(), message,null);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
package com.helpmeCookies.global.ApiResponse;

import lombok.AllArgsConstructor;
import lombok.Getter;
import org.springframework.http.HttpStatus;

@AllArgsConstructor
@Getter
public enum SuccessCode {
OK(200, "OK"),
CREATED_SUCCESS(201, "저장에 성공했습니다");

private final int code;
private final String message;

}
12 changes: 12 additions & 0 deletions src/main/java/com/helpmeCookies/global/config/ProPertyConfig.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
package com.helpmeCookies.global.config;

import org.springframework.boot.context.properties.ConfigurationPropertiesScan;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Configuration;

import com.helpmeCookies.global.jwt.JwtProperties;

@Configuration
@EnableConfigurationProperties(JwtProperties.class)
public class ProPertyConfig {
}
Original file line number Diff line number Diff line change
@@ -1,5 +1,8 @@
package com.helpmeCookies.global.exception;

import com.helpmeCookies.global.ApiResponse.ApiResponse;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;

Expand All @@ -10,8 +13,8 @@
public class GlobalExceptionHandler {

@ExceptionHandler(ResourceNotFoundException.class)
public String handleResourceNotFoundException() {
return "해당 리소스를 찾을 수 없습니다.";
public ResponseEntity<ApiResponse<Void>> handleResourceNotFoundException() {
return ResponseEntity.badRequest().body(ApiResponse.error(HttpStatus.BAD_REQUEST,"해당 리소스를 찾을 수 없습니다."));
}

@ExceptionHandler(DuplicateRequestException.class)
Expand Down
20 changes: 20 additions & 0 deletions src/main/java/com/helpmeCookies/global/jwt/JwtProperties.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
package com.helpmeCookies.global.jwt;

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

import lombok.Getter;
import lombok.Setter;

@Component
@ConfigurationProperties(prefix = "jwt")
@Getter
@Setter
public class JwtProperties {
private String secret;
private long accessTokenExpireTime;
private long refreshTokenExpireTime;

public JwtProperties() {
}
}
11 changes: 6 additions & 5 deletions src/main/java/com/helpmeCookies/global/jwt/JwtProvider.java
Original file line number Diff line number Diff line change
Expand Up @@ -12,12 +12,13 @@
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.RequiredArgsConstructor;

@Component
@RequiredArgsConstructor
public class JwtProvider implements InitializingBean {
private String secret = "4099a46b-39db-4860-a61b-2ae76ea24c43";
private long accessTokenExpireTime = 1800000; // 30 minutes;
private long refreshTokenExpireTime = 259200000; // 3 days;

private final JwtProperties jwtProperties;
private Key secretKey;
private static final String ROLE = "role";
private static final String IS_ACCESS_TOKEN = "isAccessToken";
Expand Down Expand Up @@ -92,7 +93,7 @@ private JwtUser claimsToJwtUser(Claims claims) {
}

private String generateToken(JwtUser jwtUser, boolean isAccessToken) {
long expireTime = isAccessToken ? accessTokenExpireTime : refreshTokenExpireTime;
long expireTime = isAccessToken ? jwtProperties.getAccessTokenExpireTime() : jwtProperties.getRefreshTokenExpireTime();
Date expireDate = new Date(System.currentTimeMillis() + expireTime);
return Jwts.builder()
.signWith(secretKey)
Expand All @@ -112,6 +113,6 @@ private Claims extractClaims(String rawToken) {

@Override
public void afterPropertiesSet() {
secretKey = new SecretKeySpec(secret.getBytes(), SignatureAlgorithm.HS256.getJcaName());
secretKey = new SecretKeySpec(jwtProperties.getSecret().getBytes(), SignatureAlgorithm.HS256.getJcaName());
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,6 @@
@Component
public class JwtAuthenticationFilter extends OncePerRequestFilter {
private final JwtProvider jwtProvider;

private static final String AUTHORIZATION_HEADER = "Authorization";

@Override
Expand All @@ -46,6 +45,9 @@ protected void doFilterInternal(HttpServletRequest request, HttpServletResponse
Authentication authentication = new UsernamePasswordAuthenticationToken(jwtUser, null,
jwtUser.getAuthorities());
SecurityContextHolder.getContext().setAuthentication(authentication);
} else {
log.info("유효하지 않은 토큰 발생");
response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "토큰이 유효하지 않습니다.");
}

filterChain.doFilter(request, response);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,9 @@ public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
"/actuator/**",
"/v1/**",
"swagger-ui/**",
"/test/signup"
"/test/signup",
"/v1/artist",
"/v1/artists"
).permitAll()
.anyRequest().authenticated()
).exceptionHandling((exception) -> exception
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
package com.helpmeCookies.product.controller;

import com.helpmeCookies.global.ApiResponse.ApiResponse;
import com.helpmeCookies.global.ApiResponse.SuccessCode;
import com.helpmeCookies.product.dto.ImageUpload;
import static com.helpmeCookies.product.util.SortUtil.convertProductSort;

Expand Down Expand Up @@ -29,6 +31,11 @@ public class ProductController implements ProductApiDocs {
private final ProductService productService;
private final ProductImageService productImageService;

@PostMapping("/successTest")
public ResponseEntity<ApiResponse<Void>> saveTest() {
return ResponseEntity.ok(ApiResponse.success(SuccessCode.OK));
}

@PostMapping
public ResponseEntity<Void> saveProduct(@RequestBody ProductRequest productRequest) {
Product product = productService.save(productRequest);
Expand Down
Original file line number Diff line number Diff line change
@@ -1,14 +1,14 @@
package com.helpmeCookies.user.controller;

import com.helpmeCookies.global.ApiResponse.ApiResponse;
import com.helpmeCookies.global.ApiResponse.SuccessCode;
import com.helpmeCookies.global.jwt.JwtUser;
import com.helpmeCookies.user.controller.apiDocs.ArtistApiDocs;
import com.helpmeCookies.user.dto.ArtistInfoPage;
import com.helpmeCookies.user.dto.request.BusinessArtistReq;
import com.helpmeCookies.user.dto.request.StudentArtistReq;
import com.helpmeCookies.user.dto.response.ArtistDetailsRes;
import com.helpmeCookies.user.service.ArtistService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import org.springframework.data.domain.PageRequest;
import org.springframework.http.ResponseEntity;
Expand All @@ -26,44 +26,47 @@ public class ArtistController implements ArtistApiDocs {
private final ArtistService artistService;

@PostMapping("/v1/artists/students")
public ResponseEntity<String> registerStudents(
public ResponseEntity<ApiResponse<Void>> registerStudents(
@RequestBody StudentArtistReq artistDetailsReq,
@AuthenticationPrincipal JwtUser jwtUser
) {
artistService.registerStudentsArtist(artistDetailsReq, jwtUser.getId());
return ResponseEntity.ok().build();
return ResponseEntity.ok((ApiResponse.success(SuccessCode.OK)));
}

@PostMapping("/v1/artists/bussinesses")
public ResponseEntity<String> registerbussinsess(
public ResponseEntity<ApiResponse<Void>> registerbussinsess(
@RequestBody BusinessArtistReq businessArtistReq,
@AuthenticationPrincipal JwtUser jwtUser
) {
artistService.registerBusinessArtist(businessArtistReq, jwtUser.getId());
return ResponseEntity.ok().build();
return ResponseEntity.ok((ApiResponse.success(SuccessCode.OK)));
}

@GetMapping("/v1/artists/{userId}")
public ArtistDetailsRes getArtist(
public ResponseEntity<ApiResponse<ArtistDetailsRes>> getArtist(
@PathVariable Long userId
) {
return artistService.getArtistDetails(userId);
ArtistDetailsRes artistDetailsRes = artistService.getArtistDetails(userId);
return ResponseEntity.ok((ApiResponse.success(SuccessCode.OK, artistDetailsRes)));
}

@GetMapping("/v1/artist")
public ArtistDetailsRes getArtist(
public ResponseEntity<ApiResponse<ArtistDetailsRes>> getArtist(
@AuthenticationPrincipal JwtUser jwtUser
) {
return artistService.getArtistDetails(jwtUser.getId());
ArtistDetailsRes artistDetailsRes = artistService.getArtistDetails(jwtUser.getId());
return ResponseEntity.ok((ApiResponse.success(SuccessCode.OK, artistDetailsRes)));
}

@GetMapping("/v1/artists")
public ResponseEntity<ArtistInfoPage.Paging> getArtistsByPage(
public ResponseEntity<ApiResponse<ArtistInfoPage.Paging>> getArtistsByPage(
@RequestParam("query") String query,
@RequestParam(name = "size", required = false, defaultValue = "20") int size,
@RequestParam("page") int page
) {
var pageable = PageRequest.of(page, size);
return ResponseEntity.ok(artistService.getArtistsByPage(query, pageable));
ArtistInfoPage.Paging artistInfoPage = artistService.getArtistsByPage(query, pageable);
return ResponseEntity.ok((ApiResponse.success(SuccessCode.OK, artistInfoPage)));
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ public JwtToken signup() {
}

@GetMapping("/oauth2/login/kakao")
public JwtToken ttt(@AuthenticationPrincipal OAuth2User oAuth2User) {
public JwtToken loginKakao(@AuthenticationPrincipal OAuth2User oAuth2User) {
KakaoOAuth2Response kakaoUser = KakaoOAuth2Response.from(oAuth2User.getAttributes());
return jwtProvider.createToken(userDetailsService.loadUserByEmail(kakaoUser.email(), kakaoUser.nickname()));
}
Expand Down
44 changes: 29 additions & 15 deletions src/main/java/com/helpmeCookies/user/controller/UserController.java
Original file line number Diff line number Diff line change
@@ -1,9 +1,13 @@
package com.helpmeCookies.user.controller;

import java.io.IOException;
import java.util.List;

import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.web.PageableDefault;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.web.bind.annotation.DeleteMapping;
Expand All @@ -13,14 +17,19 @@
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.helpmeCookies.global.ApiResponse.ApiResponse;
import com.helpmeCookies.global.ApiResponse.SuccessCode;
import com.helpmeCookies.global.jwt.JwtUser;
import com.helpmeCookies.user.controller.apiDocs.UserApiDocs;
import com.helpmeCookies.user.dto.UserDto;
import com.helpmeCookies.user.dto.response.UserCommonInfoRes;
import com.helpmeCookies.user.dto.request.UserReq;
import com.helpmeCookies.user.dto.response.UserDetailsInfoRes;
import com.helpmeCookies.user.dto.UserTypeDto;
import com.helpmeCookies.user.dto.response.UserFollowingRes;
import com.helpmeCookies.user.dto.response.UserImageResponse;
import com.helpmeCookies.user.service.UserService;

import lombok.RequiredArgsConstructor;
Expand All @@ -32,60 +41,65 @@ public class UserController implements UserApiDocs {


@GetMapping("/v1/users")
public ResponseEntity<UserCommonInfoRes> getUsers(
public ResponseEntity<ApiResponse<UserCommonInfoRes>> getUsers(
@AuthenticationPrincipal JwtUser jwtUser
) {
return ResponseEntity.ok(UserCommonInfoRes.fromDto(userService.getUserInfo(jwtUser.getId())));
UserCommonInfoRes userCommonInfoRes = UserCommonInfoRes.fromDto(userService.getUserInfo(jwtUser.getId()));
return ResponseEntity.ok(ApiResponse.success(SuccessCode.OK, userCommonInfoRes));
}

@GetMapping("/v1/users/details")
public ResponseEntity<UserDetailsInfoRes> getUserDetails(
public ResponseEntity<ApiResponse<UserDetailsInfoRes>> getUserDetails(
@AuthenticationPrincipal JwtUser jwtUser
) {
return ResponseEntity.ok(UserDetailsInfoRes.fromDto(userService.getUserInfo(jwtUser.getId())));
UserDetailsInfoRes userDetailsInfoRes = UserDetailsInfoRes.fromDto(userService.getUserInfo(jwtUser.getId()));

return ResponseEntity.ok(ApiResponse.success(SuccessCode.OK, userDetailsInfoRes));
}

@GetMapping("/v1/users/type")
public ResponseEntity<UserTypeDto> getUserType(
public ResponseEntity<ApiResponse<UserTypeDto>> getUserType(
@AuthenticationPrincipal JwtUser jwtUser
) {
return ResponseEntity.ok(userService.getUserType(jwtUser.getId()));
UserTypeDto userTypeDto = userService.getUserType(jwtUser.getId());
return ResponseEntity.ok(ApiResponse.success(SuccessCode.OK, userTypeDto));
}

@PutMapping("/v1/users")
public String updateUser(
public ResponseEntity<ApiResponse<UserDto>> updateUser(
@AuthenticationPrincipal JwtUser jwtUser,
@RequestBody UserReq userReq
) {
// UserInfoDto를 통해서 유저 정보를 수정한다.
userService.updateUser(userReq, jwtUser.getId());
return "ok";
UserDto userDto = userService.updateUser(userReq.toUserCommonInfoDto(), userReq.toUserInfoDto(), jwtUser.getId());
return ResponseEntity.ok(ApiResponse.success(SuccessCode.OK, userDto));
}

@PostMapping("/v1/users/following/{artistId}")
public ResponseEntity<String> followArtist(
public ResponseEntity<ApiResponse<Void>> followArtist(
@AuthenticationPrincipal JwtUser jwtUser,
@PathVariable Long artistId
) {
userService.followArtist(jwtUser.getId(), artistId);
return ResponseEntity.ok().build();
return ResponseEntity.ok(ApiResponse.success(SuccessCode.OK));
}

@DeleteMapping("/v1/users/following/{artistId}")
public ResponseEntity<String> unfollowArtist(
public ResponseEntity<ApiResponse<Void>> unfollowArtist(
@AuthenticationPrincipal JwtUser jwtUser,
@PathVariable Long artistId
) {
userService.unfollowArtist(jwtUser.getId(), artistId);
return ResponseEntity.ok().build();
return ResponseEntity.ok(ApiResponse.success(SuccessCode.OK));
}

@GetMapping("/v1/users/following")
public ResponseEntity<Page<UserFollowingRes>> getFollowingList(
public ResponseEntity<ApiResponse<Page<UserFollowingRes>>> getFollowingList(
@AuthenticationPrincipal JwtUser jwtUser,
@PageableDefault(size = 10, sort = "createdAt", direction = Sort.Direction.DESC) Pageable pageable
) {
return ResponseEntity.ok(userService.getFollowingWithPaging(jwtUser.getId(), pageable));
Page<UserFollowingRes> followingList = userService.getFollowingWithPaging(jwtUser.getId(), pageable);
return ResponseEntity.ok(ApiResponse.success(SuccessCode.OK, followingList));
}

@DeleteMapping("/v1/users")
Expand Down
Loading

0 comments on commit eff003f

Please sign in to comment.