Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -89,6 +89,9 @@ dependencies {
// Prometheus
implementation 'org.springframework.boot:spring-boot-starter-actuator'
implementation 'io.micrometer:micrometer-registry-prometheus'

// Jasypt
implementation 'com.github.ulisesbocchio:jasypt-spring-boot-starter:3.0.5'
}

tasks.named('test') {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
package doldol_server.doldol.auth.controller;

import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import doldol_server.doldol.auth.service.TestService;
import doldol_server.doldol.common.response.ApiResponse;
import lombok.RequiredArgsConstructor;

@RestController
@RequestMapping("/test")
@RequiredArgsConstructor
public class TestController {

private final TestService testService;

@PostMapping()
public ApiResponse<Void> resetPassword() {
testService.updateAll();
return ApiResponse.noContent();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
import java.util.Optional;
import java.util.concurrent.TimeUnit;

import org.jasypt.encryption.StringEncryptor;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
Expand Down Expand Up @@ -165,7 +166,8 @@ public void withdraw(Long userId) {
}

public void validateUserInfo(String name, String email, String phone) {
boolean existsByNameAndEmailAndPhone = userRepository.existsByNameAndEmailAndPhone(name, email, phone);
boolean existsByNameAndEmailAndPhone = userRepository.existsByNameAndEmailAndPhone(
name, email, phone);

if (!existsByNameAndEmailAndPhone) {
throw new CustomException(AuthErrorCode.INCORRECT_NAME_OR_EMAIL_OR_PHONE);
Expand Down Expand Up @@ -239,4 +241,4 @@ private String maskingId(String loginId) {
return prefix + maskedPart;
}

}
}
Original file line number Diff line number Diff line change
Expand Up @@ -12,9 +12,9 @@

import doldol_server.doldol.auth.dto.CustomUserDetails;
import doldol_server.doldol.auth.dto.OAuth2Response;
import doldol_server.doldol.common.exception.CustomOAuth2Exception;
import doldol_server.doldol.common.exception.errorCode.AuthErrorCode;
import doldol_server.doldol.common.exception.errorCode.CommonErrorCode;
import doldol_server.doldol.common.exception.CustomOAuth2Exception;
import doldol_server.doldol.user.entity.SocialType;
import doldol_server.doldol.user.entity.User;
import doldol_server.doldol.user.repository.UserRepository;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

import java.util.Optional;

import org.jasypt.encryption.StringEncryptor;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;
Expand All @@ -10,7 +11,9 @@
import doldol_server.doldol.user.entity.User;
import doldol_server.doldol.user.repository.UserRepository;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;

@Slf4j
@Component
@RequiredArgsConstructor
public class CustomUserDetailsService implements UserDetailsService {
Expand All @@ -20,9 +23,10 @@ public class CustomUserDetailsService implements UserDetailsService {
@Override
public CustomUserDetails loadUserByUsername(String loginId) throws UsernameNotFoundException {
Optional<User> user = userRepository.findByLoginIdAndIsDeletedFalse(loginId);

log.info("id: {}", loginId);
if (user.isPresent()) {
User loginUser = user.get();
log.info("user Id: {}", loginUser.getLoginId());
return new CustomUserDetails(loginUser);
}
return null;
Expand Down
55 changes: 55 additions & 0 deletions src/main/java/doldol_server/doldol/auth/service/TestService.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
package doldol_server.doldol.auth.service;

import java.util.List;

import org.jasypt.encryption.StringEncryptor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import doldol_server.doldol.rollingPaper.entity.Message;
import doldol_server.doldol.rollingPaper.repository.MessageRepository;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;

@Slf4j
@Service
@RequiredArgsConstructor
public class TestService {

private final MessageRepository messageRepository;
private final StringEncryptor encryptor;

@Transactional
public void updateAll() {
log.info("🚀 전체 데이터 암호화 시작");

encryptMessageData();

log.info("✅ 전체 데이터 암호화 완료");
}


@Transactional
public void encryptMessageData() {
log.info("💬 Message 테이블 암호화 시작");

List<Message> messages = messageRepository.findAll();
log.info("총 {} 개의 메시지 데이터를 암호화합니다.", messages.size());

for (Message message : messages) {
try {
if (message.getContent() != null) {
message.updateContent(encryptor.encrypt(message.getContent()));
messageRepository.save(message);
log.info("Message ID {} 암호화 완료", message.getId());
}

} catch (Exception e) {
log.error("Message ID {} 암호화 실패: {}", message.getId(), e.getMessage());
}
}

log.info("✅ Message 테이블 암호화 완료: {} 개 처리", messages.size());
}

}
24 changes: 24 additions & 0 deletions src/main/java/doldol_server/doldol/common/config/JasyptConfig.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
package doldol_server.doldol.common.config;

import org.jasypt.encryption.pbe.PooledPBEStringEncryptor;
import org.jasypt.encryption.pbe.config.SimpleStringPBEConfig;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class JasyptConfig {

@Value("${jasypt.encryptor.password}")
private String encryptKey;

@Bean(name = "jasyptEncryptor")
public SimpleStringPBEConfig encryptor() {
PooledPBEStringEncryptor encryptor = new PooledPBEStringEncryptor();
SimpleStringPBEConfig config = new SimpleStringPBEConfig();
config.setPassword(encryptKey);
config.setStringOutputType("base64");
encryptor.setConfig(config);
return config;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@
public class SecurityConfig {

private static final String[] WHITELIST = {
"/test",
"/auth/check-id",
"/auth/check-register-info",
"/auth/email/send-code",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -79,4 +79,19 @@ public MessageResponse withNullContent() {
.updatedAt(this.updatedAt)
.build();
}

public MessageResponse withDecryptedContent(String decryptedContent) {
return MessageResponse.builder()
.messageId(this.messageId)
.messageType(this.messageType)
.content(decryptedContent)
.fontStyle(this.fontStyle)
.backgroundColor(this.backgroundColor)
.isDeleted(this.isDeleted)
.fromName(this.fromName)
.toName(this.toName)
.createdAt(this.createdAt)
.updatedAt(this.updatedAt)
.build();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -15,4 +15,6 @@ public interface ParticipantRepository extends JpaRepository<Participant, Long>,
+ "join fetch p.user u "
+ "where pa.id = :paperId")
List<Participant> findByPaperIdWithUser(Long paperId);

boolean existsByPaperIdAndUserId(Long paperId, Long userId);
}
Original file line number Diff line number Diff line change
Expand Up @@ -6,5 +6,5 @@
import doldol_server.doldol.rollingPaper.dto.response.ParticipantResponse;

public interface ParticipantRepositoryCustom {
List<ParticipantResponse> getParticipants(Long paperId, GetParticipantsRequest pageRequest);
List<ParticipantResponse> getParticipants(Long paperId, GetParticipantsRequest pageRequest, Long userId);
}
Original file line number Diff line number Diff line change
Expand Up @@ -19,14 +19,14 @@ public class ParticipantRepositoryCustomImpl implements ParticipantRepositoryCus
private final JPAQueryFactory queryFactory;

@Override
public List<ParticipantResponse> getParticipants(Long paperId, GetParticipantsRequest request) {
public List<ParticipantResponse> getParticipants(Long paperId, GetParticipantsRequest request, Long userId) {
QParticipant participant = QParticipant.participant;
QUser user = QUser.user;

BooleanExpression cursorCondition = null;
if (request.cursorName() != null && request.cursorId() != null) {
cursorCondition = user.name.gt(request.cursorName())
.or(user.id.lt(request.cursorId()));
cursorCondition = user.name.goe(request.cursorName())
.or(user.name.eq(request.cursorName()).and(user.id.goe(request.cursorId())));
}

return queryFactory
Expand All @@ -43,7 +43,8 @@ public List<ParticipantResponse> getParticipants(Long paperId, GetParticipantsRe
.join(participant.user, user)
.where(
participant.paper.id.eq(paperId),
cursorCondition
cursorCondition,
participant.user.id.ne(userId)
)
.orderBy(user.name.asc(), user.id.asc())
.limit(request.size() + 1L)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
import java.time.LocalDate;
import java.util.List;

import org.jasypt.encryption.StringEncryptor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

Expand Down Expand Up @@ -33,6 +34,7 @@ public class MessageService {
private final PaperRepository paperRepository;
private final MessageRepository messageRepository;
private final UserService userService;
private final StringEncryptor encryptor;

public MessageResponse getMessage(Long messageId, Long userId) {
MessageResponse message = messageRepository.getMessage(messageId, userId);
Expand All @@ -41,7 +43,7 @@ public MessageResponse getMessage(Long messageId, Long userId) {
throw new CustomException(MessageErrorCode.MESSAGE_NOT_FOUND);
}

return message;
return decryptMessageContent(message);
}

public MessageListResponse getMessages(Long paperId, MessageType messageType, CursorPageRequest request, Long userId) {
Expand All @@ -56,15 +58,20 @@ public MessageListResponse getMessages(Long paperId, MessageType messageType, Cu
? messageRepository.getReceivedMessages(paperId, userId, request)
: messageRepository.getSentMessages(paperId, userId, request);

List<MessageResponse> processedMessages;
if (!isOpened && isReceiveType) {
messages = messages.stream()
processedMessages = messages.stream()
.map(MessageResponse::withNullContent)
.toList();
} else {
processedMessages = messages.stream()
.map(this::decryptMessageContent)
.toList();
}

int totalCount = isReceiveType ? getReceivedMessageCounts(paperId, userId).intValue() :
getSentMessageCounts(paperId, userId).intValue();
CursorPage<MessageResponse, Long> cursorPage = CursorPage.of(messages, request.size(),
CursorPage<MessageResponse, Long> cursorPage = CursorPage.of(processedMessages, request.size(),
MessageResponse::messageId);
return MessageListResponse.of(totalCount, cursorPage);
}
Expand Down Expand Up @@ -93,7 +100,7 @@ public void createMessage(CreateMessageRequest request, Long userId) {
.paper(paper)
.name(request.from())
.backgroundColor(request.backgroundColor())
.content(request.content())
.content(encryptor.encrypt(request.content()))
.fontStyle(request.fontStyle())
.build();

Expand Down Expand Up @@ -131,9 +138,9 @@ private Long getSentMessageCounts(Long paperId, Long userId) {
return messageRepository.getSentdMessagesCount(paperId, userId);
}

private static void conditionalUpdate(UpdateMessageRequest request, Message message) {
private void conditionalUpdate(UpdateMessageRequest request, Message message) {
if (request.content() != null) {
message.updateContent(request.content());
message.updateContent(encryptor.encrypt(request.content()));
}
if (request.fontStyle() != null) {
message.updateFontStyle(request.fontStyle());
Expand All @@ -145,4 +152,9 @@ private static void conditionalUpdate(UpdateMessageRequest request, Message mess
message.updateName(request.fromName());
}
}
}

private MessageResponse decryptMessageContent(MessageResponse messageResponse) {
String decryptedContent = encryptor.decrypt(messageResponse.content());
return messageResponse.withDecryptedContent(decryptedContent);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -17,10 +17,12 @@
import doldol_server.doldol.rollingPaper.repository.ParticipantRepository;
import doldol_server.doldol.user.service.UserService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;

@Service
@Transactional(readOnly = true)
@RequiredArgsConstructor
@Slf4j
public class ParticipantService {

private final ParticipantRepository participantRepository;
Expand All @@ -40,18 +42,20 @@ public void addUser(Long userId, Paper paper, boolean isMaster) {

public CursorPage<ParticipantResponse, ParticipantsCursorResponse> getParticipants(Long paperId,
GetParticipantsRequest request, Long userId) {
List<ParticipantResponse> participants = participantRepository.getParticipants(paperId, request);
existUser(userId, paperId);

List<ParticipantResponse> participants = participantRepository.getParticipants(paperId, request, userId);
if (participants.isEmpty()) {
throw new CustomException(PAPER_NOT_FOUND);
}
existUser(userId, participants);

List<ParticipantResponse> response = participants.stream()
.filter(resp -> !resp.userId().equals(userId))
.toList();


return CursorPage.of(response, request.size(),
last -> new ParticipantsCursorResponse(last.name(), last.participantId()));
last -> new ParticipantsCursorResponse(formatName(last.name()), last.userId()));
}

public Participant getOneByPaperAndUser(Long paperId, Long userId) {
Expand Down Expand Up @@ -81,9 +85,13 @@ private void existPaper(List<Participant> participants) {
}
}

private void existUser(Long userId, List<ParticipantResponse> participants) {
if (participants.stream().noneMatch(participant -> participant.userId().equals(userId))) {
private void existUser(Long userId, Long paperId) {
if(!participantRepository.existsByPaperIdAndUserId(paperId, userId)) {
throw new CustomException(PARTICIPANT_NOT_FOUND);
}
}

private String formatName(String name) {
return name.substring(0, name.indexOf("(")).trim();
}
}
Loading
Loading