Skip to content

Commit

Permalink
Merge pull request #80 from wooyeon0626/feature/join
Browse files Browse the repository at this point in the history
[REFACTOR] ProfilePhoto 업로드 저장소를 GCP Storage -> lightsail bucket으로 변경 및 관련 코드 수정
  • Loading branch information
easyoungcode authored Feb 5, 2024
2 parents 66a76a5 + f2f617e commit cd0841f
Show file tree
Hide file tree
Showing 4 changed files with 56 additions and 20 deletions.
3 changes: 2 additions & 1 deletion build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,8 @@ dependencies {
//fcm
implementation 'com.google.firebase:firebase-admin:9.1.1'
implementation group: 'com.squareup.okhttp3', name: 'okhttp', version: '4.2.2'

// lightsail
implementation 'software.amazon.awssdk:s3:2.17.100'
}

tasks.named('test') {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,7 @@ public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Excepti
.and()
.authorizeHttpRequests()
.antMatchers("/auth/**").permitAll()
.antMatchers("/users/**").permitAll()
.antMatchers("/encrypt/**").permitAll()
.antMatchers("/api/**").permitAll()
.anyRequest().authenticated()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
import com.wooyeon.yeon.user.service.UserService;
import lombok.RequiredArgsConstructor;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
Expand All @@ -31,6 +32,8 @@ public class UserController {
private final ProfileService profileService;
private final Map<String, SseEmitter> userEmitters = new ConcurrentHashMap<>();

@Value("${email-auth-background-image}")
private String emailAuthBackgroundImg;

// 사용자에게 인증메일 전송 및 프론트엔드와 SSE 연결
@PostMapping(value = "/auth/email", produces = "application/json;charset=UTF-8")
Expand Down Expand Up @@ -65,6 +68,7 @@ public ModelAndView verifyEmail(@RequestParam String auth) {
log.info("verify 프론트에게 : "+emailAuthResponseDto);

ModelAndView mv = new ModelAndView("email_auth_verify");
mv.addObject("backgroundImg", emailAuthBackgroundImg);

return mv;
}
Expand Down
68 changes: 49 additions & 19 deletions src/main/java/com/wooyeon/yeon/user/service/ProfileService.java
Original file line number Diff line number Diff line change
@@ -1,7 +1,5 @@
package com.wooyeon.yeon.user.service;

import com.google.cloud.storage.BlobInfo;
import com.google.cloud.storage.Storage;
import com.wooyeon.yeon.user.domain.Profile;
import com.wooyeon.yeon.user.domain.ProfilePhoto;
import com.wooyeon.yeon.user.dto.ProfileRequestDto;
Expand All @@ -13,6 +11,12 @@
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import software.amazon.awssdk.auth.credentials.AwsBasicCredentials;
import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider;
import software.amazon.awssdk.core.sync.RequestBody;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.s3.S3Client;
import software.amazon.awssdk.services.s3.model.PutObjectRequest;

import java.io.IOException;
import java.util.List;
Expand All @@ -25,10 +29,28 @@ public class ProfileService {
private final ProfileRepository profileRepository;
private final ProfilePhotoRepository profilePhotoRepository;

@Value("${spring.cloud.gcp.storage.bucket}") // application.yml에 써둔 bucket 이름
@Value("${lightsail.instanceName}") // Lightsail 인스턴스 이름
private String lightsailInstanceName;

@Value("${lightsail.accessKey}")
private String accessKey;

@Value("${lightsail.secretKey}")
private String secretKey;

@Value("${lightsail.region}")
private String region;

@Value("${lightsail.bucketName}")
private String bucketName;

private final Storage storage;
private S3Client createS3Client() {
S3Client s3Client = S3Client.builder()
.region(Region.of(region))
.credentialsProvider(StaticCredentialsProvider.create(AwsBasicCredentials.create(accessKey, secretKey)))
.build();
return s3Client;
}

public ProfileResponseDto insertProfile(ProfileRequestDto profileRequestDto, List<MultipartFile> profilePhotoUpload) throws IOException {

Expand All @@ -45,32 +67,40 @@ public ProfileResponseDto insertProfile(ProfileRequestDto profileRequestDto, Lis
.build();
profileRepository.save(profile);

// GCS에 이미지 업로드
S3Client s3Client = createS3Client();
lightsailFileUpload(profile, s3Client, profilePhotoUpload);

ProfileResponseDto profileResponseDto = ProfileResponseDto.builder()
.statusCode(202)
.statusName("success")
.build();
return profileResponseDto;
}

void lightsailFileUpload(Profile profile, S3Client s3Client, List<MultipartFile> profilePhotoUpload) throws IOException {
// bucket에 파일 업로드
StringBuilder ext = new StringBuilder(); // 파일의 contentType
StringBuilder uuid = new StringBuilder(); // 저장할 때 쓸 파일 이름(uuid)
for (MultipartFile multipartFile : profilePhotoUpload) {
ext.append(multipartFile.getContentType());
ext.append(multipartFile.getOriginalFilename().split("\\.")[1]);
uuid.append(UUID.randomUUID());

BlobInfo blobInfo = storage.create(
BlobInfo.newBuilder(bucketName, uuid.toString())
.setContentType(ext.toString())
.build(),
multipartFile.getInputStream()
);
// 업로드할 파일 정보 설정
PutObjectRequest putObjectRequest = PutObjectRequest.builder()
.bucket(bucketName)
.key(uuid.toString()+"."+ext) // 확장자 추가
.contentType(ext.toString())
.build();

// 파일 업로드
s3Client.putObject(putObjectRequest, RequestBody.fromBytes(multipartFile.getBytes()));

// profilePhoto 테이블에 해당 사진 url 저장
ProfilePhoto profilePhoto = ProfilePhoto.builder()
.photoUrl("https://storage.googleapis.com/" + bucketName + "/" + uuid)
.photoUrl("https://" + bucketName + ".s3." + region + ".amazonaws.com/" + uuid.toString() + "." + ext)
.profile(profile)
.build();
profilePhotoRepository.save(profilePhoto);
}

ProfileResponseDto profileResponseDto = ProfileResponseDto.builder()
.statusCode(202)
.statusName("success")
.build();
return profileResponseDto;
}
}

0 comments on commit cd0841f

Please sign in to comment.