Skip to content

Commit

Permalink
Merge pull request #111 from kookmin-sw/backend/develop/v3
Browse files Browse the repository at this point in the history
Backend/develop/v3
  • Loading branch information
J-Yong99 authored Apr 27, 2024
2 parents db198ff + a2dd01d commit f64c989
Show file tree
Hide file tree
Showing 23 changed files with 1,365 additions and 119 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -50,12 +50,11 @@ public ResponseEntity<APIResponse<TokenResponseDTO.GetTempToken>> sendCode(

// 인증코드 검증
@PatchMapping("/verify")
public ResponseEntity<APIResponse> verifyCode(
public ResponseEntity<APIResponse<TokenResponseDTO.GetToken>> verifyCode(
@RequestBody AuthRequest.VerifyCode verifyCode,
@RequestHeader Long userId
) {
authService.verifyCode(verifyCode, userId);
return ResponseEntity.ok(APIResponse.of(SuccessCode.UPDATE_SUCCESS));
return ResponseEntity.ok(APIResponse.of(SuccessCode.UPDATE_SUCCESS, authService.verifyCode(verifyCode, userId)));
}

// 비밀번호 변경
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,11 @@ public static class registerUser {

private Long id;

private boolean notification;

private boolean dataUsage;

private String firebaseToken;

}
}
Original file line number Diff line number Diff line change
Expand Up @@ -103,16 +103,15 @@ public TokenResponseDTO.GetTempToken sendCode(AuthRequest.SendCode sendCode) {
}


public void verifyCode(AuthRequest.VerifyCode verifyCode, Long userId) {
public TokenResponseDTO.GetToken verifyCode(AuthRequest.VerifyCode verifyCode, Long userId) {
User user = userRepository.findById(userId).orElseThrow(() -> new IllegalArgumentException("잘못된 유저 정보"));
if(!Objects.equals(user.getVerificationCode(), verifyCode.getCode())) throw new IllegalArgumentException("잘못된 인증코드");
if (user.getRole() == Role.ROLE_TEMP_USER) {
userService.registerUserToCoreServer(user);
user.setRole(Role.ROLE_AUTH_USER);
}


userService.save(user);
return jwtTokenUtils.generateToken(provider, iss, user.getId(), user.getRole());
}

public void changePassword(AuthRequest.ChangePassword changePassword, Long userId) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,9 @@ public void registerUserToCoreServer(User user) {
.builder()
.email(user.getEmail())
.id(user.getId())
.notification(false)
.dataUsage(false)
.firebaseToken("")
.build()
);
}catch (Exception e){
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -79,7 +79,6 @@ void login() throws Exception {
fieldWithPath("data.accessToken").type(JsonFieldType.STRING).description("액세스 토큰"),
fieldWithPath("data.refreshToken").type(JsonFieldType.STRING).description("리프레시 토큰"),
fieldWithPath("data.role").type(JsonFieldType.STRING).description("사용자 권한")

)
))
.andDo(print());
Expand Down Expand Up @@ -129,11 +128,17 @@ void sendCode() throws Exception {

@Test
void verifyCode() throws Exception {
TokenResponseDTO.GetToken responseDTO = TokenResponseDTO.GetToken.builder()
.accessToken("accessToken")
.refreshToken("refresh")
.grantType("Bearer")
.role(Role.ROLE_AUTH_USER)
.build();
AuthRequest.VerifyCode verifyCode = AuthRequest.VerifyCode.builder()
.code("1234")
.build();

Mockito.doNothing().when(authService).verifyCode(any(AuthRequest.VerifyCode.class), any());
Mockito.when(authService.verifyCode(any(AuthRequest.VerifyCode.class), any())).thenReturn(responseDTO);

mockMvc.perform(RestDocumentationRequestBuilders.patch("/auth/verify")
.contentType(MediaType.APPLICATION_JSON)
Expand All @@ -154,7 +159,10 @@ void verifyCode() throws Exception {
fieldWithPath("code").type(JsonFieldType.STRING).description("응답 코드"),
fieldWithPath("msg").type(JsonFieldType.STRING).description("응답 메시지"),
fieldWithPath("detailMsg").type(JsonFieldType.STRING).description("상세 메시지"),
fieldWithPath("data").type(JsonFieldType.OBJECT).description("데이터 없음")
fieldWithPath("data.grantType").type(JsonFieldType.STRING).description("토큰 타입"),
fieldWithPath("data.accessToken").type(JsonFieldType.STRING).description("액세스 토큰"),
fieldWithPath("data.refreshToken").type(JsonFieldType.STRING).description("리프레시 토큰"),
fieldWithPath("data.role").type(JsonFieldType.STRING).description("사용자 권한")
)
))
.andDo(print());
Expand Down
1 change: 1 addition & 0 deletions backend/moment/moment-server/core/build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@ dependencies {
asciidoctorExt 'org.springframework.restdocs:spring-restdocs-asciidoctor' // asciidoctorExt에 spring-restdocs-asciidoctor 의존성 추가
testImplementation 'org.springframework.restdocs:spring-restdocs-mockmvc' // mockMvc 사용
implementation group: 'com.fasterxml.jackson.datatype', name: 'jackson-datatype-jsr310', version: '2.12.4'
implementation 'org.springframework.cloud:spring-cloud-starter-aws:2.2.6.RELEASE'

}
ext {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
package com.moment.core.config;

import com.amazonaws.auth.AWSStaticCredentialsProvider;
import com.amazonaws.auth.BasicAWSCredentials;
import com.amazonaws.services.s3.AmazonS3Client;
import com.amazonaws.services.s3.AmazonS3ClientBuilder;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class S3Config {

@Value("${cloud.aws.s3.credentials.access-key}")
private String accessKey;

@Value("${cloud.aws.s3.credentials.secret-key}")
private String secretKey;

@Value("${cloud.aws.s3.region.static}")
private String region;

@Bean
public AmazonS3Client amazonS3Client() {
BasicAWSCredentials credentials = new BasicAWSCredentials(accessKey, secretKey);

return (AmazonS3Client) AmazonS3ClientBuilder
.standard()
.withRegion(region)
.withCredentials(new AWSStaticCredentialsProvider(credentials))
.build();
}
}
Original file line number Diff line number Diff line change
@@ -1,24 +1,60 @@
package com.moment.core.controller;

import com.moment.core.service.S3Service;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.couchbase.CouchbaseProperties;
import org.springframework.core.env.Environment;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.time.LocalDateTime;

@RestController
@AllArgsConstructor
@Slf4j
public class RootController {

private final Environment env;
private final S3Service s3Service;

@GetMapping("/health-check")
public ResponseEntity<String> healthCheck() {
// 서버 아이디와 포트 출력
log.info("health-check called" );
return ResponseEntity.ok("I'm alive : " + env.getProperty("server.port"));
}

@PostMapping("/test/s3")
public ResponseEntity<String> testS3(
@RequestHeader Long userId,
@RequestPart MultipartFile recordFile
) {
try {
return ResponseEntity.ok(s3Service.uploadFile(recordFile, userId, LocalDateTime.now().toString(), true));
} catch (IOException e) {
throw new RuntimeException(e);
}
}

@PostMapping("/test/s3/folder")
public ResponseEntity<String> testS3Folder(
@RequestHeader Long userId,
@RequestParam String folderName
) {
s3Service.createFolder(userId.toString());
return ResponseEntity.ok("test-s3-folder called");
}

@DeleteMapping("/test/s3")
public ResponseEntity<String> deleteS3(
@RequestHeader Long userId,
@RequestParam String fileName
) {
// fileName = "users/" + userId.toString() + "/" + fileName;
fileName = "users/" + userId.toString();
s3Service.deleteFile(fileName);
return ResponseEntity.ok("delete-s3 called");
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
import com.moment.core.common.code.SuccessCode;
import com.moment.core.domain.user.User;
import com.moment.core.dto.request.UserRequestDTO;
import com.moment.core.service.S3Service;
import com.moment.core.service.UserService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.media.Content;
Expand All @@ -23,6 +24,7 @@
@RequestMapping("/core/user")
public class UserController {
private final UserService userService;
private final S3Service s3Service;

// 유저 등록
@PostMapping("/register")
Expand All @@ -34,7 +36,18 @@ public class UserController {
public ResponseEntity<APIResponse> registerUser(
@RequestBody UserRequestDTO.registerUser request
) {
s3Service.createFolder(request.getId().toString());
userService.save(request);
return ResponseEntity.ok(APIResponse.of(SuccessCode.INSERT_SUCCESS));
}

// 유저 설정 업데이트
@PatchMapping("/setting")
public ResponseEntity<APIResponse> updateUserSetting(
@RequestBody UserRequestDTO.updateUser request,
@RequestHeader Long userId
) {
userService.updateUserSetting(request, userId);
return ResponseEntity.ok(APIResponse.of(SuccessCode.UPDATE_SUCCESS));
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -21,5 +21,17 @@ public class User extends BaseEntity{
@Column(name = "email", nullable = false, unique = true)
private String email;

// 알림설정 유무
@Column(name = "notification", nullable = false)
private boolean notification;

// 데이터 사용 유무
@Column(name = "data_usage", nullable = false)
private boolean dataUsage;

// firebase token
@Column(name = "firebase_token")
private String firebaseToken;


}
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
package com.moment.core.dto.request;

import lombok.Builder;
import lombok.Getter;
import lombok.Setter;

Expand All @@ -13,6 +14,24 @@ public static class registerUser {

private Long id;

private boolean notification;

private boolean dataUsage;

private String firebaseToken;
}

@Getter
@Setter
@Builder
public static class updateUser {

private String email;

private boolean notification;

private boolean dataUsage;

private String firebaseToken;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@

import java.io.File;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
Expand All @@ -30,18 +31,20 @@ public class CardViewService {
private final TripService tripService;
private final TripFileService tripFileService;
private final ImageFileService imageFileService;
private final S3Service s3Service;


@Value("${file.path}")
private String filePath;

@Autowired
public CardViewService(CardViewRepository cardViewRepository, UserRepository userRepository, TripService tripService, TripFileService tripFileService, ImageFileService imageFileService) {
public CardViewService(CardViewRepository cardViewRepository, UserRepository userRepository, TripService tripService, TripFileService tripFileService, ImageFileService imageFileService, S3Service s3Service) {
this.cardViewRepository = cardViewRepository;
this.userRepository = userRepository;
this.tripService = tripService;
this.tripFileService = tripFileService;
this.imageFileService = imageFileService;
this.s3Service = s3Service;
}


Expand Down Expand Up @@ -69,7 +72,7 @@ public CardViewResponseDTO.GetCardView uploadRecord(CardViewRequestDTO.UploadRec
String fileName = createFileName(recordFile.getOriginalFilename());

// 로컬 저장소에 파일 저장
recordFile.transferTo(new File(getFullPath(fileName)));
String url = s3Service.uploadToS3(recordFile, userId, fileName, true);

CardView cardView = CardView.builder()
.recordedAt(uploadRecord.getRecordedAt())
Expand All @@ -83,7 +86,7 @@ public CardViewResponseDTO.GetCardView uploadRecord(CardViewRequestDTO.UploadRec
.location(uploadRecord.getLocation())
.recordFileStatus("WAIT")
.recordFileLength(length)
.recordFileUrl("")
.recordFileUrl(url)
.recordFileName(fileName)
// .user(user)
.tripFile(tripFile)
Expand All @@ -100,7 +103,7 @@ public CardViewResponseDTO.GetCardView uploadRecord(CardViewRequestDTO.UploadRec

private String createFileName(String originalFilename) {
String ext = extractExt(originalFilename);
String uuid = UUID.randomUUID().toString();
String uuid = LocalDateTime.now().toString();
return uuid + "." + ext;
}

Expand Down
Loading

0 comments on commit f64c989

Please sign in to comment.