Skip to content

Commit

Permalink
Merge pull request #106 from Team-2m4t/feat/#105
Browse files Browse the repository at this point in the history
[feat] ν”„λ‘œν•„ 사진 μ—…λ‘œλ“œ κ΅¬ν˜„(#105)
  • Loading branch information
RudinP authored May 6, 2022
2 parents 9106dc9 + 8afdce1 commit 1d441c6
Show file tree
Hide file tree
Showing 11 changed files with 170 additions and 8 deletions.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ build/
!**/src/test/**/build/
src/main/generated
src/main/resources/application.yml
src/main/resources/aws.yml
src/main/generated
.DS_Store

Expand Down
3 changes: 2 additions & 1 deletion build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,8 @@ dependencies {
compileOnly 'org.projectlombok:lombok'
annotationProcessor 'org.projectlombok:lombok'
testImplementation 'org.springframework.boot:spring-boot-starter-test'

compileOnly 'org.springframework.cloud:spring-cloud-starter-aws:2.0.1.RELEASE'

implementation group: 'io.jsonwebtoken', name: 'jjwt-api', version: '0.11.2'
implementation group: 'io.jsonwebtoken', name: 'jjwt-impl', version: '0.11.2'
implementation group: 'io.jsonwebtoken', name: 'jjwt-jackson', version: '0.11.2'
Expand Down
9 changes: 7 additions & 2 deletions src/main/java/hyangyu/server/ServerApplication.java
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,17 @@

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;

@SpringBootApplication
public class ServerApplication {

public static final String APPLICATION_LOCATIONS = "spring.config.location="
+ "classpath:application.yml,"
+ "classpath:aws.yml";
public static void main(String[] args) {
SpringApplication.run(ServerApplication.class, args);
new SpringApplicationBuilder(ServerApplication.class)
.properties(APPLICATION_LOCATIONS)
.run(args);
}

}
38 changes: 35 additions & 3 deletions src/main/java/hyangyu/server/api/UserApi.java
Original file line number Diff line number Diff line change
Expand Up @@ -4,23 +4,28 @@
import hyangyu.server.dto.ResponseDto;
import hyangyu.server.dto.user.UserDto;
import hyangyu.server.service.UserService;
import lombok.RequiredArgsConstructor;

import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import hyangyu.server.aws.S3Uploader;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.IOException;

@RestController
@RequiredArgsConstructor
@RequestMapping("/api/user")
public class UserApi {
private final UserService userService;
private final S3Uploader s3Uploader;

public UserApi(UserService userService) {
this.userService = userService;
}

@PostMapping("/test-redirect")
public void testRedirect(HttpServletResponse response) throws IOException {
Expand Down Expand Up @@ -54,6 +59,33 @@ public ResponseEntity<ResponseDto> modifyUsername(HttpServletRequest request, @R
return ResponseEntity.ok(userService.modifyUsername(userDto, modifiedUsername));
}

@PostMapping("/image")
@PreAuthorize("hasAnyRole('USER','ADMIN')")
public ResponseEntity<ResponseDto> uploadProfileImage(HttpServletRequest request, @RequestParam("images")MultipartFile multipartFile) throws IOException {
UserDto userDto = userService.getMyUserWithAuthorities();
if(userDto.getImage() != null)
s3Uploader.delete(userDto.getImage());
String imgurl = s3Uploader.upload(multipartFile, "static");
return ResponseEntity.ok(userService.modifyImg(userDto.getEmail(), imgurl));
}

/*@DeleteMapping("/image")
@PreAuthorize("hasAnyRole('USER','ADMIN')")
public ResponseEntity<ResponseDto> deleteProfileImage(HttpServletRequest request) throws IOException {
UserDto userDto = userService.getMyUserWithAuthorities();
s3Uploader.delete(userDto.getImage());
return ResponseEntity.ok(new ResponseDto(HttpStatus.OK.value(),"ν”„λ‘œν•„ 이미지가 μ •μƒμ μœΌλ‘œ μ‚­μ œλ˜μ—ˆμŠ΅λ‹ˆλ‹€."));
}*/

@GetMapping("/image")
@PreAuthorize("hasAnyRole('USER','ADMIN')")
public ResponseEntity<ResponseDto> getProfileImage(HttpServletRequest request){
UserDto userDto = userService.getMyUserWithAuthorities();
String imgPath = s3Uploader.getThumbnailPath(userDto.getImage());
return ResponseEntity.ok(new ResponseDto(HttpStatus.OK.value(), imgPath));
}


@PostMapping("/password")
public ResponseEntity<ResponseDto> modifyPassword(@RequestBody ModificationDto user){
return ResponseEntity.ok(userService.modifyPassword(user.getEmail(), user.getPassword()));
Expand Down
81 changes: 81 additions & 0 deletions src/main/java/hyangyu/server/aws/S3Uploader.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
package hyangyu.server.aws;

import com.amazonaws.services.s3.AmazonS3Client;
import com.amazonaws.services.s3.model.AmazonS3Exception;
import com.amazonaws.services.s3.model.CannedAccessControlList;
import com.amazonaws.services.s3.model.PutObjectRequest;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Optional;
import java.util.UUID;

@Slf4j
@RequiredArgsConstructor
@Service
public class S3Uploader {

private final AmazonS3Client amazonS3Client;

@Value("${cloud.aws.s3.bucket}")
public String bucket; // S3 버킷 이름

public String upload(MultipartFile multipartFile, String dirName) throws IOException {
File uploadFile = convert(multipartFile) // 파일 λ³€ν™˜ν•  수 μ—†μœΌλ©΄ μ—λŸ¬
.orElseThrow(() -> new IllegalArgumentException("error: MultipartFile -> File convert fail"));

return upload(uploadFile, dirName);
}

public void delete(String name) {
if(!amazonS3Client.doesObjectExist(bucket, name))
throw new AmazonS3Exception("Object " +name+ " does not exist!");
amazonS3Client.deleteObject(bucket,name);
}

// S3둜 파일 μ—…λ‘œλ“œν•˜κΈ°
private String upload(File uploadFile, String dirName) {
String fileName = dirName + "/" + UUID.randomUUID() + uploadFile.getName(); // S3에 μ €μž₯된 파일 이름
String uploadImageUrl = putS3(uploadFile, fileName); // s3둜 μ—…λ‘œλ“œ
removeNewFile(uploadFile);
return fileName;
}

// S3둜 μ—…λ‘œλ“œ
private String putS3(File uploadFile, String fileName) {
amazonS3Client.putObject(new PutObjectRequest(bucket, fileName, uploadFile).withCannedAcl(CannedAccessControlList.PublicRead));
return amazonS3Client.getUrl(bucket, fileName).toString();
}

public String getThumbnailPath(String path) {
return amazonS3Client.getUrl(bucket, path).toString();
}

// λ‘œμ»¬μ— μ €μž₯된 이미지 μ§€μš°κΈ°
private void removeNewFile(File targetFile) {
if (targetFile.delete()) {
//log.info("File delete success");
return;
}
//log.info("File delete fail");
}

// λ‘œμ»¬μ— 파일 μ—…λ‘œλ“œ ν•˜κΈ°
private Optional<File> convert(MultipartFile file) throws IOException {
File convertFile = new File(System.getProperty("user.dir") + "/" + file.getOriginalFilename());
if (convertFile.createNewFile()) { // λ°”λ‘œ μœ„μ—μ„œ μ§€μ •ν•œ κ²½λ‘œμ— File이 생성됨 (κ²½λ‘œκ°€ 잘λͺ»λ˜μ—ˆλ‹€λ©΄ 생성 λΆˆκ°€λŠ₯)
try (FileOutputStream fos = new FileOutputStream(convertFile)) { // FileOutputStream 데이터λ₯Ό νŒŒμΌμ— λ°”μ΄νŠΈ 슀트림으둜 μ €μž₯ν•˜κΈ° μœ„ν•¨
fos.write(file.getBytes());
}
return Optional.of(convertFile);
}

return Optional.empty();
}
}
31 changes: 31 additions & 0 deletions src/main/java/hyangyu/server/config/AmazonS3Config.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
package hyangyu.server.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 AmazonS3Config {

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

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

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

@Bean
public AmazonS3Client amazonS3Client() {
BasicAWSCredentials awsCreds = new BasicAWSCredentials(accessKey, secretKey);
return (AmazonS3Client) AmazonS3ClientBuilder.standard()
.withRegion(region)
.withCredentials(new AWSStaticCredentialsProvider(awsCreds))
.build();
}
}
1 change: 1 addition & 0 deletions src/main/java/hyangyu/server/config/SecurityConfig.java
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,7 @@ protected void configure(HttpSecurity httpSecurity) throws Exception {
.antMatchers("/api/user/username").permitAll()
.antMatchers("/api/user/password").permitAll()
.antMatchers("/api/user").permitAll()
.antMatchers("/api/user/image").permitAll()
.antMatchers("/api/block/{reportedId}").permitAll()
.antMatchers("/api/display/{displayId}").permitAll()
.antMatchers("/api/authnum").permitAll()
Expand Down
6 changes: 5 additions & 1 deletion src/main/java/hyangyu/server/domain/User.java
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ public class User {
@NotNull
private String token;

@Column(length = 50)
@Column
private String image;

@ManyToMany
Expand Down Expand Up @@ -75,5 +75,9 @@ public void setPassword(String password) {
public void setUsername(String username) {
this.username = username;
}

public void setImage(String img) {
this.image = img;
}

}
1 change: 0 additions & 1 deletion src/main/java/hyangyu/server/dto/user/UserDto.java
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,6 @@ public class UserDto {

private String token;

@Size(max = 50)
private String image;

private Set<AuthorityDto> authorityDtoSet;
Expand Down
7 changes: 7 additions & 0 deletions src/main/java/hyangyu/server/service/UserService.java
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,13 @@ public ResponseDto modifyPassword(String email, String password) {
return new ResponseDto(HttpStatus.OK.value(), email+"λ‹˜μ˜ λΉ„λ°€λ²ˆν˜Έκ°€ λ³€κ²½λ˜μ—ˆμŠ΅λ‹ˆλ‹€.");
}

@Transactional
public ResponseDto modifyImg(String email, String imgurl) {
User userEntity = userRepository.findByEmail(email).orElseThrow(() ->new IllegalArgumentException("ν•΄λ‹Ή νšŒμ›μ΄ μ—†μŠ΅λ‹ˆλ‹€."));
userEntity.setImage(imgurl);
return new ResponseDto(HttpStatus.OK.value(), email+"λ‹˜μ˜ ν”„λ‘œν•„ 사진이 λ³€κ²½λ˜μ—ˆμŠ΅λ‹ˆλ‹€.");
}

@Transactional
public ResponseDto deleteMyUser(UserDto userDto) {
User user = userRepository.findById(userDto.getUserId())
Expand Down
Binary file added 캑처.PNG
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.

0 comments on commit 1d441c6

Please sign in to comment.