Skip to content

Commit

Permalink
Merge pull request #98 from Developer-Wikis/feature/#97
Browse files Browse the repository at this point in the history
Feature/#97
  • Loading branch information
jhdl0157 authored Nov 25, 2022
2 parents e4ffe17 + 2faa0d5 commit 1e3956f
Show file tree
Hide file tree
Showing 12 changed files with 209 additions and 3 deletions.
3 changes: 3 additions & 0 deletions build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,9 @@ dependencies {
testImplementation("org.testcontainers:junit-jupiter:1.17.3")

implementation 'com.google.code.gson:gson:2.8.9'
// AWS 의존성 추가
// https://mvnrepository.com/artifact/org.springframework.cloud/spring-cloud-starter-aws
implementation 'org.springframework.cloud:spring-cloud-starter-aws:2.2.6.RELEASE'
}

tasks.named('test') {
Expand Down
36 changes: 36 additions & 0 deletions src/main/java/com/developer/wiki/config/S3Config.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
package com.developer.wiki.config;

import com.amazonaws.auth.AWSStaticCredentialsProvider;
import com.amazonaws.auth.BasicAWSCredentials;
import com.amazonaws.client.builder.AwsClientBuilder;
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.credentials.access-key}")
private String accessKey;

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

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

@Value("${cloud.aws.s3.endpoint}")
private String endPoint;

@Bean
public AmazonS3Client amazonS3Client() {
System.out.println("엔드 포인트!!!!!!!!!!!!!!!!!!!!!!!!!!!!"+endPoint);
BasicAWSCredentials awsCreds = new BasicAWSCredentials(accessKey,secretKey);
return (AmazonS3Client) AmazonS3ClientBuilder.standard()
.withCredentials(new AWSStaticCredentialsProvider(awsCreds))
.withEndpointConfiguration(new AwsClientBuilder.EndpointConfiguration(endPoint, region))
.build();
}
}
5 changes: 5 additions & 0 deletions src/main/java/com/developer/wiki/oauth/User.java
Original file line number Diff line number Diff line change
Expand Up @@ -51,4 +51,9 @@ public UserResponseDto toDto(){
public void updateRefreshToken(String token){
this.refreshToken=token;
}

public void changeUserName(String newUserName){
if(newUserName.isEmpty()) throw new BadRequestException("userName is empty");
this.name=newUserName;
}
}
1 change: 1 addition & 0 deletions src/main/java/com/developer/wiki/oauth/UserRepository.java
Original file line number Diff line number Diff line change
Expand Up @@ -6,4 +6,5 @@
public interface UserRepository extends JpaRepository<User,Long> {
Optional<User> findByEmail(String email);
Optional<User> findByRefreshToken(String token);
Boolean existsByName(String userName);
}
Original file line number Diff line number Diff line change
Expand Up @@ -3,28 +3,66 @@

import com.developer.wiki.common.exception.BadRequestException;
import com.developer.wiki.oauth.User;
import com.developer.wiki.oauth.dto.ImageDto;
import com.developer.wiki.oauth.dto.NicknameDto;
import com.developer.wiki.oauth.dto.UserResponseDto;
import com.developer.wiki.oauth.service.UserService;
import com.developer.wiki.oauth.util.AwsService;
import lombok.RequiredArgsConstructor;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.validation.Valid;
import java.io.IOException;
import java.util.Objects;
import java.util.UUID;

@RequiredArgsConstructor
@RestController
@RequestMapping("/api/v1/user")
public class UserController {
private final UserService userService;
private final AwsService awsService;

@GetMapping
public ResponseEntity<UserResponseDto> getUserInfo(@AuthenticationPrincipal User currentUser){
return ResponseEntity.ok().body(currentUser.toDto());
}

@DeleteMapping("/{userId}")
public ResponseEntity<String> deleteUSer(@AuthenticationPrincipal User currentUser, @PathVariable(name = "userId")Long userid){
public ResponseEntity<String> deleteUser(@AuthenticationPrincipal User currentUser, @PathVariable(name = "userId")Long userid){
if(!currentUser.getId().equals(userid)) throw new BadRequestException("Not Match Userid");
userService.deleteUser(currentUser.getId());
return ResponseEntity.ok("delete");
}



@PostMapping("/nickname/{userId}")
public ResponseEntity<NicknameDto> changeUserName(@AuthenticationPrincipal User currentUser,
@PathVariable(name = "userId")Long userId,
@RequestBody @Valid NicknameDto nicknameDto){
if(!currentUser.getId().equals(userId)) throw new BadRequestException("Not Match Userid");
String newUserName=userService.updateUserName(nicknameDto.getUserName(),userId);
return ResponseEntity.ok(new NicknameDto(newUserName));
}

@PostMapping("/image/{userId}")
public ResponseEntity<String> changeImg(@AuthenticationPrincipal User currentUser, @RequestParam("image") MultipartFile file, @PathVariable Long userId) throws IOException {
if(!currentUser.getId().equals(userId)) throw new BadRequestException("Not Match Userid");
if(file.isEmpty()) throw new BadRequestException("파일은 Null이 될수 없습니다.");
String originalName=file.getOriginalFilename();
System.out.println("!!!!!!!!!!!!!!!오리지널"+originalName);
String[] name=originalName.split("\\.");
System.out.println(name.length);
final String ext = name[1];
final String saveFileName = getUuid() +"."+ ext;
System.out.println(saveFileName);
return ResponseEntity.ok(awsService.upload(saveFileName,file));
}
private static String getUuid() {
return UUID.randomUUID().toString().replaceAll("-", "");
}
}
14 changes: 14 additions & 0 deletions src/main/java/com/developer/wiki/oauth/dto/ImageDto.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
package com.developer.wiki.oauth.dto;

import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Getter;
import lombok.NoArgsConstructor;

@Getter
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class ImageDto {
private String imageUrl;
}
19 changes: 19 additions & 0 deletions src/main/java/com/developer/wiki/oauth/dto/NicknameDto.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
package com.developer.wiki.oauth.dto;

import lombok.*;

import javax.validation.constraints.NotBlank;
import javax.validation.constraints.Pattern;
import javax.validation.constraints.Size;

@Getter
@Builder
@NoArgsConstructor
public class NicknameDto {
@NotBlank(message = "닉네임은 null일 수 없습니다.")
@Pattern(regexp="^(?=.*[a-z0-9가-힣])[a-z0-9가-힣]{2,10}$", message = "닉네임 조건 불일치")
private String userName;
public NicknameDto(String userName){
this.userName=userName;
}
}
13 changes: 13 additions & 0 deletions src/main/java/com/developer/wiki/oauth/service/UserService.java
Original file line number Diff line number Diff line change
@@ -1,10 +1,14 @@
package com.developer.wiki.oauth.service;

import com.developer.wiki.common.exception.BadRequestException;
import com.developer.wiki.common.exception.NotFoundException;
import com.developer.wiki.oauth.User;
import com.developer.wiki.oauth.UserRepository;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import javax.transaction.Transactional;
import java.util.Optional;

@Service
@RequiredArgsConstructor
Expand All @@ -15,4 +19,13 @@ public void deleteUser(Long userId){
userRepository.deleteById(userId);
}

@Transactional
public String updateUserName(String userName,Long userId){
if(userRepository.existsByName(userName)) throw new BadRequestException("닉네임 중복입니다.");
User user=userRepository.findById(userId)
.orElseThrow(()-> new NotFoundException("유저가 없습니다."));
user.changeUserName(userName);
return user.getName();
}

}
59 changes: 59 additions & 0 deletions src/main/java/com/developer/wiki/oauth/util/AwsService.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
package com.developer.wiki.oauth.util;


import com.amazonaws.AmazonClientException;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.model.Bucket;
import com.amazonaws.services.s3.model.PutObjectRequest;
import com.amazonaws.services.s3.transfer.TransferManager;
import com.amazonaws.services.s3.transfer.TransferManagerBuilder;
import com.amazonaws.services.s3.transfer.Upload;
import com.developer.wiki.config.S3Config;
import lombok.RequiredArgsConstructor;
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.IOException;
import java.util.List;
@Service
@RequiredArgsConstructor
public class AwsService {
// @Value("${cloud.aws.defaultUrl}")
private final String defaultUrl="https://kr.object.ncloudstorage.com/devwiki/";
//
// @Value("${cloud.aws.s3.bucket}")
private final String bucketName="devwiki";
private final S3Config s3Config;


public void S3Test(){


List<Bucket> buckets = s3Config.amazonS3Client().listBuckets();
System.out.println("Bucket List: ");
for (Bucket bucket : buckets) {
System.out.println(" name=" + bucket.getName() + ", creation_date=" + bucket.getCreationDate() + ", owner=" + bucket.getOwner().getId());
}

}

public String upload(String saveFileName,MultipartFile multipartFile) throws IOException {
File file = new File(System.getProperty("user.dir") + saveFileName);
multipartFile.transferTo(file);
final TransferManager transferManager = TransferManagerBuilder.standard().withS3Client(s3Config.amazonS3Client()).build();
System.out.println(saveFileName);
final PutObjectRequest request = new PutObjectRequest(bucketName, saveFileName, file);
final Upload upload = transferManager.upload(request);
try {
upload.waitForCompletion();
return defaultUrl+saveFileName;
} catch (AmazonClientException | InterruptedException amazonClientException) {
amazonClientException.printStackTrace();
return null;
}finally {
file.delete();
}
}
}
5 changes: 4 additions & 1 deletion src/main/resources/application-dev.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,9 @@ spring:
main:
allow-bean-definition-overriding: true
config:
import: application-oauth.yaml
import:
- application-oauth.yaml
- application-ncp.yaml
jpa:
open-in-view: false
show-sql: true
Expand All @@ -20,3 +22,4 @@ spring:
jasypt:
encryptor:
bean: jasyptStringEncryptor

13 changes: 13 additions & 0 deletions src/main/resources/application-ncp.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
cloud:
aws:
credentials:
access-key: ENC(cGBvyLuYjKZ6eldcPBUNLOuO08CGMKetB8njxUmcJOM=)
secret-key: ENC(mN3n2krPI0WFexB4NGfwdAuY6TK3GxT3GfvLtGy6AIf18xTnri3PUHO9l+y5jGiQf7qqI0s6B1M=)
stack:
auto: false
region:
static: ap-northeast-2
s3:
endpoint: https://kr.object.ncloudstorage.com
bucket: devwiki
defaultUrl : https://kr.object.ncloudstorage.com/devwiki
4 changes: 3 additions & 1 deletion src/main/resources/application.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,9 @@ spring:
main:
allow-bean-definition-overriding: true
config:
import: application-oauth.yaml
import:
- application-oauth.yaml
- application-ncp.yaml
jpa:
open-in-view: false
show-sql: true
Expand Down

0 comments on commit 1e3956f

Please sign in to comment.