diff --git a/null0912191014511_99741401_profile b/null0912191014511_99741401_profile deleted file mode 100644 index e69de29b..00000000 diff --git a/null0912191140231_512155661_profile b/null0912191140231_512155661_profile deleted file mode 100644 index e69de29b..00000000 diff --git a/src/main/generated/me/snaptime/user/domain/QUser.java b/src/main/generated/me/snaptime/user/domain/QUser.java index ce70c863..8dc71d29 100644 --- a/src/main/generated/me/snaptime/user/domain/QUser.java +++ b/src/main/generated/me/snaptime/user/domain/QUser.java @@ -24,8 +24,6 @@ public class QUser extends EntityPathBase { public final me.snaptime.common.QBaseTimeEntity _super = new me.snaptime.common.QBaseTimeEntity(this); - public final StringPath birthDay = createString("birthDay"); - //inherited public final DateTimePath createdDate = _super.createdDate; @@ -34,10 +32,10 @@ public class QUser extends EntityPathBase { //inherited public final DateTimePath lastModifiedDate = _super.lastModifiedDate; - public final StringPath loginId = createString("loginId"); - public final StringPath name = createString("name"); + public final StringPath nickName = createString("nickName"); + public final StringPath password = createString("password"); public final me.snaptime.profilePhoto.domain.QProfilePhoto profilePhoto; diff --git a/src/main/java/me/snaptime/alarm/dto/res/AlarmInfoResDto.java b/src/main/java/me/snaptime/alarm/dto/res/AlarmInfoResDto.java index 50651712..10e02162 100644 --- a/src/main/java/me/snaptime/alarm/dto/res/AlarmInfoResDto.java +++ b/src/main/java/me/snaptime/alarm/dto/res/AlarmInfoResDto.java @@ -19,7 +19,7 @@ public record AlarmInfoResDto( String previewText, AlarmType alarmType, Long snapId, - String senderLoginId, + String senderEmail, @Getter LocalDateTime createdDate @@ -36,7 +36,7 @@ public static AlarmInfoResDto toDtoByFollowAlarm(String senderProfilePhotoURL, S .alarmType(followAlarm.getAlarmType()) .createdDate(followAlarm.getCreatedDate()) .snapId(null) - .senderLoginId(followAlarm.getSender().getLoginId()) + .senderEmail(followAlarm.getSender().getEmail()) .build(); } @@ -53,7 +53,7 @@ public static AlarmInfoResDto toDtoBySnapAlarm(String senderProfilePhotoURL, Str .alarmType(snapAlarm.getAlarmType()) .createdDate(snapAlarm.getCreatedDate()) .snapId(snapAlarm.getSnap().getId()) - .senderLoginId(snapAlarm.getSender().getLoginId()) + .senderEmail(snapAlarm.getSender().getEmail()) .build(); } @@ -70,7 +70,7 @@ public static AlarmInfoResDto toDtoByReplyAlarm(String senderProfilePhotoURL, St .alarmType(replyAlarm.getAlarmType()) .createdDate(replyAlarm.getCreatedDate()) .snapId(replyAlarm.getSnap().getId()) - .senderLoginId(replyAlarm.getSender().getLoginId()) + .senderEmail(replyAlarm.getSender().getEmail()) .build(); } } diff --git a/src/main/java/me/snaptime/alarm/service/AlarmService.java b/src/main/java/me/snaptime/alarm/service/AlarmService.java index 24bf1cfe..94d6ba95 100644 --- a/src/main/java/me/snaptime/alarm/service/AlarmService.java +++ b/src/main/java/me/snaptime/alarm/service/AlarmService.java @@ -8,25 +8,25 @@ public interface AlarmService { /* snapAlarm을 읽음처리합니다. */ - void readSnapAlarm(String reqLoginId, Long snapAlarmId); + void readSnapAlarm(String reqEmail, Long snapAlarmId); //팔로우알림을 읽음처리합니다. - void readFollowAlarm(String reqLoginId, Long followAlarmId); + void readFollowAlarm(String reqEmail, Long followAlarmId); /* ReplyAlarm을 읽음처리합니다. */ - void readReplyAlarm(String reqLoginId, Long replyAlarmId); + void readReplyAlarm(String reqEmail, Long replyAlarmId); //유저의 모든 알림을 불러옵니다. - Object findAlarms(String reqLoginId); + Object findAlarms(String reqEmail); // 읽지않은 알림이 몇개인지 조회합니다. - Long findNotReadAlarmCnt(String reqLoginId); + Long findNotReadAlarmCnt(String reqEmail); /* 알림을 삭제합니다. 읽지않은 팔로우요청에 대한 알림의 경우 자동으로 요청거절이 됩니다. */ - void deleteAlarm(String reqLoginId, Long alarmId, AlarmType alarmType); + void deleteAlarm(String reqEmail, Long alarmId, AlarmType alarmType); } diff --git a/src/main/java/me/snaptime/alarm/service/impl/AlarmServiceImpl.java b/src/main/java/me/snaptime/alarm/service/impl/AlarmServiceImpl.java index 99d40ae8..49e0991e 100644 --- a/src/main/java/me/snaptime/alarm/service/impl/AlarmServiceImpl.java +++ b/src/main/java/me/snaptime/alarm/service/impl/AlarmServiceImpl.java @@ -38,13 +38,13 @@ public class AlarmServiceImpl implements AlarmService { @Override @Transactional - public void readSnapAlarm(String reqLoginId, Long snapAlarmId) { + public void readSnapAlarm(String reqEmail, Long snapAlarmId) { SnapAlarm snapAlarm = snapAlarmRepository.findById(snapAlarmId) .orElseThrow(() -> new CustomException(ExceptionCode.ALARM_NOT_EXIST)); // 자신한테 온 알림인지 여부체크 - isMyAlarm(reqLoginId,snapAlarm.getReceiver().getLoginId()); + isMyAlarm(reqEmail,snapAlarm.getReceiver().getEmail()); snapAlarm.readAlarm(); snapAlarmRepository.save(snapAlarm); @@ -52,12 +52,12 @@ public void readSnapAlarm(String reqLoginId, Long snapAlarmId) { @Override @Transactional - public void readFollowAlarm(String reqLoginId, Long followAlarmId) { + public void readFollowAlarm(String reqEmail, Long followAlarmId) { FollowAlarm followAlarm = followAlarmRepository.findById(followAlarmId) .orElseThrow(() -> new CustomException(ExceptionCode.ALARM_NOT_EXIST)); // 자신한테 온 알림인지 여부체크 - isMyAlarm(reqLoginId, followAlarm.getReceiver().getLoginId()); + isMyAlarm(reqEmail, followAlarm.getReceiver().getEmail()); followAlarm.readAlarm(); @@ -66,28 +66,28 @@ public void readFollowAlarm(String reqLoginId, Long followAlarmId) { @Override @Transactional - public void readReplyAlarm(String reqLoginId, Long replyAlarmId) { + public void readReplyAlarm(String reqEmail, Long replyAlarmId) { ReplyAlarm replyAlarm = replyAlarmRepository.findById(replyAlarmId) .orElseThrow(() -> new CustomException(ExceptionCode.ALARM_NOT_EXIST)); // 자신한테 온 알림인지 여부체크 - isMyAlarm(reqLoginId, replyAlarm.getReceiver().getLoginId()); + isMyAlarm(reqEmail, replyAlarm.getReceiver().getEmail()); replyAlarm.readAlarm(); replyAlarmRepository.save(replyAlarm); } @Override - public AlarmFindAllResDto findAlarms(String reqLoginId) { - User reqUser = userRepository.findByLoginId(reqLoginId) + public AlarmFindAllResDto findAlarms(String reqEmail) { + User reqUser = userRepository.findByEmail(reqEmail) .orElseThrow(() -> new CustomException(ExceptionCode.USER_NOT_EXIST)); return AlarmFindAllResDto.toDto(findSortedAlarms(reqUser,false), findSortedAlarms(reqUser,true)); } @Override - public Long findNotReadAlarmCnt(String reqLoginId) { - User reqUser = userRepository.findByLoginId(reqLoginId) + public Long findNotReadAlarmCnt(String reqEmail) { + User reqUser = userRepository.findByEmail(reqEmail) .orElseThrow(() -> new CustomException(ExceptionCode.USER_NOT_EXIST)); return followAlarmRepository.countByReceiverAndIsRead(reqUser,false)+ @@ -97,14 +97,14 @@ public Long findNotReadAlarmCnt(String reqLoginId) { @Override @Transactional - public void deleteAlarm(String reqLoginId, Long alarmId, AlarmType alarmType) { + public void deleteAlarm(String reqEmail, Long alarmId, AlarmType alarmType) { // 팔로우 알림일 경우 if(alarmType == AlarmType.FOLLOW){ FollowAlarm followAlarm = followAlarmRepository.findById(alarmId) .orElseThrow(() -> new CustomException(ExceptionCode.ALARM_NOT_EXIST)); - isMyAlarm(reqLoginId, followAlarm.getReceiver().getLoginId()); + isMyAlarm(reqEmail, followAlarm.getReceiver().getEmail()); followAlarmRepository.delete(followAlarm); } // 댓글알림일 경우 @@ -112,7 +112,7 @@ else if(alarmType == AlarmType.REPLY){ ReplyAlarm replyAlarm = replyAlarmRepository.findById(alarmId) .orElseThrow(() -> new CustomException(ExceptionCode.ALARM_NOT_EXIST)); - isMyAlarm(reqLoginId, replyAlarm.getReceiver().getLoginId()); + isMyAlarm(reqEmail, replyAlarm.getReceiver().getEmail()); replyAlarmRepository.delete(replyAlarm); } // 스냅(스냅태그, 좋아요)에 대한 알림일 경우 @@ -120,15 +120,15 @@ else if(alarmType == AlarmType.REPLY){ SnapAlarm snapAlarm = snapAlarmRepository.findById(alarmId) .orElseThrow(() -> new CustomException(ExceptionCode.ALARM_NOT_EXIST)); - isMyAlarm(reqLoginId, snapAlarm.getReceiver().getLoginId()); + isMyAlarm(reqEmail, snapAlarm.getReceiver().getEmail()); snapAlarmRepository.delete(snapAlarm); } } // 자신한테 온 알림인지 여부체크 - private void isMyAlarm(String reqLoginId, String alarmReceiverLoginId){ + private void isMyAlarm(String reqEmail, String alarmReceiverEmail){ - if(!reqLoginId.equals(alarmReceiverLoginId)) + if(!reqEmail.equals(alarmReceiverEmail)) throw new CustomException(ExceptionCode.ACCESS_FAIL_ALARM); } diff --git a/src/main/java/me/snaptime/album/controller/AlbumController.java b/src/main/java/me/snaptime/album/controller/AlbumController.java index 530b8717..cb18df78 100644 --- a/src/main/java/me/snaptime/album/controller/AlbumController.java +++ b/src/main/java/me/snaptime/album/controller/AlbumController.java @@ -27,15 +27,15 @@ public class AlbumController { @Operation(summary = "Album 목록(썸네일 포함) 조회", description = "사용자의 Album 목록(썸네일 포함)을 조회합니다.") @GetMapping(path = "/albumListWithThumbnail") - public ResponseEntity>> findAllAlbumsByLoginId( + public ResponseEntity>> findAllAlbumsByEmail( final @AuthenticationPrincipal UserDetails userDetails ) { - String uId = userDetails.getUsername(); + String userEmail = userDetails.getUsername(); return ResponseEntity.status(HttpStatus.OK) .body( new CommonResponseDto<>( "사용자의 앨범 목록(썸네일 포함)이 정상적으로 불러와졌습니다.", - albumService.findAllAlbumsByLoginId(uId) + albumService.findAllAlbumsByEmail(userEmail) ) ); } @@ -46,8 +46,8 @@ public ResponseEntity> createAlbum( final @RequestBody CreateAlbumReqDto createAlbumReqDto, final @AuthenticationPrincipal UserDetails userDetails ) { - String uId = userDetails.getUsername(); - albumService.createAlbum(createAlbumReqDto, uId); + String userEmail = userDetails.getUsername(); + albumService.createAlbum(createAlbumReqDto, userEmail); return ResponseEntity.status(HttpStatus.CREATED).body( new CommonResponseDto<>( "사용자의 앨범을 정상적으로 생성했습니다.", @@ -61,11 +61,11 @@ public ResponseEntity> createAlbum( public ResponseEntity>> findAlbumList( final @AuthenticationPrincipal UserDetails userDetails ) { - String uId = userDetails.getUsername(); + String userEmail = userDetails.getUsername(); return ResponseEntity.status(HttpStatus.OK).body( new CommonResponseDto<>( "사용자의 앨범 목록(앨범의 이름들)을 정상적으로 가져왔습니다.", - albumService.getAlbumListByLoginId(uId) + albumService.getAlbumListByEmail(userEmail) ) ); } @@ -76,11 +76,11 @@ public ResponseEntity> findAlbum( final @PathVariable("album_id") Long album_id, final @AuthenticationPrincipal UserDetails userDetails ) { - String uId = userDetails.getUsername(); + String userEmail = userDetails.getUsername(); return ResponseEntity.status(HttpStatus.OK).body( new CommonResponseDto<>( album_id + "번 Album의 내용을 전부 가져오는데 성공했습니다.", - albumService.findAlbum(uId, album_id) + albumService.findAlbum(userEmail, album_id) ) ); } @@ -107,8 +107,8 @@ ResponseEntity> deleteAlbum( final @RequestParam Long albumId, final @AuthenticationPrincipal UserDetails userDetails ) { - String uId = userDetails.getUsername(); - albumService.removeAlbum(uId, albumId); + String userEmail = userDetails.getUsername(); + albumService.removeAlbum(userEmail, albumId); return ResponseEntity.status(HttpStatus.OK).body( new CommonResponseDto<>( albumId + "번 album을 정상적으로 삭제했습니다.", @@ -116,10 +116,4 @@ ResponseEntity> deleteAlbum( ) ); } - - - - - - } diff --git a/src/main/java/me/snaptime/album/service/AlbumService.java b/src/main/java/me/snaptime/album/service/AlbumService.java index a249d2ec..3f1b5951 100644 --- a/src/main/java/me/snaptime/album/service/AlbumService.java +++ b/src/main/java/me/snaptime/album/service/AlbumService.java @@ -9,10 +9,10 @@ import java.util.List; public interface AlbumService { - List findAllAlbumsByLoginId(String uid); - FindAlbumResDto findAlbum(String uId, Long album_id); - List getAlbumListByLoginId(String uid); - void createAlbum(CreateAlbumReqDto createAlbumReqDto, String uid); + List findAllAlbumsByEmail(String userEmail); + FindAlbumResDto findAlbum(String userEmail, Long album_id); + List getAlbumListByEmail(String userEmail); + void createAlbum(CreateAlbumReqDto createAlbumReqDto, String userEmail); /* * 사용자 계정에 Non-Classification Album 을 생성하고 생성된 Album 의 Id를 반환한다. * */ diff --git a/src/main/java/me/snaptime/album/service/impl/AlbumServiceImpl.java b/src/main/java/me/snaptime/album/service/impl/AlbumServiceImpl.java index bbc2fb0d..49ddb93b 100644 --- a/src/main/java/me/snaptime/album/service/impl/AlbumServiceImpl.java +++ b/src/main/java/me/snaptime/album/service/impl/AlbumServiceImpl.java @@ -39,8 +39,8 @@ public class AlbumServiceImpl implements AlbumService { @Override @Transactional(readOnly = true) - public List findAllAlbumsByLoginId(String uid) { - User foundUser = userRepository.findByLoginId(uid).orElseThrow(() -> new CustomException(ExceptionCode.USER_NOT_EXIST)); + public List findAllAlbumsByEmail(String userEmail) { + User foundUser = userRepository.findByEmail(userEmail).orElseThrow(() -> new CustomException(ExceptionCode.USER_NOT_EXIST)); List foundAlbums = albumRepository.findAlbumsByUser(foundUser); return foundAlbums.stream().map(album -> { int lastNumber = album.getSnap().size(); @@ -56,9 +56,9 @@ public List findAllAlbumsByLoginId(String uid) { @Override @Transactional(readOnly = true) - public FindAlbumResDto findAlbum(String uId, Long album_id) { + public FindAlbumResDto findAlbum(String userEmail, Long album_id) { Album foundAlbum = albumRepository.findById(album_id).orElseThrow(() -> new CustomException(ExceptionCode.ALBUM_NOT_EXIST)); - User foundUser = userRepository.findByLoginId(uId).orElseThrow(() -> new CustomException(ExceptionCode.USER_NOT_EXIST)); + User foundUser = userRepository.findByEmail(userEmail).orElseThrow(() -> new CustomException(ExceptionCode.USER_NOT_EXIST)); try { isUserHavePermission(foundUser, album_id); } catch (CustomException e) { @@ -119,15 +119,15 @@ public Long findUserNonClassificationId(User user) { @Override @Transactional(readOnly = true) - public List getAlbumListByLoginId(String uid) { - User foundUser = userRepository.findByLoginId(uid).orElseThrow(() -> new CustomException(ExceptionCode.USER_NOT_EXIST)); + public List getAlbumListByEmail(String userEmail) { + User foundUser = userRepository.findByEmail(userEmail).orElseThrow(() -> new CustomException(ExceptionCode.USER_NOT_EXIST)); return albumRepository.findAlbumsByUser(foundUser).stream().map(album -> GetAllAlbumListResDto.builder().id(album.getId()).name(album.getName()).build()).toList(); } @Override @Transactional - public void createAlbum(CreateAlbumReqDto createAlbumReqDto, String uid) { - User foundUser = userRepository.findByLoginId(uid).orElseThrow(() -> new CustomException(ExceptionCode.USER_NOT_EXIST)); + public void createAlbum(CreateAlbumReqDto createAlbumReqDto, String userEmail) { + User foundUser = userRepository.findByEmail(userEmail).orElseThrow(() -> new CustomException(ExceptionCode.USER_NOT_EXIST)); albumRepository.save(Album.builder().name(createAlbumReqDto.name()).user(foundUser).build()); } @@ -146,8 +146,8 @@ public void modifyAlbumName(Long album_id, String album_name) { @Override @Transactional - public void removeAlbum(String uId, Long album_id) { - User foundUser = userRepository.findByLoginId(uId).orElseThrow(() -> new CustomException(ExceptionCode.USER_NOT_EXIST)); + public void removeAlbum(String userEmail, Long album_id) { + User foundUser = userRepository.findByEmail(userEmail).orElseThrow(() -> new CustomException(ExceptionCode.USER_NOT_EXIST)); isUserHavePermission(foundUser, album_id); Album foundAlbum = albumRepository.findById(album_id).orElseThrow(() -> new CustomException(ExceptionCode.ALBUM_NOT_EXIST)); // 사용자가 가지고 있는 non-classification id를 가져온다. diff --git a/src/main/java/me/snaptime/component/email/EmailComponent.java b/src/main/java/me/snaptime/component/email/EmailComponent.java new file mode 100644 index 00000000..3d084d75 --- /dev/null +++ b/src/main/java/me/snaptime/component/email/EmailComponent.java @@ -0,0 +1,8 @@ +package me.snaptime.component.email; + +import jakarta.mail.MessagingException; + +public interface EmailComponent { + + String sendVerificationCode(String toEmail, String verificationCode) throws MessagingException; +} diff --git a/src/main/java/me/snaptime/component/email/impl/EmailComponentImpl.java b/src/main/java/me/snaptime/component/email/impl/EmailComponentImpl.java new file mode 100644 index 00000000..7f6697a8 --- /dev/null +++ b/src/main/java/me/snaptime/component/email/impl/EmailComponentImpl.java @@ -0,0 +1,49 @@ +package me.snaptime.component.email.impl; + +import jakarta.mail.MessagingException; +import jakarta.mail.internet.MimeMessage; +import lombok.RequiredArgsConstructor; +import me.snaptime.component.email.EmailComponent; +import org.springframework.mail.javamail.JavaMailSender; +import org.springframework.mail.javamail.MimeMessageHelper; +import org.springframework.stereotype.Component; +import org.springframework.transaction.annotation.Transactional; + +@Component +@Transactional +@RequiredArgsConstructor +public class EmailComponentImpl implements EmailComponent { + + private final JavaMailSender javaMailSender; + + public String sendVerificationCode(String toEmail, String verificationCode) throws MessagingException { + MimeMessage message = javaMailSender.createMimeMessage(); + MimeMessageHelper helper = new MimeMessageHelper(message, true,"utf-8"); + + String msgg = ""; + msgg += "
"; + msgg += "

SnapTime 입니다.

"; + msgg += "
"; + msgg += "
"; + msgg += "

아래 코드를 복사해 입력해주세요.

"; + msgg += "

감사합니다.

"; + msgg += "
"; + msgg += "
"; + msgg += "
"; + msgg += "

회원 가입 인증 코드입니다.

"; + msgg += "
"; + msgg += "CODE : 123456"; // 여기에 verificationCode 값을 넣으세요 + msgg += "
"; + msgg += "
"; + msgg += "
"; + msgg += "
"; + + helper.setTo(toEmail); + helper.setSubject("회원 가입 인증 코드"); + helper.setText(msgg,true); + + javaMailSender.send(message); + + return verificationCode; + } +} diff --git a/src/main/java/me/snaptime/component/encryption/EncryptionComponent.java b/src/main/java/me/snaptime/component/encryption/EncryptionComponent.java index 415fb180..18911bdb 100644 --- a/src/main/java/me/snaptime/component/encryption/EncryptionComponent.java +++ b/src/main/java/me/snaptime/component/encryption/EncryptionComponent.java @@ -9,10 +9,10 @@ public interface EncryptionComponent { /* * getSecretKey - * User LoginId를 인자로 받아 + * User Email을 인자로 받아 * Encryption Entity의 field인 SecretKey에 접근하여 SecretKey를 가져오는 메소드 * */ - SecretKey getSecretKey(String uId); + SecretKey getSecretKey(String userEmail); /* * getEncryption diff --git a/src/main/java/me/snaptime/component/encryption/EncryptionImpl.java b/src/main/java/me/snaptime/component/encryption/EncryptionImpl.java index a955c70c..247f123d 100644 --- a/src/main/java/me/snaptime/component/encryption/EncryptionImpl.java +++ b/src/main/java/me/snaptime/component/encryption/EncryptionImpl.java @@ -21,8 +21,8 @@ public class EncryptionImpl implements EncryptionComponent { private final EncryptionRepository encryptionRepository; @Override - public SecretKey getSecretKey(String uId) { - User foundUser = userRepository.findByLoginId(uId).orElseThrow(() -> new CustomException(ExceptionCode.USER_NOT_EXIST)); + public SecretKey getSecretKey(String userEmail) { + User foundUser = userRepository.findByEmail(userEmail).orElseThrow(() -> new CustomException(ExceptionCode.USER_NOT_EXIST)); Encryption foundSecretKey = encryptionRepository.findByUser(foundUser); return foundSecretKey.getSecretKey(); } diff --git a/src/main/java/me/snaptime/component/redis/RedisComponent.java b/src/main/java/me/snaptime/component/redis/RedisComponent.java new file mode 100644 index 00000000..6fb8ede2 --- /dev/null +++ b/src/main/java/me/snaptime/component/redis/RedisComponent.java @@ -0,0 +1,10 @@ +package me.snaptime.component.redis; + +import java.time.Duration; + +public interface RedisComponent { + + String getValues(String key); + void setValuesExpire(String key, String data, Duration duration); + boolean checkExistSValue(String value); +} diff --git a/src/main/java/me/snaptime/component/redis/impl/RedisComponentImpl.java b/src/main/java/me/snaptime/component/redis/impl/RedisComponentImpl.java new file mode 100644 index 00000000..61242dd8 --- /dev/null +++ b/src/main/java/me/snaptime/component/redis/impl/RedisComponentImpl.java @@ -0,0 +1,36 @@ +package me.snaptime.component.redis.impl; + +import lombok.RequiredArgsConstructor; +import me.snaptime.component.redis.RedisComponent; +import org.springframework.data.redis.core.RedisTemplate; +import org.springframework.data.redis.core.ValueOperations; +import org.springframework.stereotype.Component; +import org.springframework.transaction.annotation.Transactional; + +import java.time.Duration; + +@Component +@RequiredArgsConstructor +@Transactional +public class RedisComponentImpl implements RedisComponent { + private final RedisTemplate redisTemplate; + + @Override + @Transactional(readOnly = true) + public String getValues(String key){ + ValueOperations valueOperations = redisTemplate.opsForValue(); + if(valueOperations.get(key) == null) return "false"; + return (String) valueOperations.get(key); + } + + @Override + public void setValuesExpire(String key, String data, Duration duration){ + ValueOperations valueOperations = redisTemplate.opsForValue(); + valueOperations.set(key, data, duration); + } + + @Override + public boolean checkExistSValue(String value){ + return !value.equals("false"); + } +} diff --git a/src/main/java/me/snaptime/config/EmailConfig.java b/src/main/java/me/snaptime/config/EmailConfig.java new file mode 100644 index 00000000..0baa20f0 --- /dev/null +++ b/src/main/java/me/snaptime/config/EmailConfig.java @@ -0,0 +1,69 @@ +package me.snaptime.config; + +import org.springframework.beans.factory.annotation.Value; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.mail.javamail.JavaMailSender; +import org.springframework.mail.javamail.JavaMailSenderImpl; + +import java.util.Properties; + +@Configuration +public class EmailConfig { + + @Value("${spring.mail.host}") + private String host; + + @Value("${spring.mail.port}") + private int port; + + @Value("${spring.mail.username}") + private String username; + + @Value("${spring.mail.password}") + private String password; + + @Value("${spring.mail.properties.mail.smtp.auth}") + private boolean auth; + + @Value("${spring.mail.properties.mail.smtp.starttls.enable}") + private boolean starttlsEnable; + + @Value("${spring.mail.properties.mail.smtp.starttls.required}") + private boolean starttlsRequired; + + @Value("${spring.mail.properties.mail.smtp.connectiontimeout}") + private int connectionTimeout; + + @Value("${spring.mail.properties.mail.smtp.timeout}") + private int timeout; + + @Value("${spring.mail.properties.mail.smtp.writetimeout}") + private int writeTimeout; + + @Bean + public JavaMailSender javaMailSender() { + JavaMailSenderImpl mailSender = new JavaMailSenderImpl(); + mailSender.setHost(host); + mailSender.setPort(port); + mailSender.setUsername(username); + mailSender.setPassword(password); + mailSender.setDefaultEncoding("UTF-8"); + mailSender.setJavaMailProperties(getMailProperties()); + + return mailSender; + } + + private Properties getMailProperties() { + Properties properties = new Properties(); + properties.put("mail.smtp.auth", auth); + properties.put("mail.smtp.starttls.enable", starttlsEnable); + properties.put("mail.smtp.starttls.required", starttlsRequired); + properties.put("mail.smtp.connectiontimeout", connectionTimeout); + properties.put("mail.smtp.timeout", timeout); + properties.put("mail.smtp.writetimeout", writeTimeout); + + return properties; + } + +} diff --git a/src/main/java/me/snaptime/config/SecurityConfig.java b/src/main/java/me/snaptime/config/SecurityConfig.java index e64be72b..3f742bb2 100644 --- a/src/main/java/me/snaptime/config/SecurityConfig.java +++ b/src/main/java/me/snaptime/config/SecurityConfig.java @@ -38,6 +38,7 @@ protected SecurityFilterChain filterChain(HttpSecurity httpSecurity) throws Exce requests .requestMatchers("/swagger-resources/**", "/swagger-ui/index.html", "/webjars/**", "/swagger/**", "/users/exception", "/v3/api-docs/**", "/swagger-ui/**").permitAll() .requestMatchers("/users/sign-in", "/users/sign-up","/users/test/sign-in").permitAll() + .requestMatchers("/emails/send", "/emails/verify").permitAll() .requestMatchers(HttpMethod.GET,"/users/profile", "/profile-photos/**","/snap/**","/friends/**").permitAll() .requestMatchers("**exception**").permitAll() .anyRequest().hasRole("USER") diff --git a/src/main/java/me/snaptime/email/contoller/EmailController.java b/src/main/java/me/snaptime/email/contoller/EmailController.java new file mode 100644 index 00000000..ef46aecd --- /dev/null +++ b/src/main/java/me/snaptime/email/contoller/EmailController.java @@ -0,0 +1,45 @@ +package me.snaptime.email.contoller; + +import io.swagger.v3.oas.annotations.Operation; +import io.swagger.v3.oas.annotations.tags.Tag; +import jakarta.mail.MessagingException; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import me.snaptime.common.CommonResponseDto; +import me.snaptime.email.service.EmailService; +import me.snaptime.profile.dto.res.UserProfileResDto; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.RestController; + +@Tag(name ="[Email] Email API", description = "회원가입을 위한 이메일 전송, 이메일 인증") +@RestController +@Slf4j +@RequiredArgsConstructor +@RequestMapping("/emails") +public class EmailController { + + private final EmailService emailService; + + @PostMapping("/send") + @Operation(summary = "이메일 인증코드 발송", description = "email로 인증코드를 전송합니다.") + public ResponseEntity> mailSend(@RequestParam String email) throws MessagingException { + log.info("EmailController.mailSend()"); + emailService.sendCodeToEmail(email); + return ResponseEntity.status(HttpStatus.OK).body( + new CommonResponseDto<>("인증코드가 성공적으로 발송되었습니다.", email)); + } + + @PostMapping("/verify") + @Operation(summary = "인증코드를 확인합니다.", description = "이메일과 인증코드를 통해서, 해당 이메일로 보낸 인증코드의 유효를 검증합니다.") + public ResponseEntity> verify(@RequestParam String email, @RequestParam String code) { + log.info("EmailController.verify()"); + boolean isVerified = emailService.verifyCode(email, code); + + return ResponseEntity.status(HttpStatus.OK).body( + new CommonResponseDto<>(isVerified ? "인증에 성공하였습니다" : "인증에 실패하였습니다",isVerified)); + } +} diff --git a/src/main/java/me/snaptime/email/service/EmailService.java b/src/main/java/me/snaptime/email/service/EmailService.java new file mode 100644 index 00000000..268ec39e --- /dev/null +++ b/src/main/java/me/snaptime/email/service/EmailService.java @@ -0,0 +1,9 @@ +package me.snaptime.email.service; + +import jakarta.mail.MessagingException; + +public interface EmailService { + void sendCodeToEmail(String toEmail) throws MessagingException; + boolean verifyCode(String email, String verificationCode); + +} diff --git a/src/main/java/me/snaptime/email/service/impl/EmailServiceImpl.java b/src/main/java/me/snaptime/email/service/impl/EmailServiceImpl.java new file mode 100644 index 00000000..0b164dfb --- /dev/null +++ b/src/main/java/me/snaptime/email/service/impl/EmailServiceImpl.java @@ -0,0 +1,61 @@ +package me.snaptime.email.service.impl; + +import jakarta.mail.MessagingException; +import lombok.RequiredArgsConstructor; +import me.snaptime.component.email.EmailComponent; +import me.snaptime.component.redis.RedisComponent; +import me.snaptime.email.service.EmailService; +import me.snaptime.exception.CustomException; +import me.snaptime.exception.ExceptionCode; +import me.snaptime.user.repository.UserRepository; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +import java.time.Duration; +import java.util.Random; + +@Service +@RequiredArgsConstructor +@Transactional +public class EmailServiceImpl implements EmailService { + + private final UserRepository userRepository; + private final RedisComponent redisComponent; + private final EmailComponent emailComponent; + + @Value("${spring.mail.auth-code-expiration-millis}") + private long authCodeExpirationMillis; + @Override + public void sendCodeToEmail(String toEmail) throws MessagingException { + // 이메일 중복 검사 + if(userRepository.existsByEmail(toEmail)) throw new CustomException(ExceptionCode.EMAIL_DUPLICATE); + + // 인증코드 생성, 저장 및 이메일 전송 + String verificationCode = createCode(); + // 이메일 인증 요청 시 인증 번호 Redis에 저장 + redisComponent.setValuesExpire(toEmail, verificationCode, Duration.ofMillis(authCodeExpirationMillis)); + emailComponent.sendVerificationCode(toEmail,verificationCode); + } + + @Override + public boolean verifyCode(String email, String verificationCode){ + String redisVerificationCode = redisComponent.getValues(email); + return redisComponent.checkExistSValue(redisVerificationCode) && redisVerificationCode.equals(verificationCode); + } + + private String createCode(){ + int leftLimit = 48; // 숫자 '0' + int rightLimit = 122; // 알파벳 'z' + int targetStringLength = 6; + Random random = new Random(); + + return random.ints(leftLimit, rightLimit + 1) // leftLimit ~ rightLimit 사이의 난수 생성 + .filter(i -> (i >= 48 && i <= 57) || // 숫자 '0' ~ '9' + (i >= 65 && i <= 90) || // 대문자 'A' ~ 'Z' + (i >= 97 && i <= 122)) // 소문자 'a' ~ 'z' + .limit(targetStringLength) // 길이 제한 + .collect(StringBuilder::new, StringBuilder::appendCodePoint, StringBuilder::append) // 객체 생성, 코드 포인트 StringBuilder에 추가, StringBuilder 객체 합치기 + .toString(); + } +} diff --git a/src/main/java/me/snaptime/exception/ExceptionCode.java b/src/main/java/me/snaptime/exception/ExceptionCode.java index d2d63d93..0a80ab3d 100644 --- a/src/main/java/me/snaptime/exception/ExceptionCode.java +++ b/src/main/java/me/snaptime/exception/ExceptionCode.java @@ -40,7 +40,7 @@ public enum ExceptionCode { USER_NOT_EXIST(HttpStatus.BAD_REQUEST, "사용자가 존재하지 않습니다."), PASSWORD_DUPLICATE(HttpStatus.BAD_REQUEST,"같은 비밀번호로 수정 할 수 없습니다."), LOGIN_ID_ALREADY_EXIST(HttpStatus.BAD_REQUEST, "이미 존재하는 loginId 입니다."), - + EMAIL_DUPLICATE(HttpStatus.BAD_REQUEST,"이미 존재하는 이메일입니다."), // Snap Exception SNAP_NOT_EXIST(HttpStatus.BAD_REQUEST, "스냅이 존재하지 않습니다."), SNAP_IS_PRIVATE(HttpStatus.BAD_REQUEST, "사용자가 이 스냅을 비공개로 설정했습니다."), diff --git a/src/main/java/me/snaptime/friend/controller/FriendController.java b/src/main/java/me/snaptime/friend/controller/FriendController.java index 0f9e7cc9..258acb06 100644 --- a/src/main/java/me/snaptime/friend/controller/FriendController.java +++ b/src/main/java/me/snaptime/friend/controller/FriendController.java @@ -30,24 +30,24 @@ public class FriendController { @PostMapping @Operation(summary = "팔로우 요청", description = "팔로우할 유저의 loginId를 입력해주세요.
" + "sender의 팔로잉 +1, receiver의 팔로워 +1") - @Parameter(name = "receiverLoginId", description = "팔로우할 유저의 loginId를 입력해주세요", required = true, example = "seyong") + @Parameter(name = "receiverEmail", description = "팔로우할 유저의 Email을 입력해주세요", required = true, example = "seyong") public ResponseEntity> sendFollowReq( @AuthenticationPrincipal UserDetails userDetails, - @RequestParam(name = "receiverLoginId") @NotBlank(message = "팔로우요청을 보낼 유저의 이름을 입력해주세요.")String receiverLoginId) { + @RequestParam(name = "receiverEmail") @NotBlank(message = "팔로우요청을 보낼 유저의 이름을 입력해주세요.")String receiverEmail) { - friendService.sendFollow(userDetails.getUsername(), receiverLoginId); + friendService.sendFollow(userDetails.getUsername(), receiverEmail); return ResponseEntity.status(HttpStatus.CREATED).body(new CommonResponseDto("팔로우가 완료되었습니다.", null)); } @DeleteMapping - @Operation(summary = "팔로우하는 친구삭제", description = "언팔로우 할 친구의 loginId를 보내주세요.
" + + @Operation(summary = "팔로우하는 친구삭제", description = "언팔로우 할 친구의 email을 보내주세요.
" + "deletor(언팔하는 유저)의 팔로잉 -1, deletedUser(언팔당하는 유저)의 팔로워 -1") - @Parameter(name = "deletedUserLoginId", description = "팔로우 삭제할 친구의 loginId를 입력해주세요.", required = true, example = "seyong") + @Parameter(name = "deletedUserEmail", description = "팔로우 삭제할 친구의 email을 입력해주세요.", required = true, example = "seyong") public ResponseEntity> unFollow( @AuthenticationPrincipal UserDetails userDetails, - @RequestParam @NotBlank(message = "언팔로우할 유저의 loginId를 입력해주세요.")final String deletedUserLoginId) { + @RequestParam @NotBlank(message = "언팔로우할 유저의 email을 입력해주세요.")final String deletedUserEmail) { - friendService.unFollow(userDetails.getUsername(), deletedUserLoginId); + friendService.unFollow(userDetails.getUsername(), deletedUserEmail); return ResponseEntity.status(HttpStatus.OK).body(new CommonResponseDto("팔로우삭제가 완료되었습니다.", null)); } @@ -57,20 +57,20 @@ public ResponseEntity> unFollow( "
검색키워드는 필수가 아니며 없으면 입력하지 않아도 됩니다." + "
스냅에 친구를 태그하기 위해 태그할 유저 조회를 할 경우 friendSearchType을 팔로잉으로 보내시면 됩니다.") @Parameters({ - @Parameter(name = "targetLoginId" , description = "친구목록을 조회할 유저의 loginId", required = true,example = "tempLoginId"), + @Parameter(name = "targetEmail" , description = "친구목록을 조회할 유저의 email", required = true,example = "tempEmail"), @Parameter(name = "searchKeyword", description = "친구 검색키워드", required = false, example = "홍길동"), @Parameter(name = "friendSearchType", description = "검색 타입(팔로워 조회 시 FOLLOWER/팔로잉 조회 시 FOLLOWING)으로 입력해주세요.", required = true, example = "FOLLOWER"), @Parameter(name = "pageNum", description = "친구조회 페이지번호", required = true, example = "1") }) public ResponseEntity> findFriendPage( @AuthenticationPrincipal UserDetails userDetails, - @RequestParam(name = "targetLoginId") @NotBlank(message = "친구목록을 조회할 유저의 loginId를 입력해주세요.") String loginId, + @RequestParam(name = "targetEmail") @NotBlank(message = "친구목록을 조회할 유저의 email을 입력해주세요.") String email, @RequestParam(name = "friendSearchType") @NotNull(message = "팔로우,팔로잉중 하나를 입력해주세요.") FriendSearchType friendSearchType, @RequestParam(name = "searchKeyword",required = false) String searchKeyword, @PathVariable(name = "pageNum") final Long pageNum){ return ResponseEntity.status(HttpStatus.OK).body(new CommonResponseDto("친구조회가 완료되었습니다.", - friendService.findFriendPage(userDetails.getUsername(), loginId,pageNum,friendSearchType,searchKeyword))); + friendService.findFriendPage(userDetails.getUsername(), email,pageNum,friendSearchType,searchKeyword))); } } diff --git a/src/main/java/me/snaptime/friend/dto/res/FriendInfoResDto.java b/src/main/java/me/snaptime/friend/dto/res/FriendInfoResDto.java index 1f21ab49..0cd0e440 100644 --- a/src/main/java/me/snaptime/friend/dto/res/FriendInfoResDto.java +++ b/src/main/java/me/snaptime/friend/dto/res/FriendInfoResDto.java @@ -9,7 +9,7 @@ @Builder public record FriendInfoResDto( - String foundLoginId, + String foundEmail, String profilePhotoURL, String foundUserName, Long friendId, @@ -17,7 +17,7 @@ public record FriendInfoResDto( ) { public static FriendInfoResDto toDto(Tuple tuple, String profilePhotoURL, boolean isMyFriend){ return FriendInfoResDto.builder() - .foundLoginId(tuple.get(user.loginId)) + .foundEmail(tuple.get(user.email)) .profilePhotoURL(profilePhotoURL) .foundUserName(tuple.get(user.name)) .friendId(tuple.get(friend.friendId)) diff --git a/src/main/java/me/snaptime/friend/repository/impl/FriendPagingRepositoryImpl.java b/src/main/java/me/snaptime/friend/repository/impl/FriendPagingRepositoryImpl.java index 867ab34e..2a115af2 100644 --- a/src/main/java/me/snaptime/friend/repository/impl/FriendPagingRepositoryImpl.java +++ b/src/main/java/me/snaptime/friend/repository/impl/FriendPagingRepositoryImpl.java @@ -33,7 +33,7 @@ public List findFriendPage(User targetUser, FriendSearchType searchType, Pageable pageable= PageRequest.of((int) (pageNum-1),20); List tuples = jpaQueryFactory.select( - user.loginId, user.profilePhoto.profilePhotoId, user.name, friend.friendId + user.email, user.profilePhoto.profilePhotoId, user.name, friend.friendId ) .from(friend) .join(user).on(getJoinBuilder(searchType)) @@ -65,7 +65,7 @@ private BooleanBuilder getWhereBuilder(User targetUser, FriendSearchType friendS } if(searchKeyword !=null){ - builder.and(user.name.startsWith(searchKeyword).or(user.loginId.startsWith(searchKeyword))); + builder.and(user.name.startsWith(searchKeyword).or(user.email.startsWith(searchKeyword))); } return builder; diff --git a/src/main/java/me/snaptime/friend/service/FriendService.java b/src/main/java/me/snaptime/friend/service/FriendService.java index df4dd234..e6d0d309 100644 --- a/src/main/java/me/snaptime/friend/service/FriendService.java +++ b/src/main/java/me/snaptime/friend/service/FriendService.java @@ -8,7 +8,7 @@ public interface FriendService { // 친구요청 전송(sender(요청자)의 팔로잉 +1, receiver의 팔로워 +1) - void sendFollow(String senderLoginId, String receiverLoginId); + void sendFollow(String senderEmail, String receiverEmail); // 친구요청 수락(sender(수락자)의 팔로잉 +1, receiver의 팔로워 +1) // 친구요청 거절(sender(수락자)의 팔로워 -1, receiver의 팔로잉 -1) @@ -16,15 +16,15 @@ public interface FriendService { String acceptFollow(User sender, User receiver, boolean isAccept); // 친구 삭제(deletingUser(삭제자)의 팔로잉 -1, deletedUser의 팔로워 -1) - void unFollow(String deletingUserLoginId, String deletedUserLoginId); + void unFollow(String deletingUserEmail, String deletedUserEmail); // myLoginId유저가 targetLoginId유저의 팔로워 or 팔로잉 친구리스트 조회 - FriendPagingResDto findFriendPage(String loginId, String targetLoginId, Long pageNum, + FriendPagingResDto findFriendPage(String email, String targetEmail, Long pageNum, FriendSearchType searchType, String searchKeyword); // 유저 프로필 조회 시 팔로잉,팔로워 수를 반환하는 메소드 - FriendCntResDto findFriendCnt(String loginId); + FriendCntResDto findFriendCnt(String email); /* reqUser가 targetUser를 팔로우했는 지 여부 반환 diff --git a/src/main/java/me/snaptime/friend/service/impl/FriendServiceImpl.java b/src/main/java/me/snaptime/friend/service/impl/FriendServiceImpl.java index 65a269cb..4cde4975 100644 --- a/src/main/java/me/snaptime/friend/service/impl/FriendServiceImpl.java +++ b/src/main/java/me/snaptime/friend/service/impl/FriendServiceImpl.java @@ -38,10 +38,10 @@ public class FriendServiceImpl implements FriendService { @Override @Transactional - public void sendFollow(String senderLoginId, String receiverLoginId){ + public void sendFollow(String senderEmail, String receiverEmail){ - User sender = findUserByLoginId(senderLoginId); - User receiver = findUserByLoginId(receiverLoginId); + User sender = findUserByEmail(senderEmail); + User receiver = findUserByEmail(receiverEmail); Optional friendOptional = friendRepository.findBySenderAndReceiver(sender,receiver); @@ -87,10 +87,10 @@ public String acceptFollow(User sender, User receiver, boolean isAccept){ @Override @Transactional - public void unFollow(String deletorLoginId, String deletedUserLoginId){ + public void unFollow(String deletorEmail, String deletedUserEmail){ - User deletor = findUserByLoginId(deletorLoginId); - User deletedUser = findUserByLoginId(deletedUserLoginId); + User deletor = findUserByEmail(deletorEmail); + User deletedUser = findUserByEmail(deletedUserEmail); Friend friend = friendRepository.findBySenderAndReceiver(deletor,deletedUser) .orElseThrow(() -> new CustomException(ExceptionCode.FRIEND_NOT_EXIST)); @@ -98,11 +98,11 @@ public void unFollow(String deletorLoginId, String deletedUserLoginId){ } @Override - public FriendPagingResDto findFriendPage(String reqLoginId, String targetLoginId, Long pageNum, + public FriendPagingResDto findFriendPage(String reqEmail, String targetEmail, Long pageNum, FriendSearchType searchType, String searchKeyword){ - User reqUser = findUserByLoginId(reqLoginId); - User targetUser = findUserByLoginId(targetLoginId); + User reqUser = findUserByEmail(reqEmail); + User targetUser = findUserByEmail(targetEmail); List tuples = friendRepository.findFriendPage(targetUser,searchType,pageNum,searchKeyword); // 다음 페이지 유무 체크 @@ -110,7 +110,7 @@ public FriendPagingResDto findFriendPage(String reqLoginId, String targetLoginId List friendInfoResDtos = tuples.stream().map(tuple -> { - boolean isMyFriend = checkIsFollow(reqUser ,findUserByLoginId(tuple.get(user.loginId))); + boolean isMyFriend = checkIsFollow(reqUser ,findUserByEmail(tuple.get(user.email))); String profilePhotoURL = urlComponent.makeProfileURL(tuple.get(user.profilePhoto.profilePhotoId)); return FriendInfoResDto.toDto(tuple,profilePhotoURL,isMyFriend); }).collect(Collectors.toList()); @@ -119,9 +119,9 @@ public FriendPagingResDto findFriendPage(String reqLoginId, String targetLoginId } @Override - public FriendCntResDto findFriendCnt(String loginId){ + public FriendCntResDto findFriendCnt(String email){ - User targetUser = findUserByLoginId(loginId); + User targetUser = findUserByEmail(email); // target의 팔로잉,팔로워 수 조회 Long followingCnt = friendRepository.countBySender(targetUser); @@ -135,8 +135,8 @@ public boolean checkIsFollow(User reqUser, User targetUser){ return friendRepository.existsBySenderAndReceiver(reqUser, targetUser); } - private User findUserByLoginId(String loginId){ - return userRepository.findByLoginId(loginId) + private User findUserByEmail(String email){ + return userRepository.findByEmail(email) .orElseThrow(() -> new CustomException(ExceptionCode.USER_NOT_EXIST)); } diff --git a/src/main/java/me/snaptime/jwt/JwtProvider.java b/src/main/java/me/snaptime/jwt/JwtProvider.java index 01c0c6e1..c30f60ce 100644 --- a/src/main/java/me/snaptime/jwt/JwtProvider.java +++ b/src/main/java/me/snaptime/jwt/JwtProvider.java @@ -42,8 +42,8 @@ protected void init(){ secretKey = Base64.getEncoder().encodeToString(secretKey.getBytes(StandardCharsets.UTF_8)); } - public String createAccessToken(Long userId, String loginId, List roles){ - Claims claims = Jwts.claims().setSubject(loginId); + public String createAccessToken(Long userId, String email, List roles){ + Claims claims = Jwts.claims().setSubject(email); claims.put("userId",userId); claims.put("type","access"); claims.put("roles",roles); @@ -58,8 +58,8 @@ public String createAccessToken(Long userId, String loginId, List roles) return token; } - public String createRefreshToken(Long id, String loginId, List roles){ - Claims claims = Jwts.claims().setSubject(loginId); + public String createRefreshToken(Long id, String email, List roles){ + Claims claims = Jwts.claims().setSubject(email); claims.put("userId", id); claims.put("type", "refresh"); claims.put("roles", roles); @@ -73,8 +73,8 @@ public String createRefreshToken(Long id, String loginId, List roles){ return token; } - public String testCreateAccessToken(Long userId, String loginId, List roles){ - Claims claims = Jwts.claims().setSubject(loginId); + public String testCreateAccessToken(Long userId, String email, List roles){ + Claims claims = Jwts.claims().setSubject(email); claims.put("userId",userId); claims.put("type","testAccess"); claims.put("roles",roles); @@ -89,8 +89,8 @@ public String testCreateAccessToken(Long userId, String loginId, List ro return token; } - public String testCreateRefreshToken(Long id, String loginId, List roles){ - Claims claims = Jwts.claims().setSubject(loginId); + public String testCreateRefreshToken(Long id, String email, List roles){ + Claims claims = Jwts.claims().setSubject(email); claims.put("userId", id); claims.put("type", "testRefresh"); claims.put("roles", roles); @@ -123,14 +123,14 @@ public Authentication getAuthentication(String token){ //Jwts.parser()를 통해 secretKey를 설정하고 클레임을 추출해서 토큰을 생성할 때 넣었던 sub값을 추출합니다. public String getUsername(String token) { - String loginId = Jwts.parserBuilder() + String email = Jwts.parserBuilder() .setSigningKey(secretKey) .build() .parseClaimsJws(token) .getBody() .getSubject(); - log.info("[getUsername] 토큰 기반 회원 구별 정보 추출 완료, loginId : {}",loginId); - return loginId; + log.info("[getUsername] 토큰 기반 회원 구별 정보 추출 완료, loginId : {}", email); + return email; } public String getAuthorizationToken(HttpServletRequest request){ diff --git a/src/main/java/me/snaptime/jwt/UserDetailsServiceImpl.java b/src/main/java/me/snaptime/jwt/UserDetailsServiceImpl.java index 20ff5a7b..ef2d5999 100644 --- a/src/main/java/me/snaptime/jwt/UserDetailsServiceImpl.java +++ b/src/main/java/me/snaptime/jwt/UserDetailsServiceImpl.java @@ -18,8 +18,8 @@ public class UserDetailsServiceImpl implements UserDetailsService { private final UserRepository userRepository; @Override - public UserDetails loadUserByUsername(String loginId) throws UsernameNotFoundException { - log.info("[loadUserByUsername] loadUserByUsername 수행. username: {}", loginId); - return (UserDetails) userRepository.findByLoginId(loginId).orElseThrow(()-> new CustomException(ExceptionCode.USER_NOT_EXIST)); + public UserDetails loadUserByUsername(String email) throws UsernameNotFoundException { + log.info("[loadUserByUsername] loadUserByUsername 수행. username: {}", email); + return (UserDetails) userRepository.findByEmail(email).orElseThrow(()-> new CustomException(ExceptionCode.USER_NOT_EXIST)); } } diff --git a/src/main/java/me/snaptime/profile/controller/ProfileController.java b/src/main/java/me/snaptime/profile/controller/ProfileController.java index 1b7ec9ff..ecd8241c 100644 --- a/src/main/java/me/snaptime/profile/controller/ProfileController.java +++ b/src/main/java/me/snaptime/profile/controller/ProfileController.java @@ -38,13 +38,13 @@ public class ProfileController { @Operation(summary = "유저 앨범, 스냅 조회", description = "유저의 앨범들과, 각 앨범의 스냅들을 조회합니다." + "
자신의 프로필 조회 -> 앨범 당 private, public 관계 없이 최근 snap 2개 리턴" + "
다른 사람의 프로필 조회 -> snap이 전부 private이거나 없는 경우 앨범 리턴 x 그리고 private 인 snap 리턴 x") - @Parameter(name = "targetLoginId", description = "앨범과 사진들을 가져오기 위한 loginId", required = true) + @Parameter(name = "targetEmail", description = "앨범과 사진들을 가져오기 위한 email", required = true) @GetMapping("/album-snap") public ResponseEntity>> getAlbumSnap(@AuthenticationPrincipal UserDetails userDetails, - @RequestParam("targetLoginId") - @NotBlank(message = "로그인 아이디 입력은 필수입니다.") String targetLoginId){ - String reqLoginId = userDetails.getUsername(); - List albumSnapResDtos = profileService.getAlbumSnap(reqLoginId, targetLoginId); + @RequestParam("targetEmail") + @NotBlank(message = "조회할 유저의 이메일 입력은 필수입니다.") String targetEmail){ + String reqEmail = userDetails.getUsername(); + List albumSnapResDtos = profileService.getAlbumSnap(reqEmail, targetEmail); return ResponseEntity.status(HttpStatus.OK).body( new CommonResponseDto<>( "유저 앨범과 스냅 조회를 성공적으로 완료하였습니다.", @@ -55,13 +55,13 @@ public ResponseEntity>> getAlbumSnap(@Au @Operation(summary = "유저 이름, 프로필 사진 조회", description = "유저의 이름과, 프로필 사진을 조회합니다." + "
유저 번호, 유저 이름, 프로필 사진 url 리턴(토큰 없이 url 접근 가능)" + "
토큰이 없어도 해당 Api 엔드포인트를 요청할 수 있습니다.") - @Parameter(name = "targetLoginId", description = "이름과 프로필 사진을 가져오기 위한 loginId", required = true) + @Parameter(name = "targetEmail", description = "이름과 프로필 사진을 가져오기 위한 email", required = true) @GetMapping("/profile") public ResponseEntity> getUserProfile(@AuthenticationPrincipal UserDetails userDetails, - @RequestParam("targetLoginId") - @NotBlank(message = "로그인 아이디 입력은 필수입니다.") String targetLoginId){ - String reqLoginId = userDetails.getUsername(); - UserProfileResDto userProfileResDto = profileService.getUserProfile(reqLoginId, targetLoginId); + @RequestParam("targetEmail") + @NotBlank(message = "조회할 유저의 이메일 입력은 필수입니다.") String targetEmail){ + String reqEmail = userDetails.getUsername(); + UserProfileResDto userProfileResDto = profileService.getUserProfile(reqEmail, targetEmail); return ResponseEntity.status(HttpStatus.OK).body( new CommonResponseDto<>( "유저 이름과, 프로필 사진 조회를 성공적으로 완료하였습니다.", @@ -70,11 +70,11 @@ public ResponseEntity> getUserProfile(@Auth } @Operation(summary = "유저의 Snap 수, Follower 수, Following 수 조회", description = "유저의 loginId로 유저의 snap 수, 팔로워 수, 팔로잉 수를 조회합니다.") - @Parameter(name = "loginId", description = "팔로워와 팔로잉 수를 가져오기 위한 loginId", required = true) + @Parameter(name = "email", description = "팔로워와 팔로잉 수를 가져오기 위한 email", required = true) @GetMapping("/count") - public ResponseEntity> getProfileCnt(@RequestParam("loginId") - @NotBlank(message = "로그인 아이디 입력은 필수입니다.") String loginId){ - ProfileCntResDto profileCntResDto = profileService.getUserProfileCnt(loginId); + public ResponseEntity> getProfileCnt(@RequestParam("email") + @NotBlank(message = "조회할 유저의 이메일 입력은 필수입니다.") String email){ + ProfileCntResDto profileCntResDto = profileService.getUserProfileCnt(email); return ResponseEntity.status(HttpStatus.OK).body( new CommonResponseDto<>( "유저 팔로워, 팔로잉 수 조회를 성공적으로 완료하였습니다.", @@ -82,13 +82,13 @@ public ResponseEntity> getProfileCnt(@Reques )); } - @Operation(summary = "유저의 태그된 snap 들 조회", description = "유저의 loginId로 유저가 태그된 snap 들을 조회합니다" + + @Operation(summary = "유저의 태그된 snap 들 조회", description = "유저의 email 로 유저가 태그된 snap 들을 조회합니다" + "
snap id 기준 내림차순으로 조회합니다.(최근 snap 이 제일 먼저 조회)") - @Parameter(name = "loginId", description = "팔로워와 팔로잉 수를 가져오기 위한 loginId", required = true) + @Parameter(name = "email", description = "팔로워와 팔로잉 수를 가져오기 위한 email", required = true) @GetMapping("/tag-snap") - public ResponseEntity>> getTagSnap(@RequestParam("loginId") - @NotBlank(message = "로그인 아이디 입력은 필수입니다.") String loginId){ - List profileTagSnapResDto = profileService.getTagSnap(loginId); + public ResponseEntity>> getTagSnap(@RequestParam("email") + @NotBlank(message = "조회할 유저의 이메일 입력은 필수입니다.") String email){ + List profileTagSnapResDto = profileService.getTagSnap(email); return ResponseEntity.status(HttpStatus.OK).body( new CommonResponseDto<>( "유저가 태그된 Snap 들을 성공적으로 조회하였습니다.", diff --git a/src/main/java/me/snaptime/profile/dto/res/ProfileTagSnapResDto.java b/src/main/java/me/snaptime/profile/dto/res/ProfileTagSnapResDto.java index 718c7417..bf4659d4 100644 --- a/src/main/java/me/snaptime/profile/dto/res/ProfileTagSnapResDto.java +++ b/src/main/java/me/snaptime/profile/dto/res/ProfileTagSnapResDto.java @@ -6,7 +6,7 @@ public record ProfileTagSnapResDto( Long taggedSnapId, - String snapOwnLoginId, + String snapOwnEmail, String taggedSnapUrl ){} diff --git a/src/main/java/me/snaptime/profile/repository/impl/ProfileRepositoryImpl.java b/src/main/java/me/snaptime/profile/repository/impl/ProfileRepositoryImpl.java index 0247addf..27db956b 100644 --- a/src/main/java/me/snaptime/profile/repository/impl/ProfileRepositoryImpl.java +++ b/src/main/java/me/snaptime/profile/repository/impl/ProfileRepositoryImpl.java @@ -91,10 +91,10 @@ public List findAlbumSnap(User targetUser, Boolean checkPermiss @Override public List findTagSnap(User targetUser) { List tagSnaps = jpaQueryFactory - .select(snap.id,snap.user.loginId, snap.fileName, snap.isPrivate, snap.createdDate).distinct() + .select(snap.id,snap.user.email, snap.fileName, snap.isPrivate, snap.createdDate).distinct() .from(snap) .join(snapTag).on(snapTag.snap.id.eq(snap.id)) - .where(snapTag.tagUser.loginId.eq(targetUser.getLoginId())) + .where(snapTag.tagUser.email.eq(targetUser.getEmail())) .orderBy(snap.createdDate.desc()) .fetch(); @@ -102,7 +102,7 @@ public List findTagSnap(User targetUser) { .map(tuple -> { return ProfileTagSnapResDto.builder() .taggedSnapId(tuple.get(snap.id)) - .snapOwnLoginId(tuple.get(snap.user.loginId)) + .snapOwnEmail(tuple.get(snap.user.email)) .taggedSnapUrl(urlComponent.makePhotoURL(tuple.get(snap.fileName), tuple.get(snap.isPrivate))) .build(); }) diff --git a/src/main/java/me/snaptime/profile/service/ProfileService.java b/src/main/java/me/snaptime/profile/service/ProfileService.java index 082c8b21..e9bb5905 100644 --- a/src/main/java/me/snaptime/profile/service/ProfileService.java +++ b/src/main/java/me/snaptime/profile/service/ProfileService.java @@ -9,12 +9,12 @@ public interface ProfileService { /* 호출자의 loginId, 피호출자의 loginId를 통해 피호출자의 album과 snap을 조회 */ - List getAlbumSnap(String reqLoginId, String targetLoginId); + List getAlbumSnap(String reqEmail, String targetEmail); /* loginId에 해당하는 User의 profile 사진을 조회 */ - UserProfileResDto getUserProfile(String reqLoginId, String targetLoginId); + UserProfileResDto getUserProfile(String reqEmail, String targetEmail); /* loginId에 해당하는 User의 스냅, 팔로우, 팔로워 수 리턴 */ - ProfileCntResDto getUserProfileCnt(String loginId); + ProfileCntResDto getUserProfileCnt(String email); /* loginId에 해당하는 User가 Tag된 snap들을 조회합니다 */ - List getTagSnap(String loginId); + List getTagSnap(String email); } diff --git a/src/main/java/me/snaptime/profile/service/impl/ProfileServiceImpl.java b/src/main/java/me/snaptime/profile/service/impl/ProfileServiceImpl.java index f4dfd1b1..763dfe0c 100644 --- a/src/main/java/me/snaptime/profile/service/impl/ProfileServiceImpl.java +++ b/src/main/java/me/snaptime/profile/service/impl/ProfileServiceImpl.java @@ -34,21 +34,21 @@ public class ProfileServiceImpl implements ProfileService { @Override @Transactional(readOnly = true) - public List getAlbumSnap(String reqLoginId, String targetLoginId) { - User targetUser = userRepository.findByLoginId(targetLoginId).orElseThrow(() -> new CustomException(ExceptionCode.USER_NOT_EXIST)); + public List getAlbumSnap(String reqEmail, String targetEmail) { + User targetUser = userRepository.findByEmail(targetEmail).orElseThrow(() -> new CustomException(ExceptionCode.USER_NOT_EXIST)); - return profileRepository.findAlbumSnap(targetUser, reqLoginId.equals(targetLoginId)); + return profileRepository.findAlbumSnap(targetUser, reqEmail.equals(targetEmail)); } @Override @Transactional(readOnly = true) - public UserProfileResDto getUserProfile(String reqLoginId, String targetLoginId) { + public UserProfileResDto getUserProfile(String reqEmail, String targetEmail) { Boolean isFollow = null; - User targetUser = userRepository.findByLoginId(targetLoginId).orElseThrow(() -> new CustomException(ExceptionCode.USER_NOT_EXIST)); + User targetUser = userRepository.findByEmail(targetEmail).orElseThrow(() -> new CustomException(ExceptionCode.USER_NOT_EXIST)); - if(!reqLoginId.equals(targetLoginId)){ - User reqUser = userRepository.findByLoginId(reqLoginId).orElseThrow(() -> new CustomException(ExceptionCode.USER_NOT_EXIST)); + if(!reqEmail.equals(targetEmail)){ + User reqUser = userRepository.findByEmail(reqEmail).orElseThrow(() -> new CustomException(ExceptionCode.USER_NOT_EXIST)); isFollow = friendService.checkIsFollow(reqUser, targetUser); } @@ -59,10 +59,10 @@ public UserProfileResDto getUserProfile(String reqLoginId, String targetLoginId) @Override @Transactional(readOnly = true) - public ProfileCntResDto getUserProfileCnt(String loginId) { - User user = userRepository.findByLoginId(loginId).orElseThrow(() -> new CustomException(ExceptionCode.USER_NOT_EXIST)); + public ProfileCntResDto getUserProfileCnt(String email) { + User user = userRepository.findByEmail(email).orElseThrow(() -> new CustomException(ExceptionCode.USER_NOT_EXIST)); Long userSnapCnt = snapRepository.countByUser(user); - FriendCntResDto friendCntResDto = friendService.findFriendCnt(loginId); + FriendCntResDto friendCntResDto = friendService.findFriendCnt(email); return ProfileCntResDto.builder() .snapCnt(userSnapCnt) @@ -73,8 +73,8 @@ public ProfileCntResDto getUserProfileCnt(String loginId) { @Override @Transactional(readOnly = true) - public List getTagSnap(String loginId) { - User user = userRepository.findByLoginId(loginId).orElseThrow(() -> new CustomException(ExceptionCode.USER_NOT_EXIST)); + public List getTagSnap(String email) { + User user = userRepository.findByEmail(email).orElseThrow(() -> new CustomException(ExceptionCode.USER_NOT_EXIST)); return profileRepository.findTagSnap(user); } diff --git a/src/main/java/me/snaptime/profilePhoto/controller/ProfilePhotoController.java b/src/main/java/me/snaptime/profilePhoto/controller/ProfilePhotoController.java index 678d526c..17515591 100644 --- a/src/main/java/me/snaptime/profilePhoto/controller/ProfilePhotoController.java +++ b/src/main/java/me/snaptime/profilePhoto/controller/ProfilePhotoController.java @@ -44,9 +44,9 @@ public ResponseEntity downloadProfileToFileSystem(@PathVariable("profilePhoto @PutMapping(consumes = MULTIPART_FORM_DATA) public ResponseEntity updateProfileToFileSystem(@AuthenticationPrincipal UserDetails userDetails, @RequestParam MultipartFile file) throws Exception { - String loginId = userDetails.getUsername(); - log.info("[updateProfile] 유저의 프로필 사진을 수정합니다. loginId : {}", loginId); - ProfilePhotoResDto updateProfile = profilePhotoService.updatePhotoFromFileSystem(loginId, file); + String userEmail = userDetails.getUsername(); + log.info("[updateProfile] 유저의 프로필 사진을 수정합니다. userEmail : {}", userEmail); + ProfilePhotoResDto updateProfile = profilePhotoService.updatePhotoFromFileSystem(userEmail, file); return ResponseEntity.status(HttpStatus.OK).body( new CommonResponseDto<>( "프로필 사진 수정을 성공적으로 완료하였습니다.", diff --git a/src/main/java/me/snaptime/profilePhoto/service/ProfilePhotoService.java b/src/main/java/me/snaptime/profilePhoto/service/ProfilePhotoService.java index 56bfff03..16bbc926 100644 --- a/src/main/java/me/snaptime/profilePhoto/service/ProfilePhotoService.java +++ b/src/main/java/me/snaptime/profilePhoto/service/ProfilePhotoService.java @@ -6,6 +6,6 @@ public interface ProfilePhotoService { byte[] downloadPhotoFromFileSystem(Long profilePhotoId); - ProfilePhotoResDto updatePhotoFromFileSystem(String loginId, MultipartFile updateFile) throws Exception; + ProfilePhotoResDto updatePhotoFromFileSystem(String userEmail, MultipartFile updateFile) throws Exception; } diff --git a/src/main/java/me/snaptime/profilePhoto/service/impl/ProfilePhotoServiceImpl.java b/src/main/java/me/snaptime/profilePhoto/service/impl/ProfilePhotoServiceImpl.java index 5bccb795..173fae1b 100644 --- a/src/main/java/me/snaptime/profilePhoto/service/impl/ProfilePhotoServiceImpl.java +++ b/src/main/java/me/snaptime/profilePhoto/service/impl/ProfilePhotoServiceImpl.java @@ -72,8 +72,8 @@ public byte[] downloadPhotoFromFileSystem(Long profilePhotoId){ //트랜잭션 어노테이션을 사용하면 upload -> delete -> update, 프로필을 삭제를 해도 수정에 성공함. @Override @Transactional - public ProfilePhotoResDto updatePhotoFromFileSystem(String loginId, MultipartFile updateFile) throws Exception{ - User updateUser = userRepository.findByLoginId(loginId).orElseThrow(()-> new CustomException(ExceptionCode.USER_NOT_EXIST)); + public ProfilePhotoResDto updatePhotoFromFileSystem(String email, MultipartFile updateFile) throws Exception{ + User updateUser = userRepository.findByEmail(email).orElseThrow(()-> new CustomException(ExceptionCode.USER_NOT_EXIST)); ProfilePhoto profilePhoto = profilePhotoRepository.findById(updateUser.getProfilePhoto().getProfilePhotoId()).orElseThrow(()-> new CustomException(ExceptionCode.PROFILE_PHOTO_NOT_FOUND)); String updateFileName = FileNameGenerator.generatorName(updateFile.getOriginalFilename()); diff --git a/src/main/java/me/snaptime/reply/dto/req/ChildReplyAddReqDto.java b/src/main/java/me/snaptime/reply/dto/req/ChildReplyAddReqDto.java index f7410008..827f5ddf 100644 --- a/src/main/java/me/snaptime/reply/dto/req/ChildReplyAddReqDto.java +++ b/src/main/java/me/snaptime/reply/dto/req/ChildReplyAddReqDto.java @@ -21,8 +21,8 @@ public record ChildReplyAddReqDto( @Schema( example = "홍길동", - description = "태그할 유저의 loginId를 입력해주세요. 없으면 입력하지 않아도 됩니다." + description = "태그할 유저의 email을 입력해주세요. 없으면 입력하지 않아도 됩니다." ) - String tagLoginId + String tagEmail ) { } diff --git a/src/main/java/me/snaptime/reply/dto/res/ChildReplyInfoResDto.java b/src/main/java/me/snaptime/reply/dto/res/ChildReplyInfoResDto.java index b3efe2ff..0c78585b 100644 --- a/src/main/java/me/snaptime/reply/dto/res/ChildReplyInfoResDto.java +++ b/src/main/java/me/snaptime/reply/dto/res/ChildReplyInfoResDto.java @@ -7,11 +7,11 @@ @Builder public record ChildReplyInfoResDto( - String writerLoginId, + String writerEmail, String writerUserName, String writerProfilePhotoURL, String content, - String tagUserLoginId, + String tagUserEmail, String tagUserName, Long parentReplyId, Long childReplyId, @@ -21,7 +21,7 @@ public record ChildReplyInfoResDto( public static ChildReplyInfoResDto toDto(ChildReply childReply, String profilePhotoURL, String timeAgo){ if(childReply.getReplyTagUser() == null){ return ChildReplyInfoResDto.builder() - .writerLoginId(childReply.getUser().getLoginId()) + .writerEmail(childReply.getUser().getEmail()) .writerProfilePhotoURL(profilePhotoURL) .writerUserName(childReply.getUser().getName()) .content(childReply.getContent()) @@ -31,11 +31,11 @@ public static ChildReplyInfoResDto toDto(ChildReply childReply, String profilePh .build(); } return ChildReplyInfoResDto.builder() - .writerLoginId(childReply.getUser().getLoginId()) + .writerEmail(childReply.getUser().getEmail()) .writerProfilePhotoURL(profilePhotoURL) .writerUserName(childReply.getUser().getName()) .content(childReply.getContent()) - .tagUserLoginId(childReply.getReplyTagUser().getLoginId()) + .tagUserEmail(childReply.getReplyTagUser().getEmail()) .tagUserName(childReply.getReplyTagUser().getName()) .parentReplyId(childReply.getParentReply().getParentReplyId()) .childReplyId(childReply.getChildReplyId()) diff --git a/src/main/java/me/snaptime/reply/dto/res/ParentReplyInfoResDto.java b/src/main/java/me/snaptime/reply/dto/res/ParentReplyInfoResDto.java index 4a3ca20c..fed36ce4 100644 --- a/src/main/java/me/snaptime/reply/dto/res/ParentReplyInfoResDto.java +++ b/src/main/java/me/snaptime/reply/dto/res/ParentReplyInfoResDto.java @@ -10,7 +10,7 @@ @Builder public record ParentReplyInfoResDto( - String writerLoginId, + String writerEmail, String writerProfilePhotoURL, String writerUserName, String content, @@ -19,7 +19,7 @@ public record ParentReplyInfoResDto( ) { public static ParentReplyInfoResDto toDto(Tuple tuple, String profilePhotoURL, String timeAgo){ return ParentReplyInfoResDto.builder() - .writerLoginId(tuple.get(user.loginId)) + .writerEmail(tuple.get(user.email)) .writerProfilePhotoURL(profilePhotoURL) .writerUserName(tuple.get(user.name)) .content(tuple.get(parentReply.content)) diff --git a/src/main/java/me/snaptime/reply/repository/impl/ParentReplyPagingRepositoryImpl.java b/src/main/java/me/snaptime/reply/repository/impl/ParentReplyPagingRepositoryImpl.java index cdbecd42..0463d507 100644 --- a/src/main/java/me/snaptime/reply/repository/impl/ParentReplyPagingRepositoryImpl.java +++ b/src/main/java/me/snaptime/reply/repository/impl/ParentReplyPagingRepositoryImpl.java @@ -27,7 +27,7 @@ public List findReplyPage(Long snapId, Long pageNum) { Pageable pageable= PageRequest.of((int) (pageNum-1),20); List tuples = jpaQueryFactory.select( - user.loginId,user.profilePhoto.profilePhotoId,user.name, + user.email,user.profilePhoto.profilePhotoId,user.name, parentReply.content,parentReply.parentReplyId,parentReply.lastModifiedDate ) .from(parentReply) diff --git a/src/main/java/me/snaptime/reply/service/ReplyService.java b/src/main/java/me/snaptime/reply/service/ReplyService.java index cff0731e..298aacb7 100644 --- a/src/main/java/me/snaptime/reply/service/ReplyService.java +++ b/src/main/java/me/snaptime/reply/service/ReplyService.java @@ -8,10 +8,10 @@ public interface ReplyService { // 댓글을 추가합니다. - void addParentReply(String reqLoginId, ParentReplyAddReqDto parentReplyAddReqDto); + void addParentReply(String reqEmail, ParentReplyAddReqDto parentReplyAddReqDto); // 댓글에 대댓글을 추가합니다. - void addChildReply(String reqLoginId, ChildReplyAddReqDto childReplyAddReqDto); + void addChildReply(String reqEmail, ChildReplyAddReqDto childReplyAddReqDto); /* 댓글을 최신순으로 20개씩 조회합니다. @@ -26,17 +26,17 @@ public interface ReplyService { ChildReplyPagingResDto findChildReplyPage(Long parentReplyId, Long pageNum); // 댓글을 변경합니다. - void updateParentReply(String reqLoginId ,Long parentReplyId, String newContent); + void updateParentReply(String reqEmail ,Long parentReplyId, String newContent); // 대댓글을 변경합니다. - void updateChildReply(String reqLoginId, Long childReplyId, String newContent); + void updateChildReply(String reqEmail, Long childReplyId, String newContent); /* 댓글을 삭제합니다. 댓글에 달린 모든 대댓글까지 함께 삭제됩니다. */ - void deleteParentReply(String reqLoginId, Long parentReplyId); + void deleteParentReply(String reqEmail, Long parentReplyId); // 대댓글을 삭제합니다. - void deleteChildReply(String reqLoginId, Long childReplyId); + void deleteChildReply(String reqEmail, Long childReplyId); } diff --git a/src/main/java/me/snaptime/reply/service/impl/ReplyServiceImpl.java b/src/main/java/me/snaptime/reply/service/impl/ReplyServiceImpl.java index fb0b00f0..c84ce757 100644 --- a/src/main/java/me/snaptime/reply/service/impl/ReplyServiceImpl.java +++ b/src/main/java/me/snaptime/reply/service/impl/ReplyServiceImpl.java @@ -47,8 +47,8 @@ public class ReplyServiceImpl implements ReplyService { @Override @Transactional - public void addParentReply(String reqLoginId, ParentReplyAddReqDto parentReplyAddReqDto){ - User reqUser = findUserByLoginId(reqLoginId); + public void addParentReply(String reqEmail, ParentReplyAddReqDto parentReplyAddReqDto){ + User reqUser = findUserByEmail(reqEmail); Snap snap = snapRepository.findById(parentReplyAddReqDto.snapId()) .orElseThrow(() -> new CustomException(ExceptionCode.SNAP_NOT_EXIST)); @@ -64,15 +64,15 @@ public void addParentReply(String reqLoginId, ParentReplyAddReqDto parentReplyAd } @Transactional - public void addChildReply(String reqLoginId, ChildReplyAddReqDto childReplyAddReqDto){ - User reqUser = findUserByLoginId(reqLoginId); + public void addChildReply(String reqEmail, ChildReplyAddReqDto childReplyAddReqDto){ + User reqUser = findUserByEmail(reqEmail); ParentReply parentReply = parentReplyRepository.findById(childReplyAddReqDto.parentReplyId()) .orElseThrow(() -> new CustomException(ExceptionCode.REPLY_NOT_FOUND)); Snap snap = parentReply.getSnap(); // 태그유저가 없는 댓글 등록이면 - if( childReplyAddReqDto.tagLoginId().isBlank()){ + if( childReplyAddReqDto.tagEmail().isBlank()){ childReplyRepository.save( ChildReply.builder() .parentReply(parentReply) @@ -83,7 +83,7 @@ public void addChildReply(String reqLoginId, ChildReplyAddReqDto childReplyAddRe } // 태그유저가 있는 댓글등록이면 else{ - User tagUser = userRepository.findByLoginId(childReplyAddReqDto.tagLoginId()) + User tagUser = userRepository.findByEmail(childReplyAddReqDto.tagEmail()) .orElseThrow(() -> new CustomException(ExceptionCode.USER_NOT_EXIST)); childReplyRepository.save( @@ -131,51 +131,51 @@ public ChildReplyPagingResDto findChildReplyPage(Long parentReplyId, Long pageNu } @Transactional - public void updateParentReply(String reqLoginId ,Long parentReplyId, String newContent){ + public void updateParentReply(String reqEmail ,Long parentReplyId, String newContent){ ParentReply parentReply = parentReplyRepository.findById(parentReplyId) .orElseThrow(() -> new CustomException(ExceptionCode.REPLY_NOT_FOUND)); - isMyReply(reqLoginId,parentReply.getUser().getLoginId()); + isMyReply(reqEmail,parentReply.getUser().getEmail()); parentReply.updateReply(newContent); parentReplyRepository.save(parentReply); } @Transactional - public void updateChildReply(String reqLoginId, Long childReplyId, String newContent){ + public void updateChildReply(String reqEmail, Long childReplyId, String newContent){ ChildReply childReply = childReplyRepository.findById(childReplyId) .orElseThrow(() -> new CustomException(ExceptionCode.REPLY_NOT_FOUND)); - isMyReply(reqLoginId,childReply.getUser().getLoginId()); + isMyReply(reqEmail,childReply.getUser().getEmail()); childReply.updateReply(newContent); childReplyRepository.save(childReply); } @Transactional - public void deleteParentReply(String reqLoginId, Long parentReplyId){ + public void deleteParentReply(String reqEmail, Long parentReplyId){ ParentReply parentReply = parentReplyRepository.findById(parentReplyId) .orElseThrow(() -> new CustomException(ExceptionCode.REPLY_NOT_FOUND)); - isMyReply(reqLoginId,parentReply.getUser().getLoginId()); + isMyReply(reqEmail,parentReply.getUser().getEmail()); parentReplyRepository.delete(parentReply); } @Transactional - public void deleteChildReply(String reqLoginId, Long childReplyId){ + public void deleteChildReply(String reqEmail, Long childReplyId){ ChildReply childReply = childReplyRepository.findById(childReplyId) .orElseThrow(() -> new CustomException(ExceptionCode.REPLY_NOT_FOUND)); - isMyReply(reqLoginId,childReply.getUser().getLoginId()); + isMyReply(reqEmail,childReply.getUser().getEmail()); childReplyRepository.delete(childReply); } - private User findUserByLoginId(String loginId){ - return userRepository.findByLoginId(loginId) + private User findUserByEmail(String email){ + return userRepository.findByEmail(email) .orElseThrow(() -> new CustomException(ExceptionCode.USER_NOT_EXIST)); } - private void isMyReply(String reqLoginId, String targetLoginId){ + private void isMyReply(String reqEmail, String targetEmail){ - if(!targetLoginId.equals(reqLoginId)) + if(!targetEmail.equals(reqEmail)) throw new CustomException(ExceptionCode.ACCESS_FAIL_REPLY); } } \ No newline at end of file diff --git a/src/main/java/me/snaptime/snap/controller/PhotoController.java b/src/main/java/me/snaptime/snap/controller/PhotoController.java index f9ac94db..c932e8c7 100644 --- a/src/main/java/me/snaptime/snap/controller/PhotoController.java +++ b/src/main/java/me/snaptime/snap/controller/PhotoController.java @@ -33,9 +33,9 @@ public ResponseEntity findPhoto( final @RequestParam("isEncrypted") boolean isEncrypted, final @AuthenticationPrincipal UserDetails userDetails ) { - String uId = userDetails.getUsername(); + String userEmail = userDetails.getUsername(); return ResponseEntity.status(HttpStatus.OK).contentType(MediaType.IMAGE_PNG).body( - snapService.downloadPhotoFromFileSystem(fileName, uId, isEncrypted) + snapService.downloadPhotoFromFileSystem(fileName, userEmail, isEncrypted) ); } } diff --git a/src/main/java/me/snaptime/snap/controller/SnapController.java b/src/main/java/me/snaptime/snap/controller/SnapController.java index 545140e4..a3c693a6 100644 --- a/src/main/java/me/snaptime/snap/controller/SnapController.java +++ b/src/main/java/me/snaptime/snap/controller/SnapController.java @@ -33,12 +33,12 @@ public class SnapController { public ResponseEntity> createSnap( final @RequestParam(value = "isPrivate") boolean isPrivate, final @RequestParam(value = "albumId", required = false) Long album_id, - final @RequestParam(value = "tagUserLoginIds", required = false) List tagUserLoginIds, + final @RequestParam(value = "tagUserEmails", required = false) List tagUserEmails, final @ModelAttribute CreateSnapReqDto createSnapReqDto, final @AuthenticationPrincipal UserDetails userDetails ) { - String uId = userDetails.getUsername(); - Long snapId = snapService.createSnap(createSnapReqDto, uId, isPrivate, tagUserLoginIds, album_id); + String userEmail = userDetails.getUsername(); + Long snapId = snapService.createSnap(createSnapReqDto, userEmail, isPrivate, tagUserEmails, album_id); return ResponseEntity.status(HttpStatus.CREATED) .body(new CommonResponseDto<>( @@ -54,11 +54,11 @@ public ResponseEntity> findSnap( final @PathVariable("id") Long id, final @AuthenticationPrincipal UserDetails userDetails ) { - String uId = userDetails.getUsername(); + String userEmail = userDetails.getUsername(); return ResponseEntity.status(HttpStatus.OK).body( new CommonResponseDto<>( "스냅이 정상적으로 불러와졌습니다.", - snapService.findSnap(id, uId) + snapService.findSnap(id, userEmail) ) ); } @@ -67,21 +67,21 @@ public ResponseEntity> findSnap( @Parameters({ @Parameter(name = "isPrivate", description = "변경 할 상태"), @Parameter(name = "snapId", description = "변경 할 Snap의 ID"), - @Parameter(name = "tagUserLoginIds", description = "변경 할 TagID") + @Parameter(name = "tagUserEmails", description = "변경 할 TagID") }) @PutMapping(consumes = {MediaType.MULTIPART_FORM_DATA_VALUE}) public ResponseEntity> modifySnap( final @ModelAttribute ModifySnapReqDto modifySnapReqDto, final @RequestParam boolean isPrivate, final @RequestParam Long snapId, - final @RequestParam(required = false) List tagUserLoginIds, + final @RequestParam(required = false) List tagUserEmails, final @AuthenticationPrincipal UserDetails userDetails ) { - String uId = userDetails.getUsername(); + String userEmail = userDetails.getUsername(); return ResponseEntity.status(HttpStatus.OK).body( new CommonResponseDto<>( "스냅이 정상적으로 수정되었습니다.", - snapService.modifySnap(snapId, modifySnapReqDto, uId, tagUserLoginIds, isPrivate) + snapService.modifySnap(snapId, modifySnapReqDto, userEmail, tagUserEmails, isPrivate) ) ); } @@ -97,8 +97,8 @@ public ResponseEntity> changeVisibility( final @RequestParam("isPrivate") boolean isPrivate, final @AuthenticationPrincipal UserDetails userDetails ) { - String uId = userDetails.getUsername(); - snapService.changeVisibility(snapId, uId, isPrivate); + String userEmail = userDetails.getUsername(); + snapService.changeVisibility(snapId, userEmail, isPrivate); return ResponseEntity.status(HttpStatus.OK).body( new CommonResponseDto<>( "게시글의 상태가 성공적으로 변경되었습니다.", @@ -118,8 +118,8 @@ ResponseEntity> relocateSnap( final @RequestParam Long albumId, final @AuthenticationPrincipal UserDetails userDetails ) { - String uId = userDetails.getUsername(); - snapService.relocateSnap(snapId, albumId, uId); + String userEmail = userDetails.getUsername(); + snapService.relocateSnap(snapId, albumId, userEmail); return ResponseEntity.status(HttpStatus.OK).body( new CommonResponseDto<>( "스냅의 위치가 " + albumId + "번 앨범으로 변경되었습니다.", @@ -135,8 +135,8 @@ ResponseEntity> deleteSnap( final @RequestParam Long snapId, final @AuthenticationPrincipal UserDetails userDetails ) { - String uId = userDetails.getUsername(); - snapService.deleteSnap(snapId, uId); + String userEmail = userDetails.getUsername(); + snapService.deleteSnap(snapId, userEmail); return ResponseEntity.status(HttpStatus.OK).body( new CommonResponseDto<>( snapId + "번 스냅이 삭제되었습니다.", diff --git a/src/main/java/me/snaptime/snap/controller/SnapPagingController.java b/src/main/java/me/snaptime/snap/controller/SnapPagingController.java index 09dd7cdf..09599754 100644 --- a/src/main/java/me/snaptime/snap/controller/SnapPagingController.java +++ b/src/main/java/me/snaptime/snap/controller/SnapPagingController.java @@ -29,9 +29,9 @@ public ResponseEntity> findSnapPage( @AuthenticationPrincipal final UserDetails userDetails, @PathVariable final Long pageNum) { - String reqLoginId = userDetails.getUsername(); + String reqUserEmail = userDetails.getUsername(); return ResponseEntity.status(HttpStatus.OK).body(new CommonResponseDto( - "스냅 페이징조회가 완료되었습니다.", snapPagingService.findSnapPage(reqLoginId,pageNum))); + "스냅 페이징조회가 완료되었습니다.", snapPagingService.findSnapPage(reqUserEmail,pageNum))); } } diff --git a/src/main/java/me/snaptime/snap/dto/res/SnapDetailInfoResDto.java b/src/main/java/me/snaptime/snap/dto/res/SnapDetailInfoResDto.java index 3810a665..41e26497 100644 --- a/src/main/java/me/snaptime/snap/dto/res/SnapDetailInfoResDto.java +++ b/src/main/java/me/snaptime/snap/dto/res/SnapDetailInfoResDto.java @@ -20,7 +20,7 @@ public record SnapDetailInfoResDto( String snapPhotoURL, LocalDateTime snapCreatedDate, LocalDateTime snapModifiedDate, - String writerLoginId, + String writerEmail, String profilePhotoURL, String writerUserName, List tagUserFindResDtos, @@ -36,7 +36,7 @@ public static SnapDetailInfoResDto toDto(Tuple tuple, String profilePhotoURL, St .snapPhotoURL(snapPhotoURL) .snapCreatedDate(tuple.get(snap.createdDate)) .snapModifiedDate(tuple.get(snap.lastModifiedDate)) - .writerLoginId(tuple.get(user.loginId)) + .writerEmail(tuple.get(user.email)) .profilePhotoURL(profilePhotoURL) .writerUserName(tuple.get(user.name)) .tagUserFindResDtos(tagUserFindResDtos) @@ -54,7 +54,7 @@ public static SnapDetailInfoResDto toDto(Snap snap, String profilePhotoURL, Stri .snapPhotoURL(snapPhotoURL) .snapCreatedDate(snap.getCreatedDate()) .snapModifiedDate(snap.getLastModifiedDate()) - .writerLoginId(snap.getUser().getLoginId()) + .writerEmail(snap.getUser().getEmail()) .profilePhotoURL(profilePhotoURL) .writerUserName(snap.getUser().getName()) .tagUserFindResDtos(tagUserFindResDtos) diff --git a/src/main/java/me/snaptime/snap/dto/res/SnapInfoResDto.java b/src/main/java/me/snaptime/snap/dto/res/SnapInfoResDto.java index f0a3b2fc..48a83948 100644 --- a/src/main/java/me/snaptime/snap/dto/res/SnapInfoResDto.java +++ b/src/main/java/me/snaptime/snap/dto/res/SnapInfoResDto.java @@ -12,15 +12,15 @@ public record SnapInfoResDto( String snapPhotoURL, LocalDateTime snapCreatedDate, LocalDateTime snapModifiedDate, - String loginId, + String email, String profilePhotoURL, String userName ) { public static SnapInfoResDto entityToResDto(Snap entity, String snapPhotoURL, String profilePhotoURL) { - String userUid = null; + String userEmail = null; String userName = null; if (entity.getUser() != null) { - userUid = entity.getUser().getLoginId(); + userEmail = entity.getUser().getEmail(); userName = entity.getUser().getName(); } return SnapInfoResDto.builder() @@ -29,7 +29,7 @@ public static SnapInfoResDto entityToResDto(Snap entity, String snapPhotoURL, St .snapPhotoURL(snapPhotoURL) .snapCreatedDate(entity.getCreatedDate()) .snapModifiedDate(entity.getLastModifiedDate()) - .loginId(userUid) + .email(userEmail) .profilePhotoURL(profilePhotoURL) .userName(userName) .build(); diff --git a/src/main/java/me/snaptime/snap/repository/impl/SnapPagingRepositoryImpl.java b/src/main/java/me/snaptime/snap/repository/impl/SnapPagingRepositoryImpl.java index 05a9893e..6270edcd 100644 --- a/src/main/java/me/snaptime/snap/repository/impl/SnapPagingRepositoryImpl.java +++ b/src/main/java/me/snaptime/snap/repository/impl/SnapPagingRepositoryImpl.java @@ -40,7 +40,7 @@ public List findSnapPage(Long pageNum, User reqUser) { followUserIds.add(reqUser.getUserId()); List tuples = jpaQueryFactory.select( - user.loginId, user.profilePhoto.profilePhotoId, user.name, + user.email, user.profilePhoto.profilePhotoId, user.name, snap.id, snap.createdDate, snap.lastModifiedDate, snap.oneLineJournal, snap.fileName ).distinct() .from(friend) diff --git a/src/main/java/me/snaptime/snap/service/SnapPagingService.java b/src/main/java/me/snaptime/snap/service/SnapPagingService.java index 60f1c8b5..f6d0188f 100644 --- a/src/main/java/me/snaptime/snap/service/SnapPagingService.java +++ b/src/main/java/me/snaptime/snap/service/SnapPagingService.java @@ -8,5 +8,5 @@ public interface SnapPagingService { 자신이 팔로우한 유저들의 스냅을 최신순으로 불러옵니다. 커뮤니티 기능이므로 10개씩 페이징처리를 합니다. */ - SnapPagingResDto findSnapPage(String reqLoginId, Long pageNum); + SnapPagingResDto findSnapPage(String reqEmail, Long pageNum); } diff --git a/src/main/java/me/snaptime/snap/service/SnapService.java b/src/main/java/me/snaptime/snap/service/SnapService.java index 9faa657f..8c9abbd6 100644 --- a/src/main/java/me/snaptime/snap/service/SnapService.java +++ b/src/main/java/me/snaptime/snap/service/SnapService.java @@ -8,11 +8,11 @@ public interface SnapService { - Long createSnap(CreateSnapReqDto createSnapReqDto, String userUid, boolean isPrivate, List tagUserLoginIds, Long album_id); - SnapDetailInfoResDto findSnap(Long id, String uId); - Long modifySnap(Long snapId, ModifySnapReqDto modifySnapReqDto, String userUid, List tagUserLoginIds, boolean isPrivate); - void changeVisibility(Long snapId, String userUid, boolean isPrivate); - void deleteSnap(Long id, String Uid); - byte[] downloadPhotoFromFileSystem(String fileName, String uId, boolean isEncrypted); - void relocateSnap(Long snapId, Long albumId, String uId); + Long createSnap(CreateSnapReqDto createSnapReqDto, String userEmail, boolean isPrivate, List tagUserEmails, Long album_id); + SnapDetailInfoResDto findSnap(Long id, String userEmail); + Long modifySnap(Long snapId, ModifySnapReqDto modifySnapReqDto, String userEmail, List tagUserEmails, boolean isPrivate); + void changeVisibility(Long snapId, String userEmail, boolean isPrivate); + void deleteSnap(Long id, String userEmail); + byte[] downloadPhotoFromFileSystem(String fileName, String userEmail, boolean isEncrypted); + void relocateSnap(Long snapId, Long albumId, String userEmail); } diff --git a/src/main/java/me/snaptime/snap/service/impl/SnapPagingServiceImpl.java b/src/main/java/me/snaptime/snap/service/impl/SnapPagingServiceImpl.java index d719414d..724e19fa 100644 --- a/src/main/java/me/snaptime/snap/service/impl/SnapPagingServiceImpl.java +++ b/src/main/java/me/snaptime/snap/service/impl/SnapPagingServiceImpl.java @@ -35,9 +35,9 @@ public class SnapPagingServiceImpl implements SnapPagingService { private final SnapTagService snapTagService; private final SnapLikeService snapLikeService; - public SnapPagingResDto findSnapPage(String reqLoginId, Long pageNum){ + public SnapPagingResDto findSnapPage(String reqEmail, Long pageNum){ - User reqUser = userRepository.findByLoginId(reqLoginId) + User reqUser = userRepository.findByEmail(reqEmail) .orElseThrow(() -> new CustomException(ExceptionCode.USER_NOT_EXIST)); List tuples = snapRepository.findSnapPage(pageNum,reqUser); @@ -53,7 +53,7 @@ public SnapPagingResDto findSnapPage(String reqLoginId, Long pageNum){ return SnapDetailInfoResDto.toDto(tuple,profilePhotoURL,snapPhotoURL, snapTagService.findTagUsers(snapId), snapLikeService.findSnapLikeCnt(snapId), - snapLikeService.isLikedSnap(snapId, reqLoginId)); + snapLikeService.isLikedSnap(snapId, reqEmail)); }).collect(Collectors.toList()); return SnapPagingResDto.toDto(snapDetailInfoResDtos,hasNextPage); diff --git a/src/main/java/me/snaptime/snap/service/impl/SnapServiceImpl.java b/src/main/java/me/snaptime/snap/service/impl/SnapServiceImpl.java index edf89e7d..44337b87 100644 --- a/src/main/java/me/snaptime/snap/service/impl/SnapServiceImpl.java +++ b/src/main/java/me/snaptime/snap/service/impl/SnapServiceImpl.java @@ -47,8 +47,8 @@ public class SnapServiceImpl implements SnapService { private final SnapLikeService snapLikeService; @Override - public Long createSnap(CreateSnapReqDto createSnapReqDto, String userUid, boolean isPrivate, List tagUserLoginIds, Long album_id) { - User foundUser = userRepository.findByLoginId(userUid).orElseThrow(() -> new CustomException(ExceptionCode.USER_NOT_EXIST)); + public Long createSnap(CreateSnapReqDto createSnapReqDto, String userEmail, boolean isPrivate, List tagUserEmails, Long album_id) { + User foundUser = userRepository.findByEmail(userEmail).orElseThrow(() -> new CustomException(ExceptionCode.USER_NOT_EXIST)); WritePhotoToFileSystemResult writePhotoToFileSystemResult = savePhotoToFileSystem(foundUser, createSnapReqDto.multipartFile(), isPrivate); Snap savedSnap = snapRepository.save( Snap.builder() @@ -77,18 +77,18 @@ public Long createSnap(CreateSnapReqDto createSnapReqDto, String userUid, boolea } // tagUserLoginIds가 파라미터로 주어졌을 경우 태그에 추가 - if (tagUserLoginIds != null) { - snapTagService.addTagUser(tagUserLoginIds, savedSnap); + if (tagUserEmails != null) { + snapTagService.addTagUser(tagUserEmails, savedSnap); } return savedSnap.getId(); } @Override - public SnapDetailInfoResDto findSnap(Long id, String uId) { + public SnapDetailInfoResDto findSnap(Long id, String userEmail) { Snap foundSnap = snapRepository.findById(id).orElseThrow(() -> new CustomException(ExceptionCode.SNAP_NOT_EXIST)); if(foundSnap.isPrivate()) { - User foundUser = userRepository.findByLoginId(uId).orElseThrow(() -> new CustomException(ExceptionCode.USER_NOT_EXIST)); + User foundUser = userRepository.findByEmail(userEmail).orElseThrow(() -> new CustomException(ExceptionCode.USER_NOT_EXIST)); // Snap이 비공개라면, 요청한 유저와 스냅의 ID가 일치하는지 확인한다. if (!Objects.equals(foundUser.getUserId(), foundSnap.getUser().getUserId())) { throw new CustomException(ExceptionCode.SNAP_IS_PRIVATE); @@ -98,14 +98,14 @@ public SnapDetailInfoResDto findSnap(Long id, String uId) { String profilePhotoUrl = urlComponent.makeProfileURL(foundSnap.getUser().getProfilePhoto().getProfilePhotoId()); List tagUserFindResDtos = snapTagService.findTagUsers(foundSnap.getId()); Long likeCnt = snapLikeService.findSnapLikeCnt(foundSnap.getId()); - boolean isLikedSnap = snapLikeService.isLikedSnap(foundSnap.getId(), uId); + boolean isLikedSnap = snapLikeService.isLikedSnap(foundSnap.getId(), userEmail); return SnapDetailInfoResDto.toDto(foundSnap, profilePhotoUrl, snapPhotoUrl, tagUserFindResDtos, likeCnt, isLikedSnap); } @Override - public Long modifySnap(Long snapId, ModifySnapReqDto modifySnapReqDto, String userUid, List tagUserLoginIds, boolean isPrivate) { + public Long modifySnap(Long snapId, ModifySnapReqDto modifySnapReqDto, String userEmail, List tagUserEmails, boolean isPrivate) { Snap foundSnap = snapRepository.findById(snapId).orElseThrow(() -> new CustomException(ExceptionCode.SNAP_NOT_EXIST)); - User foundUser = userRepository.findByLoginId(userUid).orElseThrow(() -> new CustomException(ExceptionCode.USER_NOT_EXIST)); + User foundUser = userRepository.findByEmail(userEmail).orElseThrow(() -> new CustomException(ExceptionCode.USER_NOT_EXIST)); // 수정하려는 유저와 수정되려는 스냅의 저자가 일치하는지 확인한다. if (!foundSnap.getUser().getUserId().equals(foundUser.getUserId())) { @@ -142,8 +142,8 @@ public Long modifySnap(Long snapId, ModifySnapReqDto modifySnapReqDto, String us // Snap의 암호화 상태를 비활성화로 변경한다. foundSnap.updateIsPrivate(false); - if (tagUserLoginIds != null) { - snapTagService.modifyTagUser(tagUserLoginIds, foundSnap); + if (tagUserEmails != null) { + snapTagService.modifyTagUser(tagUserEmails, foundSnap); } } } catch (IOException e) { @@ -156,9 +156,9 @@ public Long modifySnap(Long snapId, ModifySnapReqDto modifySnapReqDto, String us } @Override - public void changeVisibility(Long snapId, String userUid, boolean isPrivate) { + public void changeVisibility(Long snapId, String userEmail, boolean isPrivate) { Snap foundSnap = snapRepository.findById(snapId).orElseThrow(() -> new CustomException(ExceptionCode.SNAP_NOT_EXIST)); - User foundUser = userRepository.findByLoginId(userUid).orElseThrow(() -> new CustomException(ExceptionCode.USER_NOT_EXIST)); + User foundUser = userRepository.findByEmail(userEmail).orElseThrow(() -> new CustomException(ExceptionCode.USER_NOT_EXIST)); // 설정되어 있는 값하고 똑같다면 if (foundSnap.isPrivate() == isPrivate) { @@ -189,9 +189,9 @@ public void changeVisibility(Long snapId, String userUid, boolean isPrivate) { } @Override - public void deleteSnap(Long snapId, String uId) { + public void deleteSnap(Long snapId, String userEmail) { Snap foundSnap = snapRepository.findById(snapId).orElseThrow(() -> new CustomException(ExceptionCode.SNAP_NOT_EXIST)); - User foundUser = userRepository.findByLoginId(uId).orElseThrow(() -> new CustomException(ExceptionCode.USER_NOT_EXIST)); + User foundUser = userRepository.findByEmail(userEmail).orElseThrow(() -> new CustomException(ExceptionCode.USER_NOT_EXIST)); // 삭제를 요청한 사용자가 Snap를 만든 사용자인지 확인한다. if (!Objects.equals(foundSnap.getUser().getUserId(), foundUser.getUserId())) { @@ -206,11 +206,11 @@ public void deleteSnap(Long snapId, String uId) { } @Override - public byte[] downloadPhotoFromFileSystem(String fileName, String uId, boolean isEncrypted) { + public byte[] downloadPhotoFromFileSystem(String fileName, String userEmail, boolean isEncrypted) { byte[] photoData = fileComponent.downloadPhotoFromFileSystem(fileName); if (isEncrypted) { try { - SecretKey secretKey = encryptionComponent.getSecretKey(uId); + SecretKey secretKey = encryptionComponent.getSecretKey(userEmail); return EncryptionUtil.decryptData(photoData, secretKey); } catch (Exception e) { log.error(e.getMessage()); @@ -221,10 +221,10 @@ public byte[] downloadPhotoFromFileSystem(String fileName, String uId, boolean i } @Override - public void relocateSnap(Long snapId, Long albumId, String uId) { + public void relocateSnap(Long snapId, Long albumId, String userEmail) { Snap foundSnap = snapRepository.findById(snapId).orElseThrow(() -> new CustomException(ExceptionCode.SNAP_NOT_EXIST)); Album foundAlbum = albumRepository.findById(albumId).orElseThrow(() -> new CustomException(ExceptionCode.ALBUM_NOT_EXIST)); - User foundUser = userRepository.findByLoginId(uId).orElseThrow(() -> new CustomException(ExceptionCode.USER_NOT_EXIST)); + User foundUser = userRepository.findByEmail(userEmail).orElseThrow(() -> new CustomException(ExceptionCode.USER_NOT_EXIST)); // 찾은 Snap의 소유자가 요청자와 일치하고, 새로 옮길 앨범의 소유자가 요청자와 일치한다면 if (Objects.equals(foundSnap.getUser().getUserId(), foundUser.getUserId()) && Objects.equals(foundSnap.getAlbum().getUser().getUserId(), foundUser.getUserId())) { // 새로 연관관계를 맺어주고 DB에 반영한다. diff --git a/src/main/java/me/snaptime/snapLike/service/impl/SnapLikeServiceImpl.java b/src/main/java/me/snaptime/snapLike/service/impl/SnapLikeServiceImpl.java index bfd44828..13f4454e 100644 --- a/src/main/java/me/snaptime/snapLike/service/impl/SnapLikeServiceImpl.java +++ b/src/main/java/me/snaptime/snapLike/service/impl/SnapLikeServiceImpl.java @@ -29,8 +29,8 @@ public class SnapLikeServiceImpl implements SnapLikeService { @Override @Transactional - public String toggleSnapLike(String reqLoginId, Long snapId){ - User reqUser = userRepository.findByLoginId(reqLoginId) + public String toggleSnapLike(String reqEmail, Long snapId){ + User reqUser = userRepository.findByEmail(reqEmail) .orElseThrow(() -> new CustomException(ExceptionCode.USER_NOT_EXIST)); Snap snap = snapRepository.findById(snapId) @@ -63,11 +63,11 @@ public Long findSnapLikeCnt(Long snapId){ } @Override - public boolean isLikedSnap(Long snapId, String reqLoginId){ + public boolean isLikedSnap(Long snapId, String reqEmail){ Snap snap = snapRepository.findById(snapId) .orElseThrow(() -> new CustomException(ExceptionCode.SNAP_NOT_EXIST)); - User reqUser = userRepository.findByLoginId(reqLoginId) + User reqUser = userRepository.findByEmail(reqEmail) .orElseThrow(() -> new CustomException(ExceptionCode.USER_NOT_EXIST)); return snapLikeRepository.existsBySnapAndUser(snap,reqUser); diff --git a/src/main/java/me/snaptime/snapTag/dto/res/TagUserFindResDto.java b/src/main/java/me/snaptime/snapTag/dto/res/TagUserFindResDto.java index aef7beeb..5087ea9c 100644 --- a/src/main/java/me/snaptime/snapTag/dto/res/TagUserFindResDto.java +++ b/src/main/java/me/snaptime/snapTag/dto/res/TagUserFindResDto.java @@ -6,13 +6,13 @@ @Builder public record TagUserFindResDto( - String tagUserLoginId, + String tagUserEmail, String tagUserName ) { public static TagUserFindResDto toDto(SnapTag snapTag){ return TagUserFindResDto.builder() - .tagUserLoginId(snapTag.getTagUser().getLoginId()) + .tagUserEmail(snapTag.getTagUser().getEmail()) .tagUserName(snapTag.getTagUser().getName()) .build(); } diff --git a/src/main/java/me/snaptime/snapTag/service/SnapTagService.java b/src/main/java/me/snaptime/snapTag/service/SnapTagService.java index 25d47d71..256ef462 100644 --- a/src/main/java/me/snaptime/snapTag/service/SnapTagService.java +++ b/src/main/java/me/snaptime/snapTag/service/SnapTagService.java @@ -8,10 +8,10 @@ public interface SnapTagService { // snap에 태그유저를 등록합니다. - void addTagUser(List tagUserLoginIds, Snap snap); + void addTagUser(List tagUserEmails, Snap snap); // 스냅 수정 시 태그정보를 갱신합니다. - void modifyTagUser(List tagUserLoginIds, Snap snap); + void modifyTagUser(List tagUserEmails, Snap snap); // 스냅에 저장된 모든 태그정보를 삭제합니다. void deleteAllTagUser(Snap snap); diff --git a/src/main/java/me/snaptime/snapTag/service/impl/SnapTagServiceImpl.java b/src/main/java/me/snaptime/snapTag/service/impl/SnapTagServiceImpl.java index 54f9c4f5..bc0b27ea 100644 --- a/src/main/java/me/snaptime/snapTag/service/impl/SnapTagServiceImpl.java +++ b/src/main/java/me/snaptime/snapTag/service/impl/SnapTagServiceImpl.java @@ -33,18 +33,18 @@ public class SnapTagServiceImpl implements SnapTagService { @Override @Transactional - public void addTagUser(List tagUserLoginIds, Snap snap){ + public void addTagUser(List tagUserEmails, Snap snap){ - if(tagUserLoginIds == null) - tagUserLoginIds = new ArrayList<>(); + if(tagUserEmails == null) + tagUserEmails = new ArrayList<>(); - List snapTags = tagUserLoginIds.stream().map( tagUserloginId -> { + List snapTags = tagUserEmails.stream().map( tagUserEmail -> { - User tagUser = userRepository.findByLoginId(tagUserloginId) + User tagUser = userRepository.findByEmail(tagUserEmail) .orElseThrow(() -> new CustomException(ExceptionCode.USER_NOT_EXIST)); // 셀프태그인지 체크 - checkSelfTag(snap,tagUserloginId); + checkSelfTag(snap,tagUserEmail); alarmAddService.createSnapAlarm(snap.getUser(), tagUser,snap, AlarmType.SNAPTAG); return SnapTag.builder() @@ -58,18 +58,18 @@ public void addTagUser(List tagUserLoginIds, Snap snap){ @Override @Transactional - public void modifyTagUser(List tagUserLoginIds, Snap snap){ + public void modifyTagUser(List tagUserEmails, Snap snap){ - if(tagUserLoginIds == null) - tagUserLoginIds = new ArrayList<>(); + if(tagUserEmails == null) + tagUserEmails = new ArrayList<>(); List snapTags = snapTagRepository.findBySnap(snap); // 태그유저 삭제 - snapTagRepository.deleteAll( findDeletedTagUsers(snapTags,tagUserLoginIds) ); + snapTagRepository.deleteAll( findDeletedTagUsers(snapTags,tagUserEmails) ); // 태그유저 추가 - snapTagRepository.saveAll( findNewTagUsers(tagUserLoginIds, snap) ); + snapTagRepository.saveAll( findNewTagUsers(tagUserEmails, snap) ); } @Override @@ -88,24 +88,24 @@ public List findTagUsers(Long snapId){ } // 삭제된 태그유저 추출 - private List findDeletedTagUsers(List snapTags, List tagUserLoginIds){ + private List findDeletedTagUsers(List snapTags, List tagUserEmails){ return snapTags.stream() - .filter(snapTag -> !tagUserLoginIds.contains(snapTag.getTagUser().getLoginId())) + .filter(snapTag -> !tagUserEmails.contains(snapTag.getTagUser().getEmail())) .collect(Collectors.toList()); } // 새롭게 추가된 태그유저 추출 - private List findNewTagUsers(List tagUserLoginIds, Snap snap){ + private List findNewTagUsers(List tagUserEmails, Snap snap){ - return tagUserLoginIds.stream().map( tagUserloginId-> { + return tagUserEmails.stream().map( tagUserEmail-> { - User tagUser = userRepository.findByLoginId(tagUserloginId) + User tagUser = userRepository.findByEmail(tagUserEmail) .orElseThrow(() -> new CustomException(ExceptionCode.USER_NOT_EXIST)); if(!snapTagRepository.existsBySnapAndTagUser(snap,tagUser)){ // 셀프태그인지 체크 - checkSelfTag(snap,tagUserloginId); + checkSelfTag(snap,tagUserEmail); alarmAddService.createSnapAlarm(snap.getUser(), tagUser, snap, AlarmType.SNAPTAG); return SnapTag.builder() @@ -118,9 +118,9 @@ private List findNewTagUsers(List tagUserLoginIds, Snap snap){ }).filter(Objects::nonNull).collect(Collectors.toList()); } - private void checkSelfTag(Snap snap, String tagUserLoginId){ + private void checkSelfTag(Snap snap, String tagUserEmail){ - if(snap.getUser().getLoginId().equals(tagUserLoginId)) + if(snap.getUser().getEmail().equals(tagUserEmail)) throw new CustomException(ExceptionCode.CAN_NOT_SELF_TAG); } } diff --git a/src/main/java/me/snaptime/user/controller/UserController.java b/src/main/java/me/snaptime/user/controller/UserController.java index 195541fd..a5fd43c2 100644 --- a/src/main/java/me/snaptime/user/controller/UserController.java +++ b/src/main/java/me/snaptime/user/controller/UserController.java @@ -87,7 +87,7 @@ public ResponseEntity> changeUser(@AuthenticationPrincip public ResponseEntity> deleteUser(@AuthenticationPrincipal UserDetails userDetails, @RequestParam("password") @NotBlank(message = "패스워드 입력은 필수입니다.") String password){ - userService.deleteUser(password, userDetails.getUsername()); + userService.deleteUser(userDetails.getUsername(), password); return ResponseEntity.status(HttpStatus.OK).body( new CommonResponseDto<>( "유저 삭제가 성공적으로 완료되었습니다.", diff --git a/src/main/java/me/snaptime/user/domain/User.java b/src/main/java/me/snaptime/user/domain/User.java index e201941d..cb4e4253 100644 --- a/src/main/java/me/snaptime/user/domain/User.java +++ b/src/main/java/me/snaptime/user/domain/User.java @@ -32,20 +32,17 @@ public class User extends BaseTimeEntity implements UserDetails{ @Column(name = "user_name",nullable = false) private String name; - @Column(name = "user_loginId",nullable = false, unique = true) - private String loginId; + @Column(name = "user_nick_name") + private String nickName; + + @Column(name = "user_email",nullable = false, unique = true) + private String email; //메서드의 프로퍼티를 JSON 직렬화에서 제외하도록 지정합니다. @JsonProperty(access = JsonProperty.Access.WRITE_ONLY) @Column(name = "user_password",nullable = false) private String password; - @Column(name = "user_email",nullable = false) - private String email; - - @Column(name = "user_birthDay",nullable = false) - private String birthDay; - @OneToOne(fetch = FetchType.EAGER, cascade = CascadeType.ALL) @JoinColumn(name = "profile_photo_id") private ProfilePhoto profilePhoto; @@ -57,20 +54,18 @@ public class User extends BaseTimeEntity implements UserDetails{ private List roles = new ArrayList<>(); @Builder - protected User(String name,String loginId,String password, String email, String birthDay, List roles, ProfilePhoto profilePhoto){ + protected User(String name,String nickName, String email, String password, List roles, ProfilePhoto profilePhoto){ this.name = name; - this.loginId = loginId; - this.password =password; + this.nickName = nickName; this.email = email; - this.birthDay = birthDay; + this.password = password; this.roles = roles; this.profilePhoto = profilePhoto; } public void updateUserName(String name) { this.name = name;} - public void updateUserLoginId(String loginId) { this.loginId = loginId;} + public void updateNickName(String nickName){this.nickName = nickName;} public void updateUserEmail(String email) { this.email = email;} - public void updateUserBirthDay(String birthDay) { this.birthDay = birthDay;} public void updateUserPassword(String password){this.password = password;} @@ -87,7 +82,7 @@ public Collection getAuthorities() { //일반적으로 외부에 노출되어도 되는 정보이기 때문에 JsonProperty.Access.WRITE_ONLY 가 필요하지 않다. @Override public String getUsername() { - return this.loginId; + return this.email; } //사용자 계정의 만료 여부 diff --git a/src/main/java/me/snaptime/user/dto/req/SignInReqDto.java b/src/main/java/me/snaptime/user/dto/req/SignInReqDto.java index fb12d942..b5c99e72 100644 --- a/src/main/java/me/snaptime/user/dto/req/SignInReqDto.java +++ b/src/main/java/me/snaptime/user/dto/req/SignInReqDto.java @@ -7,12 +7,12 @@ @Builder public record SignInReqDto( - @NotBlank(message = "유저 loginId 입력은 필수입니다.") + @NotBlank(message = "유저 email 입력은 필수입니다.") @Schema( - example = "kang4746", - description = "유저의 loginId를 입력해주세요" + example = "kang4746@gmail.com", + description = "유저의 email를 입력해주세요" ) - String loginId, + String email, @NotBlank(message = "유저 password 입력은 필수입니다.") @Schema( diff --git a/src/main/java/me/snaptime/user/dto/req/UserReqDto.java b/src/main/java/me/snaptime/user/dto/req/UserReqDto.java index 4446b331..27f6cf90 100644 --- a/src/main/java/me/snaptime/user/dto/req/UserReqDto.java +++ b/src/main/java/me/snaptime/user/dto/req/UserReqDto.java @@ -13,27 +13,20 @@ public record UserReqDto( @NotBlank(message = "유저 이름 입력은 필수입니다.") String name, @Schema( - example = "kang4746", - description = "유저의 로그인 아이디를 입력해주세요" - ) - @NotBlank(message = "유저 로그인 아이디 입력은 필수입니다.") - String loginId, - @Schema( - example = "password", - description = "유저의 비밀번호를 입력해주세요" - ) - @NotBlank(message = "유저 비밀번호 입력은 필수입니다.") - String password, - @Schema( - example = "strong@gmail.com", + example = "kang4746@gmail.com", description = "유저의 이메일을 입력해주세요" ) @NotBlank(message = "유저 이메일 입력은 필수입니다.") String email, @Schema( - example = "1999-10-29", - description = "유저의 생년월일을 입력해주세요" + example = "password", + description = "유저의 비밀번호를 입력해주세요" ) - @NotBlank(message = "유저 생년월일 입력은 필수입니다.") - String birthDay -){} + @NotBlank(message = "유저 비밀번호 입력은 필수입니다.") + String password +){ + static public String makeNickName(String email){ + String[]emailParts = email.split("@"); + return emailParts[0] + emailParts[1].charAt(0); + } +} diff --git a/src/main/java/me/snaptime/user/dto/req/UserUpdateReqDto.java b/src/main/java/me/snaptime/user/dto/req/UserUpdateReqDto.java index 74d302a6..8ad22fb9 100644 --- a/src/main/java/me/snaptime/user/dto/req/UserUpdateReqDto.java +++ b/src/main/java/me/snaptime/user/dto/req/UserUpdateReqDto.java @@ -11,14 +11,9 @@ public record UserUpdateReqDto( ) String name, @Schema( - example = "strong@gmail.com", - description = "유저의 이메일을 입력해주세요" + example = "kang@gmail.com", + description = "유저의 닉네임을 입력해주세요" ) - String email, - @Schema( - example = "1999-10-29", - description = "유저의 생년월일을 입력해주세요" - ) - String birthDay + String nickName ){} diff --git a/src/main/java/me/snaptime/user/dto/res/UserFindByNameResDto.java b/src/main/java/me/snaptime/user/dto/res/UserFindByNameResDto.java index 54112c9b..243e3032 100644 --- a/src/main/java/me/snaptime/user/dto/res/UserFindByNameResDto.java +++ b/src/main/java/me/snaptime/user/dto/res/UserFindByNameResDto.java @@ -8,15 +8,17 @@ @Builder public record UserFindByNameResDto ( - String foundLoginId, + String foundEmail, String profilePhotoURL, - String foundUserName + String foundUserName, + String foundNickName ){ public static UserFindByNameResDto toDto(Tuple tuple, String profilePhotoURL){ return UserFindByNameResDto.builder() - .foundLoginId(tuple.get(user.loginId)) + .foundEmail(tuple.get(user.email)) .profilePhotoURL(profilePhotoURL) .foundUserName(tuple.get(user.name)) + .foundNickName(tuple.get(user.nickName)) .build(); } } diff --git a/src/main/java/me/snaptime/user/dto/res/UserFindResDto.java b/src/main/java/me/snaptime/user/dto/res/UserFindResDto.java index 515e9594..36656aad 100644 --- a/src/main/java/me/snaptime/user/dto/res/UserFindResDto.java +++ b/src/main/java/me/snaptime/user/dto/res/UserFindResDto.java @@ -8,17 +8,15 @@ public record UserFindResDto( Long userId, String name, - String loginId, String email, - String birthDay + String nickName ){ public static UserFindResDto toDto(User user){ return UserFindResDto.builder() .userId(user.getUserId()) .name(user.getName()) - .loginId(user.getLoginId()) .email(user.getEmail()) - .birthDay(user.getBirthDay()) + .nickName(user.getNickName()) .build(); } diff --git a/src/main/java/me/snaptime/user/repository/UserRepository.java b/src/main/java/me/snaptime/user/repository/UserRepository.java index 8ddf2d38..765af907 100644 --- a/src/main/java/me/snaptime/user/repository/UserRepository.java +++ b/src/main/java/me/snaptime/user/repository/UserRepository.java @@ -8,5 +8,6 @@ @Repository public interface UserRepository extends JpaRepository, UserPagingRepository{ - Optional findByLoginId(String loginId); + Optional findByEmail(String email); + Boolean existsByEmail(String email); } diff --git a/src/main/java/me/snaptime/user/repository/impl/UserPagingRepositoryImpl.java b/src/main/java/me/snaptime/user/repository/impl/UserPagingRepositoryImpl.java index 77cba21a..f51acf36 100644 --- a/src/main/java/me/snaptime/user/repository/impl/UserPagingRepositoryImpl.java +++ b/src/main/java/me/snaptime/user/repository/impl/UserPagingRepositoryImpl.java @@ -27,10 +27,10 @@ public List findUserPageByName(String searchKeyword, Long pageNum){ Pageable pageable= PageRequest.of((int) (pageNum-1),20); List tuples = jpaQueryFactory.select( - user.loginId, user.profilePhoto.profilePhotoId, user.name + user.email, user.profilePhoto.profilePhotoId, user.name,user.nickName ) .from(user) - .where(user.name.startsWith(searchKeyword).or(user.loginId.startsWith(searchKeyword))) + .where(user.name.startsWith(searchKeyword).or(user.email.startsWith(searchKeyword).or(user.nickName.startsWith(searchKeyword)))) .orderBy(new OrderSpecifier(Order.ASC, user.userId)) .offset(pageable.getOffset()) .limit(pageable.getPageSize()+1) //페이지의 크기 diff --git a/src/main/java/me/snaptime/user/service/UserService.java b/src/main/java/me/snaptime/user/service/UserService.java index b4fb6e26..0362f8d4 100644 --- a/src/main/java/me/snaptime/user/service/UserService.java +++ b/src/main/java/me/snaptime/user/service/UserService.java @@ -5,9 +5,9 @@ import me.snaptime.user.dto.res.UserPagingResDto; public interface UserService { - UserFindResDto getUser(String loginId); + UserFindResDto getUser(String email); UserPagingResDto findUserPageByName(String searchKeyword, Long pageNum); - UserFindResDto updateUser(String loginId, UserUpdateReqDto userUpdateReqDto); - void deleteUser(String password, String loginId); - void updatePassword(String loginId, String password); + UserFindResDto updateUser(String email, UserUpdateReqDto userUpdateReqDto); + void deleteUser(String email, String password); + void updatePassword(String email, String password); } diff --git a/src/main/java/me/snaptime/user/service/impl/SignServiceImpl.java b/src/main/java/me/snaptime/user/service/impl/SignServiceImpl.java index 8f01c487..0d95905c 100644 --- a/src/main/java/me/snaptime/user/service/impl/SignServiceImpl.java +++ b/src/main/java/me/snaptime/user/service/impl/SignServiceImpl.java @@ -42,7 +42,7 @@ public class SignServiceImpl implements SignService { public UserFindResDto signUp(UserReqDto userReqDto) { //로그인 id가 이미 존재하는지 확인 - if(userRepository.findByLoginId(userReqDto.loginId()).isPresent()){ + if(userRepository.findByEmail(userReqDto.email()).isPresent()){ throw new CustomException(ExceptionCode.LOGIN_ID_ALREADY_EXIST); } @@ -59,10 +59,9 @@ public UserFindResDto signUp(UserReqDto userReqDto) { //새로운 사용자 객체 생성 User user = User.builder() .name(userReqDto.name()) - .loginId(userReqDto.loginId()) .password(passwordEncoder.encode(userReqDto.password())) .email(userReqDto.email()) - .birthDay(userReqDto.birthDay()) + .nickName(UserReqDto.makeNickName(userReqDto.email())) //단일 권한을 가진 리스트 생성, 하나의 요소를 가진 불변의 리스트 생성 .roles(Collections.singletonList("ROLE_USER")) .profilePhoto(profilePhoto) @@ -77,13 +76,13 @@ public UserFindResDto signUp(UserReqDto userReqDto) { @Override @Transactional(readOnly = true) public SignInResDto signIn(SignInReqDto signInReqDto) { - User user = userRepository.findByLoginId(signInReqDto.loginId()).orElseThrow(() -> new CustomException(ExceptionCode.USER_NOT_EXIST)); + User user = userRepository.findByEmail(signInReqDto.email()).orElseThrow(() -> new CustomException(ExceptionCode.USER_NOT_EXIST)); if (!passwordEncoder.matches(signInReqDto.password(), user.getPassword())) { throw new CustomException(ExceptionCode.PASSWORD_NOT_EQUAL); } - String accessToken = jwtProvider.createAccessToken(user.getUserId(), user.getLoginId(), user.getRoles()); - String refreshToken = jwtProvider.createRefreshToken(user.getUserId(), user.getLoginId(),user.getRoles()); + String accessToken = jwtProvider.createAccessToken(user.getUserId(), user.getEmail(), user.getRoles()); + String refreshToken = jwtProvider.createRefreshToken(user.getUserId(), user.getEmail(),user.getRoles()); refreshTokenRepository.save(new RefreshToken(user.getUserId(),refreshToken)); return SignInResDto.builder() @@ -105,8 +104,8 @@ public SignInResDto reissueAccessToken(HttpServletRequest request){ User user = userRepository.findById(userId).orElseThrow(()-> new CustomException(ExceptionCode.USER_NOT_EXIST)); - String newAccessToken = jwtProvider.createAccessToken(userId,user.getLoginId(),user.getRoles()); - String newRefreshToken = jwtProvider.createRefreshToken(userId,user.getLoginId(),user.getRoles()); + String newAccessToken = jwtProvider.createAccessToken(userId,user.getEmail(), user.getRoles()); + String newRefreshToken = jwtProvider.createRefreshToken(userId,user.getEmail(), user.getRoles()); SignInResDto signInResDto = SignInResDto.builder() .accessToken(newAccessToken) @@ -121,13 +120,13 @@ public SignInResDto reissueAccessToken(HttpServletRequest request){ @Override @Transactional(readOnly = true) public TestSignInResDto testSignIn(SignInReqDto signInReqDto) { - User testUser = userRepository.findByLoginId(signInReqDto.loginId()).orElseThrow(() -> new CustomException(ExceptionCode.USER_NOT_EXIST)); + User testUser = userRepository.findByEmail(signInReqDto.email()).orElseThrow(() -> new CustomException(ExceptionCode.USER_NOT_EXIST)); if (!passwordEncoder.matches(signInReqDto.password(), testUser.getPassword())) { throw new CustomException(ExceptionCode.PASSWORD_NOT_EQUAL); } - String testAccessToken = jwtProvider.testCreateAccessToken(testUser.getUserId(), testUser.getLoginId(), testUser.getRoles()); - String testRefreshToken = jwtProvider.testCreateRefreshToken(testUser.getUserId(), testUser.getLoginId(),testUser.getRoles()); + String testAccessToken = jwtProvider.testCreateAccessToken(testUser.getUserId(), testUser.getEmail(), testUser.getRoles()); + String testRefreshToken = jwtProvider.testCreateRefreshToken(testUser.getUserId(), testUser.getEmail(),testUser.getRoles()); refreshTokenRepository.save(new RefreshToken(testUser.getUserId(),testRefreshToken)); return TestSignInResDto.builder() diff --git a/src/main/java/me/snaptime/user/service/impl/UserServiceImpl.java b/src/main/java/me/snaptime/user/service/impl/UserServiceImpl.java index 1b4b6331..bdfd3cc0 100644 --- a/src/main/java/me/snaptime/user/service/impl/UserServiceImpl.java +++ b/src/main/java/me/snaptime/user/service/impl/UserServiceImpl.java @@ -36,20 +36,16 @@ public class UserServiceImpl implements UserService { private final UrlComponent urlComponent; @Transactional(readOnly = true) - public UserFindResDto getUser(String loginId) { - User user = userRepository.findByLoginId(loginId).orElseThrow(() -> new CustomException(ExceptionCode.USER_NOT_EXIST)); - + public UserFindResDto getUser(String email) { + User user = userRepository.findByEmail(email).orElseThrow(() -> new CustomException(ExceptionCode.USER_NOT_EXIST)); return UserFindResDto.toDto(user); } @Override public UserPagingResDto findUserPageByName(String searchKeyword, Long pageNum){ - List tuples = userRepository.findUserPageByName(searchKeyword,pageNum); - // 다음 페이지 유무 체크 boolean hasNextPage = NextPageChecker.hasNextPage(tuples,20L); - List userFindByNameResDtos = tuples.stream().map(tuple -> { String profilePhotoURL = urlComponent.makeProfileURL(tuple.get(user.profilePhoto.profilePhotoId)); @@ -59,35 +55,28 @@ public UserPagingResDto findUserPageByName(String searchKeyword, Long pageNum){ return UserPagingResDto.toDto(userFindByNameResDtos, hasNextPage); } - public UserFindResDto updateUser(String loginId, UserUpdateReqDto userUpdateReqDto) { - - User user = userRepository.findByLoginId(loginId).orElseThrow(() -> new CustomException(ExceptionCode.USER_NOT_EXIST)); - + public UserFindResDto updateUser(String email, UserUpdateReqDto userUpdateReqDto) { + User user = userRepository.findByEmail(email).orElseThrow(() -> new CustomException(ExceptionCode.USER_NOT_EXIST)); if (userUpdateReqDto.name() != null && !userUpdateReqDto.name().isEmpty()) { user.updateUserName(userUpdateReqDto.name()); } - - if (userUpdateReqDto.email() != null && !userUpdateReqDto.email().isEmpty()) { - user.updateUserEmail(userUpdateReqDto.email()); - } - - if (userUpdateReqDto.birthDay() != null && !userUpdateReqDto.birthDay().isEmpty()) { - user.updateUserBirthDay(userUpdateReqDto.birthDay()); + if(userUpdateReqDto.nickName() != null && !userUpdateReqDto.nickName().isEmpty()){ + user.updateNickName(userUpdateReqDto.nickName()); } return UserFindResDto.toDto(user); } - public void deleteUser(String password, String loginId) { + public void deleteUser(String email, String password) { - User user = userRepository.findByLoginId(loginId).orElseThrow(() -> new CustomException(ExceptionCode.USER_NOT_EXIST)); + User user = userRepository.findByEmail(email).orElseThrow(() -> new CustomException(ExceptionCode.USER_NOT_EXIST)); if (!passwordEncoder.matches(password, user.getPassword())) { throw new CustomException(ExceptionCode.PASSWORD_NOT_EQUAL); } userRepository.deleteById(user.getUserId()); } - public void updatePassword(String loginId, String password){ - User user = userRepository.findByLoginId(loginId).orElseThrow(()-> new CustomException(ExceptionCode.USER_NOT_EXIST)); + public void updatePassword(String email, String password){ + User user = userRepository.findByEmail(email).orElseThrow(()-> new CustomException(ExceptionCode.USER_NOT_EXIST)); if (!passwordEncoder.matches(password, user.getPassword())) { user.updateUserPassword(passwordEncoder.encode(password)); diff --git a/src/main/java/me/snaptime/util/FileNameGenerator.java b/src/main/java/me/snaptime/util/FileNameGenerator.java index b7028d53..a26e2056 100644 --- a/src/main/java/me/snaptime/util/FileNameGenerator.java +++ b/src/main/java/me/snaptime/util/FileNameGenerator.java @@ -6,7 +6,6 @@ public class FileNameGenerator { - public static String generatorName(String fileName) { String currentTime = LocalDateTime.now().format(DateTimeFormatter.ofPattern("MMddHHmmssSSS")); Random rd = new Random(); diff --git a/src/test/java/me/snaptime/snap/controller/PhotoControllerTest.java b/src/test/java/me/snaptime/snap/controller/PhotoControllerTest.java index 3a136929..9842b563 100644 --- a/src/test/java/me/snaptime/snap/controller/PhotoControllerTest.java +++ b/src/test/java/me/snaptime/snap/controller/PhotoControllerTest.java @@ -36,16 +36,15 @@ public class PhotoControllerTest { @DisplayName("Photo 조회 테스트") - @WithMockUser(username = "mockUid",password = "test1234",roles = "USER") + @WithMockUser(username = "kang@gmail.com",password = "test1234",roles = "USER") @Test public void findPhotoTest() throws Exception { // given signService.signUp(new UserReqDto( - "김원정", "mockUid", "test1234", "test@test.com", "990303" - )); + "김원정", "kang@gmail.com", "test1234")); byte[] emptyByte = {}; - given(snapService.downloadPhotoFromFileSystem("image.png", "mockUid", true)).willReturn(emptyByte); + given(snapService.downloadPhotoFromFileSystem("image.png", "kang@gmail.com", true)).willReturn(emptyByte); // when mockMvc.perform( get("/photo?fileName=image.png&isEncrypted=true")) diff --git a/src/test/java/me/snaptime/snap/repository/SnapPagingRepositoryImplTest.java b/src/test/java/me/snaptime/snap/repository/SnapPagingRepositoryImplTest.java index 0e8557db..8ded6a2a 100644 --- a/src/test/java/me/snaptime/snap/repository/SnapPagingRepositoryImplTest.java +++ b/src/test/java/me/snaptime/snap/repository/SnapPagingRepositoryImplTest.java @@ -74,34 +74,30 @@ void init(){ reqUser = User.builder() .email("test1@google.com") - .loginId("testLoginId1") - .name("testName1") .password("1234") - .birthDay(String.valueOf(LocalDateTime.now())) + .name("testName1") + .nickName("test1g") .profilePhoto(profilePhoto1) .build(); User user2 = User.builder() .email("test2@google.com") - .loginId("testLoginId2") - .name("testName2") .password("1234") - .birthDay(String.valueOf(LocalDateTime.now())) + .name("testName2") + .nickName("test2g") .profilePhoto(profilePhoto2) .build(); User user3 = User.builder() .email("test3@google.com") - .loginId("testLoginId3") - .name("testName3") .password("1234") - .birthDay(String.valueOf(LocalDateTime.now())) + .name("testName3") + .nickName("test3g") .profilePhoto(profilePhoto3) .build(); User user4 = User.builder() .email("test4@google.com") - .loginId("testLoginId4") - .name("testName4") .password("1234") - .birthDay(String.valueOf(LocalDateTime.now())) + .name("testName4") + .nickName("test4g") .profilePhoto(profilePhoto4) .build(); diff --git a/src/test/java/me/snaptime/snap/service/SnapPagingServiceImplTest.java b/src/test/java/me/snaptime/snap/service/SnapPagingServiceImplTest.java index 3c27d88c..aa0f7987 100644 --- a/src/test/java/me/snaptime/snap/service/SnapPagingServiceImplTest.java +++ b/src/test/java/me/snaptime/snap/service/SnapPagingServiceImplTest.java @@ -80,11 +80,11 @@ public void findSnapPagingTest1(){ given(tuple1.get(snap.fileName)).willReturn("fileName1"); given(tuple2.get(snap.fileName)).willReturn("fileName2"); given(tuple3.get(snap.fileName)).willReturn("fileName3"); - given(userRepository.findByLoginId(any(String.class))).willReturn(Optional.ofNullable(reqUser)); + given(userRepository.findByEmail(any(String.class))).willReturn(Optional.ofNullable(reqUser)); given(snapRepository.findSnapPage(any(Long.class),any(User.class))).willReturn(List.of(tuple1,tuple2,tuple3)); // when - SnapPagingResDto snapPagingResDto = snapPagingServiceImpl.findSnapPage("testLoginId",1L); + SnapPagingResDto snapPagingResDto = snapPagingServiceImpl.findSnapPage("testEmail",1L); // then assertThat(snapPagingResDto.snapDetailInfoResDtos().size()).isEqualTo(3); @@ -101,7 +101,7 @@ public void findSnapPagingTest1(){ assertThat(snapPagingResDto.snapDetailInfoResDtos().get(2).snapPhotoURL()).isEqualTo("photoURL3"); verify(snapRepository,times(1)).findSnapPage(any(Long.class),any(User.class)); - verify(userRepository,times(1)).findByLoginId(any(String.class)); + verify(userRepository,times(1)).findByEmail(any(String.class)); } diff --git a/src/test/java/me/snaptime/social/controller/FriendControllerTest.java b/src/test/java/me/snaptime/social/controller/FriendControllerTest.java index f3ce299e..41150b86 100644 --- a/src/test/java/me/snaptime/social/controller/FriendControllerTest.java +++ b/src/test/java/me/snaptime/social/controller/FriendControllerTest.java @@ -52,7 +52,7 @@ public void sendFollowReq1() throws Exception { //when, then this.mockMvc.perform(post("/friends") .contentType(MediaType.APPLICATION_JSON) - .param("receiverLoginId","followName")) + .param("receiverEmail","followName")) .andExpect(status().isCreated()) .andExpect(jsonPath("$.msg").value("팔로우가 완료되었습니다.")) .andDo(print()); @@ -70,7 +70,7 @@ public void sendFollowReq2() throws Exception { //when, then this.mockMvc.perform(post("/friends") .contentType(MediaType.APPLICATION_JSON) - .param("receiverLoginId","followName")) + .param("receiverEmail","followName")) .andExpect(status().isBadRequest()) .andExpect(jsonPath("$.msg").value("사용자가 존재하지 않습니다.")) .andDo(print()); @@ -88,7 +88,7 @@ public void sendFollowReq3() throws Exception { //when, then this.mockMvc.perform(post("/friends") .contentType(MediaType.APPLICATION_JSON) - .param("receiverLoginId","followName")) + .param("receiverEmail","followName")) .andExpect(status().isBadRequest()) .andExpect(jsonPath("$.msg").value("이미 팔로우관계입니다.")) .andDo(print()); @@ -106,7 +106,7 @@ public void sendFollowReq4() throws Exception { //when, then this.mockMvc.perform(post("/friends") .contentType(MediaType.APPLICATION_JSON) - .param("receiverLoginId","followName")) + .param("receiverEmail","followName")) .andExpect(status().isBadRequest()) .andExpect(jsonPath("$.msg").value("팔로우요청이 거절되었습니다.")) .andDo(print()); @@ -124,7 +124,7 @@ public void sendFollowReq5() throws Exception { //when, then this.mockMvc.perform(post("/friends") .contentType(MediaType.APPLICATION_JSON) - .param("receiverLoginId","followName")) + .param("receiverEmail","followName")) .andExpect(status().isBadRequest()) .andExpect(jsonPath("$.msg").value("자신에게 친구추가 요청을 보낼 수 없습니다.")) .andDo(print()); @@ -141,7 +141,7 @@ public void sendFollowReq6() throws Exception { //when, then this.mockMvc.perform(post("/friends") .contentType(MediaType.APPLICATION_JSON) - .param("receiverLoginId","")) + .param("receiverEmail","")) .andExpect(status().isBadRequest()) .andExpect(jsonPath("$.msg").value("팔로우요청을 보낼 유저의 이름을 입력해주세요.")) .andDo(print()); @@ -158,7 +158,7 @@ public void deleteFollowTest1() throws Exception { //when, then this.mockMvc.perform(delete("/friends") .contentType(MediaType.APPLICATION_JSON) - .param("deletedUserLoginId","testLoginId")) + .param("deletedUserEmail","testEmail")) .andExpect(status().isOk()) .andExpect(jsonPath("$.msg").value("팔로우삭제가 완료되었습니다.")) .andDo(print()); @@ -175,9 +175,9 @@ public void deleteFollowTest2() throws Exception { //when, then this.mockMvc.perform(delete("/friends") .contentType(MediaType.APPLICATION_JSON) - .param("deletedUserLoginId","")) + .param("deletedUserEmail","")) .andExpect(status().isBadRequest()) - .andExpect(jsonPath("$.msg").value("언팔로우할 유저의 loginId를 입력해주세요.")) + .andExpect(jsonPath("$.msg").value("언팔로우할 유저의 email을 입력해주세요.")) .andDo(print()); verify(friendService,times(0)).unFollow(any(String.class),any(String.class)); @@ -194,7 +194,7 @@ public void deleteFollowTest3() throws Exception { //when, then this.mockMvc.perform(delete("/friends") .contentType(MediaType.APPLICATION_JSON) - .param("deletedUserLoginId","testLoginId")) + .param("deletedUserEmail","testEmail")) .andExpect(status().isBadRequest()) .andExpect(jsonPath("$.msg").value("존재하지 않는 친구입니다.")) .andDo(print()); @@ -213,7 +213,7 @@ public void deleteFollowTest4() throws Exception { //when, then this.mockMvc.perform(delete("/friends") .contentType(MediaType.APPLICATION_JSON) - .param("deletedUserLoginId","testLoginId")) + .param("deletedUserEmail","testEmail")) .andExpect(status().isForbidden()) .andExpect(jsonPath("$.msg").value("해당 친구에 대한 권한이 없습니다.")) .andDo(print()); @@ -230,7 +230,7 @@ public void findFriendListTest1() throws Exception { //when, then this.mockMvc.perform(get("/friends/{pageNum}",1L) .param("friendSearchType","FOLLOWING") - .param("targetLoginId","tempLoginId") + .param("targetEmail","tempEmail") .contentType(MediaType.APPLICATION_JSON)) .andExpect(status().isOk()) .andExpect(jsonPath("$.msg").value("친구조회가 완료되었습니다.")) @@ -249,7 +249,7 @@ public void findFriendListTest2() throws Exception { //when, then this.mockMvc.perform(get("/friends/{pageNum}",1L) .param("friendSearchType","FOLLOWER") - .param("targetLoginId","tempLoginId") + .param("targetEmail","tempEmail") .contentType(MediaType.APPLICATION_JSON)) .andExpect(status().isOk()) .andExpect(jsonPath("$.msg").value("친구조회가 완료되었습니다.")) @@ -268,7 +268,7 @@ public void findFriendListTest3() throws Exception { //when, then this.mockMvc.perform(get("/friends/{pageNum}",1L) .param("friendSearchType","FOLLOWING") - .param("targetLoginId","tempLoginId") + .param("targetEmail","tempEmail") .param("searchKeyword","박") .contentType(MediaType.APPLICATION_JSON)) .andExpect(status().isOk()) @@ -288,7 +288,7 @@ public void findFriendListTest4() throws Exception { //when, then this.mockMvc.perform(get("/friends/{pageNum}",1L) .param("friendSearchType","TEST") - .param("targetLoginId","tempLoginId") + .param("targetEmail","tempEmail") .param("searchKeyword","박") .contentType(MediaType.APPLICATION_JSON)) .andExpect(status().isBadRequest()) @@ -308,7 +308,7 @@ public void findFriendListTest5() throws Exception { //when, then this.mockMvc.perform(get("/friends/{pageNum}","test") .param("friendSearchType","FOLLOWER") - .param("targetLoginId","tempLoginId") + .param("targetEmail","tempEmail") .param("searchKeyword","박") .contentType(MediaType.APPLICATION_JSON)) .andExpect(status().isBadRequest()) @@ -328,7 +328,7 @@ public void findFriendListTest6() throws Exception { //when, then this.mockMvc.perform(get("/friends/{pageNum}",1L) .param("friendSearchType","") - .param("targetLoginId","tempLoginId") + .param("targetEmail","tempEmail") .param("searchKeyword","박") .contentType(MediaType.APPLICATION_JSON)) .andExpect(status().isBadRequest()) @@ -351,7 +351,7 @@ public void findFriendListTest7() throws Exception { //when, then this.mockMvc.perform(get("/friends/{pageNum}",1L) .param("friendSearchType","FOLLOWER") - .param("targetLoginId","tempLoginId") + .param("targetEmail","tempEmail") .param("searchKeyword","박") .contentType(MediaType.APPLICATION_JSON)) .andExpect(status().isBadRequest()) diff --git a/src/test/java/me/snaptime/social/repository/FriendPagingRepositoryTest.java b/src/test/java/me/snaptime/social/repository/FriendPagingRepositoryTest.java index e4c2529a..9eecb154 100644 --- a/src/test/java/me/snaptime/social/repository/FriendPagingRepositoryTest.java +++ b/src/test/java/me/snaptime/social/repository/FriendPagingRepositoryTest.java @@ -49,11 +49,10 @@ void init(){ .build(); reqUser = User.builder() .email("test@google.com") - .loginId("testLoginId") + .nickName("testg") .name("testName") .password("1234") .profilePhoto(reqProfilePhoto) - .birthDay(String.valueOf(LocalDateTime.now())) .build(); userRepository.save(reqUser); for(int i=0;i<5;i++){ @@ -120,11 +119,10 @@ private void createFriend(User reqUser, Long i){ User user = User.builder() .email("test"+i+"@google.com") - .loginId("test"+i+"LoginId") + .nickName("test"+i+"g") .name("testName"+i) .password("1234") .profilePhoto(profilePhoto) - .birthDay(String.valueOf(LocalDateTime.now())) .build(); userRepository.save(user); friendRepository.save( diff --git a/src/test/java/me/snaptime/social/service/FriendServiceImplTest.java b/src/test/java/me/snaptime/social/service/FriendServiceImplTest.java index 2920c16f..a4fdadd3 100644 --- a/src/test/java/me/snaptime/social/service/FriendServiceImplTest.java +++ b/src/test/java/me/snaptime/social/service/FriendServiceImplTest.java @@ -70,17 +70,17 @@ public void sendFriendReqTest1(){ given(sender.getUserId()).willReturn(1L); given(receiver.getUserId()).willReturn(2L); - given(userRepository.findByLoginId(any(String.class))) + given(userRepository.findByEmail(any(String.class))) .willReturn(Optional.of(sender)) .willReturn(Optional.ofNullable(receiver)); given(friendRepository.findBySenderAndReceiver(any(User.class),any(User.class))).willReturn(Optional.empty()); //when - friendServiceImpl.sendFollow("senderLoginId","testName"); + friendServiceImpl.sendFollow("senderEmail","testName"); //then - verify(userRepository,times(2)).findByLoginId(any(String.class)); + verify(userRepository,times(2)).findByEmail(any(String.class)); verify(friendRepository,times(1)).findBySenderAndReceiver(any(User.class),any(User.class)); verify(friendRepository,times(1)).save(any(Friend.class)); } @@ -90,18 +90,18 @@ public void sendFriendReqTest1(){ public void sendFriendReqTest2(){ //given User sender = spy(user1); - given(userRepository.findByLoginId(any(String.class))) + given(userRepository.findByEmail(any(String.class))) .willReturn(Optional.ofNullable(sender)) .willReturn(Optional.empty()); //when try{ - friendServiceImpl.sendFollow("senderLoginId","testName"); + friendServiceImpl.sendFollow("senderEmail","testName"); fail("예외가 발생하지 않음"); }catch (CustomException ex){ //then assertThat(ex.getExceptionCode()).isEqualTo(ExceptionCode.USER_NOT_EXIST); - verify(userRepository,times(2)).findByLoginId(any(String.class)); + verify(userRepository,times(2)).findByEmail(any(String.class)); verify(friendRepository,times(0)).findBySenderAndReceiver(any(User.class),any(User.class)); verify(friendRepository,times(0)).save(any(Friend.class)); } @@ -115,7 +115,7 @@ public void sendFriendReqTest3(){ User receiver = spy(user1); Friend friend = spy(this.friend); - given(userRepository.findByLoginId(any(String.class))) + given(userRepository.findByEmail(any(String.class))) .willReturn(Optional.ofNullable(sender)) .willReturn(Optional.of(receiver)); @@ -123,12 +123,12 @@ public void sendFriendReqTest3(){ //when try{ - friendServiceImpl.sendFollow("senderLoginId","testName"); + friendServiceImpl.sendFollow("senderEmail","testName"); fail("예외가 발생하지 않음"); }catch (CustomException ex){ //then assertThat(ex.getExceptionCode()).isEqualTo(ExceptionCode.ALREADY_FOLLOW); - verify(userRepository,times(2)).findByLoginId(any(String.class)); + verify(userRepository,times(2)).findByEmail(any(String.class)); verify(friendRepository,times(1)).findBySenderAndReceiver(any(User.class),any(User.class)); verify(friendRepository,times(0)).save(any(Friend.class)); } @@ -144,7 +144,7 @@ public void sendFriendReqTest5(){ given(sender.getUserId()).willReturn(1L); given(receiver.getUserId()).willReturn(1L); - given(userRepository.findByLoginId(any(String.class))) + given(userRepository.findByEmail(any(String.class))) .willReturn(Optional.of(sender)) .willReturn(Optional.of(receiver)); @@ -152,12 +152,12 @@ public void sendFriendReqTest5(){ //when try{ - friendServiceImpl.sendFollow("senderLoginId","testName"); + friendServiceImpl.sendFollow("senderEmail","testName"); fail("예외가 발생하지 않음"); }catch (CustomException ex){ //then assertThat(ex.getExceptionCode()).isEqualTo(ExceptionCode.SELF_FRIEND_REQ); - verify(userRepository,times(2)).findByLoginId(any(String.class)); + verify(userRepository,times(2)).findByEmail(any(String.class)); verify(friendRepository,times(1)).findBySenderAndReceiver(any(User.class),any(User.class)); verify(friendRepository,times(0)).save(any(Friend.class)); } @@ -220,19 +220,19 @@ public void deleteFollowTest1(){ //given User deletor = spy(user1); User deletedUser = spy(user1); - given(userRepository.findByLoginId(any(String.class))) + given(userRepository.findByEmail(any(String.class))) .willReturn(Optional.ofNullable(deletor)) .willReturn(Optional.of(deletedUser)); given(friendRepository.findBySenderAndReceiver(any(User.class),any(User.class))).willReturn(Optional.ofNullable(friend)); //when - friendServiceImpl.unFollow("senderLoginId","deletedUserLoginId"); + friendServiceImpl.unFollow("senderEmail","deletedUserEmail"); //then verify(friendRepository,times(1)).delete(any(Friend.class)); verify(friendRepository,times(1)).findBySenderAndReceiver(any(User.class),any(User.class)); - verify(userRepository,times(2)).findByLoginId(any(String.class)); + verify(userRepository,times(2)).findByEmail(any(String.class)); } @Test @@ -241,21 +241,21 @@ public void deleteFollowTest2(){ //given User deletor = spy(user1); User deletedUser = spy(user1); - given(userRepository.findByLoginId(any(String.class))) + given(userRepository.findByEmail(any(String.class))) .willReturn(Optional.ofNullable(deletor)) .willReturn(Optional.of(deletedUser)); given(friendRepository.findBySenderAndReceiver(any(User.class),any(User.class))).willReturn(Optional.empty()); //when try{ - friendServiceImpl.unFollow("senderLoginId","deletedUserLoginId"); + friendServiceImpl.unFollow("senderEmail","deletedUserEmail"); fail("예외가 발생하지 않음"); }catch (CustomException ex){ //then assertThat(ex.getExceptionCode()).isEqualTo(ExceptionCode.FRIEND_NOT_EXIST); verify(friendRepository,times(0)).delete(any(Friend.class)); verify(friendRepository,times(1)).findBySenderAndReceiver(any(User.class),any(User.class)); - verify(userRepository,times(2)).findByLoginId(any(String.class)); + verify(userRepository,times(2)).findByEmail(any(String.class)); } } @@ -263,12 +263,12 @@ public void deleteFollowTest2(){ @DisplayName("친구 수 조회 : 성공") public void findFriendShipCntTest1(){ // given - given(userRepository.findByLoginId(any(String.class))).willReturn(Optional.ofNullable(user1)); + given(userRepository.findByEmail(any(String.class))).willReturn(Optional.ofNullable(user1)); given(friendRepository.countBySender(any(User.class))).willReturn(2l); given(friendRepository.countByReceiver(any(User.class))).willReturn(1l); // when - FriendCntResDto friendCntResDto = friendServiceImpl.findFriendCnt("loginId"); + FriendCntResDto friendCntResDto = friendServiceImpl.findFriendCnt("email"); // then assertThat(friendCntResDto.followerCnt()).isEqualTo(1l); @@ -286,9 +286,9 @@ public void findFriendListTest1(){ .willReturn("profile1") .willReturn("profile2") .willReturn("profile3"); - given(tuple1.get(user.loginId)).willReturn("testLoginId1"); - given(tuple2.get(user.loginId)).willReturn("testLoginId2"); - given(tuple3.get(user.loginId)).willReturn("testLoginId3"); + given(tuple1.get(user.email)).willReturn("testEmail1"); + given(tuple2.get(user.email)).willReturn("testEmail2"); + given(tuple3.get(user.email)).willReturn("testEmail3"); given(tuple1.get(user.profilePhoto.profilePhotoId)).willReturn(4L); given(tuple2.get(user.profilePhoto.profilePhotoId)).willReturn(5L); @@ -298,18 +298,18 @@ public void findFriendListTest1(){ given(tuple2.get(user.name)).willReturn("name2"); given(tuple3.get(user.name)).willReturn("name3"); - given(userRepository.findByLoginId(any(String.class))).willReturn(Optional.ofNullable(user1)); + given(userRepository.findByEmail(any(String.class))).willReturn(Optional.ofNullable(user1)); given(friendRepository.findFriendPage(any(User.class),any(FriendSearchType.class),any(Long.class),any(String.class))) .willReturn(List.of(tuple1,tuple2,tuple3)); // when FriendPagingResDto result = friendServiceImpl - .findFriendPage("writerLoginId","targetLoginId",1L,FriendSearchType.FOLLOWER,"searchKeyword"); + .findFriendPage("writerEmail","targetEmail",1L,FriendSearchType.FOLLOWER,"searchKeyword"); // then - assertThat(result.friendInfoResDtos().get(0).foundLoginId()).isEqualTo("testLoginId1"); - assertThat(result.friendInfoResDtos().get(1).foundLoginId()).isEqualTo("testLoginId2"); - assertThat(result.friendInfoResDtos().get(2).foundLoginId()).isEqualTo("testLoginId3"); + assertThat(result.friendInfoResDtos().get(0).foundEmail()).isEqualTo("testEmail1"); + assertThat(result.friendInfoResDtos().get(1).foundEmail()).isEqualTo("testEmail2"); + assertThat(result.friendInfoResDtos().get(2).foundEmail()).isEqualTo("testEmail3"); assertThat(result.friendInfoResDtos().get(0).foundUserName()).isEqualTo("name1"); assertThat(result.friendInfoResDtos().get(1).foundUserName()).isEqualTo("name2"); @@ -321,7 +321,7 @@ public void findFriendListTest1(){ assertThat(result.hasNextPage()).isFalse(); - verify(userRepository,times(5)).findByLoginId(any(String.class)); + verify(userRepository,times(5)).findByEmail(any(String.class)); verify(urlComponent,times(3)).makeProfileURL(any(Long.class)); verify(friendRepository,times(1)) .findFriendPage(any(User.class),any(FriendSearchType.class),any(Long.class),any(String.class)); diff --git a/src/test/java/me/snaptime/social/service/ReplyServiceImplTest.java b/src/test/java/me/snaptime/social/service/ReplyServiceImplTest.java index ffe46173..6945b656 100644 --- a/src/test/java/me/snaptime/social/service/ReplyServiceImplTest.java +++ b/src/test/java/me/snaptime/social/service/ReplyServiceImplTest.java @@ -60,9 +60,9 @@ public class ReplyServiceImplTest { @BeforeEach void beforeEach(){ user = User.builder() - .loginId("loginId1") - .name("user1") .email("email1@google.com") + .nickName("email1g") + .name("user1") .build(); snap = Snap.builder() .build(); @@ -74,55 +74,55 @@ void beforeEach(){ @DisplayName("댓글 등록 테스트 -> 성공") public void addParentReplyTest1(){ //given - given(userRepository.findByLoginId(any(String.class))).willReturn(Optional.ofNullable(user)); + given(userRepository.findByEmail(any(String.class))).willReturn(Optional.ofNullable(user)); given(snapRepository.findById(any(Long.class))).willReturn(Optional.ofNullable(snap)); //when - replyServiceImpl.addParentReply("loginId", new ParentReplyAddReqDto("댓글내용",1L)); + replyServiceImpl.addParentReply("reqEmail", new ParentReplyAddReqDto("댓글내용",1L)); //then verify(parentReplyRepository,times(1)).save(any(ParentReply.class)); verify(snapRepository,times(1)).findById(any(Long.class)); - verify(userRepository,times(1)).findByLoginId(any(String.class)); + verify(userRepository,times(1)).findByEmail(any(String.class)); } @Test @DisplayName("댓글 등록 테스트 -> 실패(존재하지 않는 snap)") public void addParentReplyTest2(){ //given - given(userRepository.findByLoginId(any(String.class))).willReturn(Optional.ofNullable(user)); + given(userRepository.findByEmail(any(String.class))).willReturn(Optional.ofNullable(user)); given(snapRepository.findById(any(Long.class))).willReturn(Optional.empty()); //when try{ - replyServiceImpl.addParentReply("loginId",new ParentReplyAddReqDto("댓글내용",1L)); + replyServiceImpl.addParentReply("reqEmail",new ParentReplyAddReqDto("댓글내용",1L)); fail("예외가 발생하지 않음"); }catch (CustomException ex){ //then assertThat(ex.getExceptionCode()).isEqualTo(ExceptionCode.SNAP_NOT_EXIST); verify(parentReplyRepository,times(0)).save(any(ParentReply.class)); verify(snapRepository,times(1)).findById(any(Long.class)); - verify(userRepository,times(1)).findByLoginId(any(String.class)); + verify(userRepository,times(1)).findByEmail(any(String.class)); } } @Test - @DisplayName("대댓글 등록 테스트 -> 실패(태그할 유저LoginId와 연결되는 유저가 존재하지 않음)") + @DisplayName("대댓글 등록 테스트 -> 실패(태그할 유저 Email 과 연결되는 유저가 존재하지 않음)") public void addChildReplyTest2(){ //given ChildReplyAddReqDto childReplyAddReqDto = - new ChildReplyAddReqDto("댓글내용",1L,"태그유저loginId"); - given(userRepository.findByLoginId(any(String.class))).willReturn(Optional.empty()); + new ChildReplyAddReqDto("댓글내용",1L,"태그유저Email"); + given(userRepository.findByEmail(any(String.class))).willReturn(Optional.empty()); //when try{ - replyServiceImpl.addChildReply("loginId", childReplyAddReqDto); + replyServiceImpl.addChildReply("reqEmail", childReplyAddReqDto); fail("예외가 발생하지 않음"); }catch (CustomException ex){ //then assertThat(ex.getExceptionCode()).isEqualTo(ExceptionCode.USER_NOT_EXIST); verify(parentReplyRepository,times(0)).findById(any(Long.class)); - verify(userRepository,times(1)).findByLoginId(any(String.class)); + verify(userRepository,times(1)).findByEmail(any(String.class)); verify(childReplyRepository,times(0)).save(any(ChildReply.class)); } } @@ -132,19 +132,19 @@ public void addChildReplyTest2(){ public void addChildReplyTest3(){ //given ChildReplyAddReqDto childReplyAddReqDto = - new ChildReplyAddReqDto("댓글내용",1L,"태그유저loginId"); - given(userRepository.findByLoginId(any(String.class))).willReturn(Optional.ofNullable(user)); + new ChildReplyAddReqDto("댓글내용",1L,"태그유저Email"); + given(userRepository.findByEmail(any(String.class))).willReturn(Optional.ofNullable(user)); given(parentReplyRepository.findById(any(Long.class))).willReturn(Optional.empty()); //when try{ - replyServiceImpl.addChildReply("loginId", childReplyAddReqDto); + replyServiceImpl.addChildReply("reqEmail", childReplyAddReqDto); fail("예외가 발생하지 않음"); }catch (CustomException ex){ //then assertThat(ex.getExceptionCode()).isEqualTo(ExceptionCode.REPLY_NOT_FOUND); verify(parentReplyRepository,times(1)).findById(any(Long.class)); - verify(userRepository,times(1)).findByLoginId(any(String.class)); + verify(userRepository,times(1)).findByEmail(any(String.class)); verify(childReplyRepository,times(0)).save(any(ChildReply.class)); } } diff --git a/src/test/java/me/snaptime/user/controller/UserControllerTest.java b/src/test/java/me/snaptime/user/controller/UserControllerTest.java index 66e095ae..de059d68 100644 --- a/src/test/java/me/snaptime/user/controller/UserControllerTest.java +++ b/src/test/java/me/snaptime/user/controller/UserControllerTest.java @@ -54,16 +54,16 @@ public class UserControllerTest { private JwtProvider jwtProvider; @Test - @WithMockUser(username = "kang4746",password = "test1234",roles = "USER") + @WithMockUser(username = "kang@gmail.com",password = "test1234",roles = "USER") @DisplayName("유저 정보 조회 컨트롤러 테스트") void getUserTest() throws Exception{ //given - given(userService.getUser("kang4746")).willReturn( + given(userService.getUser("kang@gmail.com")).willReturn( UserFindResDto.builder() - .loginId("kang4746") - .email("strong@gmail.com") - .birthDay("1999-10-29") + .name("홍길순") + .email("kang@gmail.com") + .nickName("kangg") .build()); //when @@ -71,13 +71,13 @@ void getUserTest() throws Exception{ .andExpect(status().isOk()) //json response 형식을 잘 봅시다. .andExpect(jsonPath("$.msg").exists()) - .andExpect(jsonPath("$.result.loginId").exists()) + .andExpect(jsonPath("$.result.name").exists()) .andExpect(jsonPath("$.result.email").exists()) - .andExpect(jsonPath("$.result.birthDay").exists()) + .andExpect(jsonPath("$.result.nickName").exists()) .andDo(print()); //then - verify(userService,times(1)).getUser("kang4746"); + verify(userService,times(1)).getUser("kang@gmail.com"); } @Test @@ -86,20 +86,17 @@ void signUpTest() throws Exception{ //given UserReqDto userRequestDto = UserReqDto.builder() - .loginId("kang4746") + .email("kang@gmail.com") .password("test1234") .name("홍길순") - .email("strong@gmail.com") - .birthDay("1999-10-29") .build(); given(signService.signUp(any(UserReqDto.class))) .willReturn(UserFindResDto.builder() .userId(1L) - .loginId("kang4746") .name("홍길순") - .email("strong@gmail.com") - .birthDay("1999-10-29") + .email("kang@gmail.com") + .nickName("kangg") .build()); Gson gson = new Gson(); @@ -110,9 +107,9 @@ void signUpTest() throws Exception{ .andExpect(status().isCreated()) .andExpect(jsonPath("$.msg").exists()) .andExpect(jsonPath("$.result.userId").exists()) - .andExpect(jsonPath("$.result.loginId").exists()) + .andExpect(jsonPath("$.result.name").exists()) .andExpect(jsonPath("$.result.email").exists()) - .andExpect(jsonPath("$.result.birthDay").exists()) + .andExpect(jsonPath("$.result.nickName").exists()) .andDo(print()); //then @@ -120,23 +117,21 @@ void signUpTest() throws Exception{ } @Test - @WithMockUser(username = "kang4746",password = "test1234",roles = "USER") + @WithMockUser(username = "kang@gmail.com",password = "test1234",roles = "USER") @DisplayName("유저 수정 테스트") void updateUserTest() throws Exception{ //given UserUpdateReqDto userUpdateDto = UserUpdateReqDto.builder() .name("홍길순") - .email("strong@naver.com") - .birthDay("1999-10-29") + .nickName("kanghj") .build(); - given(userService.updateUser(eq("kang4746"),any(UserUpdateReqDto.class))) + given(userService.updateUser(eq("kang@gmail.com"),any(UserUpdateReqDto.class))) .willReturn(UserFindResDto.builder() - .loginId("kang4746") .name("홍길순") - .email("strong@gmail.com") - .birthDay("1999-10-29") + .email("kang@gmail.com") + .nickName("kanghj") .build()); Gson gson = new Gson(); @@ -146,17 +141,16 @@ void updateUserTest() throws Exception{ mockMvc.perform(patch("/users") .content(content).contentType(MediaType.APPLICATION_JSON)) .andExpect(jsonPath("$.msg").exists()) - .andExpect(jsonPath("$.result.loginId").exists()) .andExpect(jsonPath("$.result.email").exists()) - .andExpect(jsonPath("$.result.birthDay").exists()) + .andExpect(jsonPath("$.result.nickName").exists()) .andDo(print()); //then - verify(userService,times(1)).updateUser(eq("kang4746"),any(UserUpdateReqDto.class)); + verify(userService,times(1)).updateUser(eq("kang@gmail.com"),any(UserUpdateReqDto.class)); } @Test - @WithMockUser(username = "kang4746",password = "test1234",roles = "USER") + @WithMockUser(username = "kang@gmail.com",password = "test1234",roles = "USER") @DisplayName("유저 삭제 테스트") void deleteUserTest() throws Exception{ //given @@ -165,6 +159,6 @@ void deleteUserTest() throws Exception{ .andExpect(status().isOk()) .andDo(print()); - verify(userService,times(1)).deleteUser("test1234","kang4746"); + verify(userService,times(1)).deleteUser("kang@gmail.com","test1234"); } } diff --git a/src/test/java/me/snaptime/user/service/ProfilePhotoServiceTest.java b/src/test/java/me/snaptime/user/service/ProfilePhotoServiceTest.java index d4c219c8..49ab9fa0 100644 --- a/src/test/java/me/snaptime/user/service/ProfilePhotoServiceTest.java +++ b/src/test/java/me/snaptime/user/service/ProfilePhotoServiceTest.java @@ -84,20 +84,20 @@ void updatePhotoToFileSystemTest() throws Exception { given(mockProfile.getProfilePhotoName()).willReturn("image"); given(mockProfile.getProfilePhotoPath()).willReturn("/image"); - Mockito.when(userRepository.findByLoginId("kang4746")) + Mockito.when(userRepository.findByEmail("kang@gmail.com")) .thenReturn(Optional.of(mockuser)); Mockito.when(profilePhotoRepository.findById(1L)) .thenReturn(Optional.of(mockProfile)); Mockito.when(profilePhotoRepository.save(any(ProfilePhoto.class))).thenReturn(updateProfilePhoto); //when - ProfilePhotoResDto responseDto = profilePhotoService.updatePhotoFromFileSystem("kang4746", updateFile); + ProfilePhotoResDto responseDto = profilePhotoService.updatePhotoFromFileSystem("kang@gmail.com", updateFile); //then Assertions.assertEquals(updateProfilePhoto.getProfilePhotoName(), responseDto.profilePhotoName()); Assertions.assertEquals(updateProfilePhoto.getProfilePhotoPath(), responseDto.profilePhotoPath()); - verify(userRepository, times(1)).findByLoginId("kang4746"); + verify(userRepository, times(1)).findByEmail("kang@gmail.com"); verify(profilePhotoRepository, times(1)).findById(1L); verify(profilePhotoRepository, times(1)).save(any()); diff --git a/src/test/java/me/snaptime/user/service/UserServiceTest.java b/src/test/java/me/snaptime/user/service/UserServiceTest.java index b8525c27..f40dbbba 100644 --- a/src/test/java/me/snaptime/user/service/UserServiceTest.java +++ b/src/test/java/me/snaptime/user/service/UserServiceTest.java @@ -66,10 +66,9 @@ class UserServiceTest { public void setUpTestSet() { givenUser = User.builder() .name("홍길순") - .loginId("kang4746") + .email("kang@gmail.com") .password("test1234") - .email("strong@gmail.com") - .birthDay("1999-10-29") + .nickName("kangg") .build(); } @@ -77,19 +76,18 @@ public void setUpTestSet() { @DisplayName("given_when_then 방식으로 getUser 서비스 성공 테스트") public void getUser() { //given - Mockito.when(userRepository.findByLoginId("kang4746")) + Mockito.when(userRepository.findByEmail("kang@gmail.com")) .thenReturn(Optional.of(givenUser)); //when - UserFindResDto userFindResDto = userService.getUser("kang4746"); + UserFindResDto userFindResDto = userService.getUser("kang@gmail.com"); //then Assertions.assertEquals(givenUser.getUserId(), userFindResDto.userId()); Assertions.assertEquals(givenUser.getName(), userFindResDto.name()); - Assertions.assertEquals(givenUser.getLoginId(), userFindResDto.loginId()); Assertions.assertEquals(givenUser.getEmail(), userFindResDto.email()); - Assertions.assertEquals(givenUser.getBirthDay(), userFindResDto.birthDay()); + Assertions.assertEquals(givenUser.getNickName(), userFindResDto.nickName()); - verify(userRepository, times(1)).findByLoginId("kang4746"); + verify(userRepository, times(1)).findByEmail("kang@gmail.com"); } @Test @@ -98,10 +96,8 @@ public void signUp() { //given UserReqDto givenRequest = UserReqDto.builder() .name("홍길순") - .loginId("kang4746") + .email("kang@gmail.com") .password("test1234") - .email("strong@gmail.com") - .birthDay("1999-10-29") .build(); @@ -117,9 +113,8 @@ public void signUp() { //then Assertions.assertEquals(givenRequest.name(), userFindResDto.name()); - Assertions.assertEquals(givenRequest.loginId(), userFindResDto.loginId()); Assertions.assertEquals(givenRequest.email(), userFindResDto.email()); - Assertions.assertEquals(givenRequest.birthDay(), userFindResDto.birthDay()); + verify(userRepository,times(1)).save(any()); } @@ -128,17 +123,17 @@ public void signUp() { public void signIn(){ //given SignInReqDto signInReqDto = SignInReqDto.builder() - .loginId("kang4746") + .email("kang@gmail.com") .password("test1234") .build(); - Mockito.when(userRepository.findByLoginId("kang4746")) + Mockito.when(userRepository.findByEmail("kang@gmail.com")) .thenReturn(Optional.of(givenUser)); Mockito.when(passwordEncoder.matches(signInReqDto.password(), givenUser.getPassword())) .thenReturn(true); - Mockito.when(jwtProvider.createAccessToken(givenUser.getUserId(),givenUser.getLoginId(), givenUser.getRoles())) + Mockito.when(jwtProvider.createAccessToken(givenUser.getUserId(),givenUser.getEmail(), givenUser.getRoles())) .thenReturn("mockAccessToken"); - Mockito.when(jwtProvider.createRefreshToken(givenUser.getUserId(),givenUser.getLoginId(), givenUser.getRoles())) + Mockito.when(jwtProvider.createRefreshToken(givenUser.getUserId(),givenUser.getEmail(), givenUser.getRoles())) .thenReturn("mockRefreshToken"); Mockito.when(refreshTokenRepository.save(any(RefreshToken.class))) .then(returnsFirstArg()); @@ -149,12 +144,12 @@ public void signIn(){ //then Assertions.assertEquals("mockAccessToken",signInResDto.accessToken()); Assertions.assertEquals("mockRefreshToken",signInResDto.refreshToken()); - Assertions.assertEquals(signInReqDto.loginId(),givenUser.getLoginId()); + Assertions.assertEquals(signInReqDto.email(),givenUser.getEmail()); Assertions.assertEquals(signInReqDto.password(),givenUser.getPassword()); - verify(userRepository,times(1)).findByLoginId("kang4746"); + verify(userRepository,times(1)).findByEmail("kang@gmail.com"); verify(passwordEncoder,times(1)).matches(signInReqDto.password(),givenUser.getPassword()); - verify(jwtProvider,times(1)).createAccessToken(givenUser.getUserId(),givenUser.getLoginId(),givenUser.getRoles()); + verify(jwtProvider,times(1)).createAccessToken(givenUser.getUserId(),givenUser.getEmail(),givenUser.getRoles()); } @@ -166,17 +161,17 @@ public void deleteUser() { User user = spy(givenUser); given(user.getUserId()).willReturn(1L); - Mockito.when(userRepository.findByLoginId("kang4746")) + Mockito.when(userRepository.findByEmail("kang@gmail.com")) .thenReturn(Optional.of(user)); Mockito.when(passwordEncoder.matches("test1234", user.getPassword())) .thenReturn(true); //when - userService.deleteUser("test1234","kang4746"); + userService.deleteUser("kang@gmail.com","test1234"); //then - verify(userRepository,times(1)).findByLoginId("kang4746"); + verify(userRepository,times(1)).findByEmail("kang@gmail.com"); verify(userRepository,times(1)).deleteById(1L); } @@ -186,22 +181,19 @@ public void updateUser() { //given UserUpdateReqDto userUpdateDto = UserUpdateReqDto.builder() .name("") - .email("strong@naver.com") - .birthDay("") + .nickName("kanghj") .build(); - Mockito.when(userRepository.findByLoginId("kang4746")) + Mockito.when(userRepository.findByEmail("kang@gmail.com")) .thenReturn(Optional.of(givenUser)); //when - UserFindResDto userResponseDto = userService.updateUser("kang4746",userUpdateDto); + UserFindResDto userResponseDto = userService.updateUser("kang@gmail.com",userUpdateDto); //then Assertions.assertEquals("홍길순",userResponseDto.name()); - Assertions.assertEquals("kang4746",userResponseDto.loginId()); - Assertions.assertEquals("strong@naver.com",userResponseDto.email()); - Assertions.assertEquals("1999-10-29",userResponseDto.birthDay()); - - verify(userRepository,times(1)).findByLoginId("kang4746"); + Assertions.assertEquals("kang@gmail.com",userResponseDto.email()); + Assertions.assertEquals("kanghj",userResponseDto.nickName()); + verify(userRepository,times(1)).findByEmail("kang@gmail.com"); } } \ No newline at end of file