Skip to content

Commit

Permalink
프로필 이미지 구현
Browse files Browse the repository at this point in the history
  • Loading branch information
HeeSung98 committed Dec 6, 2023
1 parent 95734bd commit d509e7c
Show file tree
Hide file tree
Showing 8 changed files with 146 additions and 65 deletions.
3 changes: 3 additions & 0 deletions user/build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,9 @@ dependencies {
//추가
implementation 'org.springframework.cloud:spring-cloud-starter-config'
implementation 'org.springframework.boot:spring-boot-starter-actuator'
//추가
implementation 'org.springframework.cloud:spring-cloud-starter-aws:2.2.6.RELEASE'
implementation 'org.springframework.cloud:spring-cloud-starter-config'
}

dependencyManagement {
Expand Down
32 changes: 32 additions & 0 deletions user/src/main/java/com/weather/user/config/AmazonS3Config.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
package com.weather.user.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() {
final BasicAWSCredentials Credentials = new BasicAWSCredentials(accessKey, secretKey);

return (AmazonS3Client) AmazonS3ClientBuilder
.standard()
.withRegion(region)
.withCredentials(new AWSStaticCredentialsProvider(Credentials))
.build();
}
}
18 changes: 13 additions & 5 deletions user/src/main/java/com/weather/user/controller/UserController.java
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,12 @@
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.UUID;

@Controller
@Log4j2
@RequiredArgsConstructor
Expand Down Expand Up @@ -101,17 +107,19 @@ public ResponseEntity<UserDTO> modify(@RequestBody UserDTO userDTO) {

@PatchMapping(value = "/api/profile/modify/image", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
@ResponseBody
public ResponseEntity<UserDTO> modifyImage(@RequestPart(value = "image", required = false) MultipartFile image,
@RequestPart("email") String email) {
public ResponseEntity<JSONObject> modifyImage(@RequestPart(value = "image", required = false) MultipartFile image,
@RequestPart("email") String email,
@RequestPart("fromSocial") Boolean fromSocial) {
log.info(" ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ modifyImage controller ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ");
log.info("email: " + email);
log.info("image: " + image);

//UserDTO result = userService.modify(userDTO);
userService.saveImage(email, image, fromSocial);

UserDTO temp = new UserDTO();
JSONObject result = new JSONObject();
result.put("result", true);

return new ResponseEntity<>(temp, HttpStatus.OK);
return new ResponseEntity<>(result, HttpStatus.OK);
}

@DeleteMapping("/api/profile/remove/{email}")
Expand Down
2 changes: 1 addition & 1 deletion user/src/main/java/com/weather/user/entity/User.java
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ public class User extends BaseEntity{
@Column(unique = true)
String email, nickname;

String name, phone, image, password;
String name, image, password;

boolean fromSocial, status;

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@
@Setter
@ToString
public class AuthUserDTO extends User implements OAuth2User {
private String email, password, name, nickname, image;
private String email, password, name, nickname, image, token;

private boolean fromSocial, status;

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -43,8 +43,8 @@ public void onAuthenticationSuccess(HttpServletRequest request, HttpServletRespo

try {
String token = jwtUtil.generateToken(authUserDTO.getNickname());
authUserDTO.setToken(token);
String result = objectMapper.writeValueAsString(authUserDTO);
result = result.replace("}", ", \"token\": \"" + token + "\"}");

response.setContentType("application/json;charset=utf-8");
response.getWriter().write(result);
Expand Down
11 changes: 7 additions & 4 deletions user/src/main/java/com/weather/user/service/UserService.java
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
import com.weather.user.dto.GoogleUserDTO;
import com.weather.user.dto.UserDTO;
import com.weather.user.entity.User;
import org.springframework.web.multipart.MultipartFile;


public interface UserService {
Expand All @@ -14,15 +15,17 @@ public interface UserService {

void signup(UserDTO userDTO);

UserDTO googleUserCheck(GoogleUserDTO googleUserDTO) throws Exception;

UserDTO googleUserAdditional(UserDTO userDTO) throws Exception;

UserDTO profile(String email);

UserDTO modify(UserDTO userDTO);

void remove(String email);
void saveImage(String email, MultipartFile image, boolean fromSocial);

UserDTO googleUserCheck(GoogleUserDTO googleUserDTO);

UserDTO googleUserAdditional(UserDTO userDTO) throws Exception;
void remove(String email);

default User dtoToEntity(UserDTO userDTO) {
User user = User.builder()
Expand Down
141 changes: 88 additions & 53 deletions user/src/main/java/com/weather/user/service/UserServiceImpl.java
Original file line number Diff line number Diff line change
@@ -1,16 +1,22 @@
package com.weather.user.service;

import com.amazonaws.services.s3.AmazonS3Client;
import com.amazonaws.services.s3.model.ObjectMetadata;
import com.weather.user.dto.GoogleUserDTO;
import com.weather.user.dto.UserDTO;
import com.weather.user.entity.User;
import com.weather.user.entity.UserRole;
import com.weather.user.repository.UserRepository;
import com.weather.user.util.JWTUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.oauth2.core.user.OAuth2User;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Optional;

@Service
Expand All @@ -19,6 +25,10 @@
public class UserServiceImpl implements UserService {
private final UserRepository userRepository;
private final PasswordEncoder passwordEncoder;
private final JWTUtil jwtUtil;
private final AmazonS3Client s3Client;
@Value("${cloud.aws.s3.bucket}")
private String bucket;

@Override
public boolean verifyEmail(String email) {
Expand Down Expand Up @@ -65,6 +75,53 @@ public void signup(UserDTO userDTO) {
userRepository.save(user);
}

@Override
public UserDTO googleUserCheck(GoogleUserDTO googleUserDTO) throws Exception{
log.info("ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ");
String email = googleUserDTO.getEmail();
String image = googleUserDTO.getPicture();
Optional<User> optionalUser = userRepository.findByEmail(email, true);

if(optionalUser.isPresent()) {
User user = optionalUser.get();
UserDTO result = entityToDTO(user);
result.setToken(jwtUtil.generateToken(user.getNickname()));
return result;
} else {
User user = User.builder()
.email(email)
.password(passwordEncoder.encode("1234"))
.image(image)
.fromSocial(true)
.status(true)
.build();
user.addRole(UserRole.USER);

userRepository.save(user);

UserDTO result = entityToDTO(user);
return result;
}
}

@Override
public UserDTO googleUserAdditional(UserDTO userDTO) throws Exception{
log.info("ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ");
Optional<User> optionalUser = userRepository.findByEmail(userDTO.getEmail(), true);

if(optionalUser.isPresent()) {
User user = optionalUser.get();
user.changeNickname(userDTO.getNickname());
user.changeName(userDTO.getName());
userRepository.save(user);
UserDTO result = entityToDTO(user);
result.setToken(jwtUtil.generateToken(user.getNickname()));
return result;
} else {
throw new Exception("잘못 된 접근입니다.");
}
}

@Override
public UserDTO profile(String email) {
Optional<User> optionalUser = userRepository.findByEmail(email);
Expand Down Expand Up @@ -94,12 +151,6 @@ public UserDTO modify(UserDTO userDTO) {
User user = optionalUser.get();

if(user.isStatus()) {
if(userDTO.getNickname() != null) {
user.changeNickname(userDTO.getNickname());
}
if(userDTO.getImage() != null) {
user.changeImage(userDTO.getImage());
}
if(userDTO.getPassword() != null) {
user.changePassword(passwordEncoder.encode(userDTO.getPassword()));
}
Expand All @@ -112,6 +163,36 @@ public UserDTO modify(UserDTO userDTO) {
}
}

@Override
public void saveImage(String email, MultipartFile image, boolean fromSocial) {
//실제 파일명에는 전체 경로가 들어오기 때문에 파일 이름만 추출
String originalName = image.getOriginalFilename();
log.info("originalName: " + image.getOriginalFilename());

LocalDateTime now = LocalDateTime.now();
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMddHHmmss");
String formattedNow = now.format(formatter);
String fileName = formattedNow + "_weatherfit_" + originalName;
String fileUrl = "https://" + bucket + ".s3.amazonaws.com/" + fileName;

try {
if (!s3Client.doesObjectExist(bucket, fileName)) {
ObjectMetadata metadata = new ObjectMetadata();
metadata.setContentType(image.getContentType());
metadata.setContentLength(image.getSize());
s3Client.putObject(bucket, fileName, image.getInputStream(), metadata);
}

Optional<User> optionalUser = userRepository.findByEmail(email, fromSocial);
User user = optionalUser.get();
user.changeImage(fileUrl);
userRepository.save(user);
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException("Failed to upload image to S3", e);
}
}

@Override
public void remove(String email) {
Optional<User> optionalUser = userRepository.findByEmail(email);
Expand All @@ -128,51 +209,5 @@ public void remove(String email) {
} else {
throw new Error("이미 탈퇴 처리중인 유저입니다.");
}

}

@Override
public UserDTO googleUserCheck(GoogleUserDTO googleUserDTO) {
log.info("ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ");
String email = googleUserDTO.getEmail();
String image = googleUserDTO.getPicture();
Optional<User> optionalUser = userRepository.findByEmail(email, true);

if(optionalUser.isPresent()) {
User user = optionalUser.get();
UserDTO result = entityToDTO(user);
return result;
} else {
User user = User.builder()
.email(email)
.password(passwordEncoder.encode("1234"))
.image(image)
.fromSocial(true)
.status(true)
.build();
user.addRole(UserRole.USER);

userRepository.save(user);

UserDTO result = entityToDTO(user);
return result;
}
}

@Override
public UserDTO googleUserAdditional(UserDTO userDTO) throws Exception{
log.info("ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ");
Optional<User> optionalUser = userRepository.findByEmail(userDTO.getEmail(), true);

if(optionalUser.isPresent()) {
User user = optionalUser.get();
user.changeNickname(userDTO.getNickname());
user.changeName(userDTO.getName());
userRepository.save(user);
UserDTO result = entityToDTO(user);
return result;
} else {
throw new Exception("잘못 된 접근입니다.");
}
}
}

0 comments on commit d509e7c

Please sign in to comment.