Skip to content

Commit

Permalink
Merge branch 'develop' of https://github.com/BangFer/BangFer-Back_End
Browse files Browse the repository at this point in the history
…into develop
  • Loading branch information
gomin0 committed Sep 12, 2024
2 parents 466819b + 8f973da commit f426aaf
Show file tree
Hide file tree
Showing 9 changed files with 112 additions and 120 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,6 @@ public class EmailService {

private final JavaMailSender javaMailSender;
private final RedisUtil redisUtil;
private final String ePw = createKey();
private static final String AUTH_CODE_PREFIX = "AuthCode ";

@Value("${spring.mail.username}")
Expand All @@ -36,28 +35,28 @@ public class EmailService {
@Value("${spring.mail.smtp.timeout}")
private long codeExpTime;

public MimeMessage createMessage(String to) throws MessagingException, UnsupportedEncodingException {
log.info("보내는 대상: " + to);
log.info("인증 번호: " + ePw);
public MimeMessage createMessage(String to, String authCode) throws MessagingException, UnsupportedEncodingException {
// log.info("보내는 대상: " + to);
// log.info("인증 번호: " + authCode);
MimeMessage message = javaMailSender.createMimeMessage();

message.addRecipients(MimeMessage.RecipientType.TO, to); // 보낼 대상
message.setSubject("방구석 퍼거슨 인증 코드"); // 메일 제목

String msg = getString();
String msg = getString(authCode);

message.setText(msg, "utf-8", "html"); //내용, charset타입, subtype
message.setFrom(new InternetAddress(id,"bangFer"));

return message;
}

private String getString() {
private String getString(String authCode) {
String msg="";
msg += "<h1 style=\"font-size: 30px; padding-right: 30px; padding-left: 30px;\">이메일 주소 확인</h1>";
msg += "<p style=\"font-size: 17px; padding-right: 30px; padding-left: 30px;\">아래 확인 코드를 화면에서 입력해주세요.</p>";
msg += "<div style=\"padding-right: 30px; padding-left: 30px; margin: 32px 0 40px;\"><table style=\"border-collapse: collapse; border: 0; background-color: #F4F4F4; height: 70px; table-layout: fixed; word-wrap: break-word; border-radius: 6px;\"><tbody><tr><td style=\"text-align: center; vertical-align: middle; font-size: 30px;\">";
msg += ePw;
msg += authCode;
msg += "</td></tr></tbody></table></div>";
return msg;
}
Expand All @@ -75,23 +74,28 @@ public static String createKey() {

@Transactional
public String sendMessage(String to) throws Exception {
MimeMessage message = createMessage(to);
String authCode = createKey();
MimeMessage message = createMessage(to, authCode);
try {
javaMailSender.send(message);
} catch (MailException es) {
es.printStackTrace();
throw new AccountsExceptionHandler(ErrorCode.UNABLE_TO_SEND_EMAIL);
}
redisUtil.save(AUTH_CODE_PREFIX + to, ePw, codeExpTime, TimeUnit.MILLISECONDS);
return ePw;
redisUtil.save(AUTH_CODE_PREFIX + to, authCode, codeExpTime, TimeUnit.MILLISECONDS);
return authCode;
}

@Transactional
public boolean verifyCode(EmailVerifyDto requestDto) {
if (!(redisUtil.hasKey(AUTH_CODE_PREFIX + requestDto.email()))) {
String key = AUTH_CODE_PREFIX + requestDto.email();

if (!(redisUtil.hasKey(key))) {
throw new CustomException(ErrorCode.CODE_IS_NOT_VALID);
}
else if (redisUtil.get(AUTH_CODE_PREFIX + requestDto.email()).toString().equals(requestDto.code())) {
String savedCode = redisUtil.get(key).toString();
if (savedCode.equals(requestDto.code())) {
redisUtil.delete(key); // 인증 후 삭제
return true;
}
else {
Expand Down

This file was deleted.

Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
package com.capstone.BnagFer.domain.board.entity;

import com.capstone.BnagFer.domain.accounts.entity.User;
import com.capstone.BnagFer.global.common.BaseEntity;
import jakarta.persistence.*;
import lombok.*;
import java.time.LocalDateTime;

@Entity
@Builder
@Getter
Expand All @@ -16,15 +16,21 @@ public class BoardBlock extends BaseEntity {
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "board_block_id", nullable = false)
private Long id;

@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "block_user_id")
private User blockUser;

@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "is_blocked_user_id")
private User isBlockedUser;

@Column(name = "blocked_at")
private LocalDateTime blockedAt;
}

public static BoardBlock create(User blockUser, User isBlockedUser) {
BoardBlock boardBlock = new BoardBlock();
boardBlock.blockUser = blockUser;
boardBlock.isBlockedUser = isBlockedUser;
return boardBlock;

}
}
Original file line number Diff line number Diff line change
@@ -1,8 +1,6 @@
package com.capstone.BnagFer.domain.board.service;

import com.capstone.BnagFer.domain.accounts.entity.User;
import com.capstone.BnagFer.domain.accounts.repository.UserJpaRepository;
import com.capstone.BnagFer.domain.board.dto.request.BoardBlockRequestDto;
import com.capstone.BnagFer.domain.board.dto.response.BoardBlockResponseDto;
import com.capstone.BnagFer.domain.board.entity.BoardBlock;
import com.capstone.BnagFer.domain.board.exception.BoardExceptionHandler;
Expand All @@ -11,7 +9,6 @@
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
@RequiredArgsConstructor
@Transactional
Expand All @@ -20,28 +17,31 @@ public class BoardBlockService {
private final UserJpaRepository userRepository;

public BoardBlockResponseDto blockUser(User blockUser, Long isBlockedUserId) {
User blockedUser = userRepository.findById(isBlockedUserId)
.orElseThrow(() -> new BoardExceptionHandler(ErrorCode.USER_NOT_FOUND));
if (blockUser.getId().equals(isBlockedUserId)) {
throw new BoardExceptionHandler(ErrorCode.CANNOT_REPORT_YOURSELF);
}
if(boardBlockRepository.existsByBlockUserAndIsBlockedUser(blockUser, blockedUser)){
User blockedUser = checkIfIsBlocked(isBlockedUserId);
validateSelfAction(blockUser, isBlockedUserId, ErrorCode.CANNOT_REPORT_YOURSELF);
if (boardBlockRepository.existsByBlockUserAndIsBlockedUser(blockUser, blockedUser)) {
throw new BoardExceptionHandler(ErrorCode.ALREADY_BLOCKED);
}
BoardBlockRequestDto request = new BoardBlockRequestDto();
BoardBlock boardBlock = request.toEntity(blockUser, blockedUser);

BoardBlock boardBlock = BoardBlock.create(blockUser, blockedUser);
boardBlockRepository.save(boardBlock);
return BoardBlockResponseDto.from(boardBlock);
}

public void unblockUser(User blockUser, Long isBlockedUserId) {
User blockedUser = userRepository.findById(isBlockedUserId)
.orElseThrow(() -> new BoardExceptionHandler(ErrorCode.USER_NOT_FOUND));
if (blockUser.getId().equals(isBlockedUserId)) {
throw new BoardExceptionHandler(ErrorCode.CANNOT_UNBLOCK_YOURSELF);
}
User blockedUser = checkIfIsBlocked(isBlockedUserId);
validateSelfAction(blockUser, isBlockedUserId, ErrorCode.CANNOT_UNBLOCK_YOURSELF);
boardBlockRepository.deleteByBlockUserAndIsBlockedUser(blockUser, blockedUser);
}

private User checkIfIsBlocked(Long isBlockedUserId) {
return userRepository.findById(isBlockedUserId)
.orElseThrow(() -> new BoardExceptionHandler(ErrorCode.USER_NOT_FOUND));
}

}
private void validateSelfAction(User blockUser, Long isBlockedUserId, ErrorCode errorCode) {
if (blockUser.getId().equals(isBlockedUserId)) {
throw new BoardExceptionHandler(errorCode);
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@
import com.capstone.BnagFer.domain.accounts.entity.User;
import com.capstone.BnagFer.domain.accounts.repository.ProfileJpaRepository;
import com.capstone.BnagFer.domain.accounts.service.account.AccountsCommonService;
import com.capstone.BnagFer.domain.notification.event.TeamInviteCreatedEvent;
import com.capstone.BnagFer.domain.myteam.dto.request.TeamInviteRequestDto;
import com.capstone.BnagFer.domain.myteam.dto.response.TeamInviteResponseDto;
import com.capstone.BnagFer.domain.myteam.dto.response.TeamMembersResponseDto;
Expand All @@ -14,6 +13,7 @@
import com.capstone.BnagFer.domain.myteam.repository.TeamInviteRepository;
import com.capstone.BnagFer.domain.myteam.repository.TeamMembersRepository;
import com.capstone.BnagFer.domain.myteam.repository.TeamRepository;
import com.capstone.BnagFer.domain.notification.event.TeamInviteCreatedEvent;
import com.capstone.BnagFer.global.common.ErrorCode;
import lombok.RequiredArgsConstructor;
import org.springframework.context.ApplicationEventPublisher;
Expand All @@ -33,36 +33,19 @@ public class TeamInviteService {

public TeamInviteResponseDto inviteTeamMembers(TeamInviteRequestDto request, User inviter) {
Profile profile = profileJpaRepository.findByNickname(request.nickName());
if(profile==null){
if (profile == null) {
throw new TeamMemberExceptionHandler(ErrorCode.USER_NOT_FOUND);
}
User invitedUser = profile.getUser();
//초대가 이루어질 팀을 ID로 찾아오고, 없으면 TEAM_NOT_FOUND 예외를 던진다

Team team = teamRepository.findById(request.teamId())
.orElseThrow(() -> new TeamExceptionHandler(ErrorCode.TEAM_NOT_FOUND));

// 방장이 자기 자신을 초대 못하게 하는 예외처리
if (inviter.getId().equals(invitedUser.getId())) {
throw new TeamMemberExceptionHandler(ErrorCode.CANNOT_INVITE_YOURSELF);
}

// 초대하려는 사용자가 팀의 리더가 아닌 경우 예외를 던진다
if (!team.getLeader().getId().equals(inviter.getId())) {
throw new TeamMemberExceptionHandler(ErrorCode.NO_AUTHORIZATION);
}

// 초대받은 사용자가 이미 팀 멤버인지 확인한다
boolean isAlreadyMember = team.getTeamMembers().stream()
.anyMatch(teamMember -> teamMember.getUser().equals(invitedUser));
if (isAlreadyMember) {
throw new TeamMemberExceptionHandler(ErrorCode.TEAMMEMBER_EXISTS);
}
checkIfAlreadyMember(team, invitedUser);

// 초대받은 사용자가 이미 초대되었는지 확인한다
boolean isAlreadyInvited = teamInviteRepository.existsByTeamAndInvitedUser(team, invitedUser);
if (isAlreadyInvited) {
throw new TeamMemberExceptionHandler(ErrorCode.INVITATION_ALREADY_SENT);
}
checkIfAlreadyInvited(team, invitedUser);

// 초대 엔티티를 생성하고 저장한다
TeamInvite teamInvite = request.toEntity(invitedUser, team, inviter);
Expand All @@ -71,30 +54,28 @@ public TeamInviteResponseDto inviteTeamMembers(TeamInviteRequestDto request, Use
// FCM 알림 전송
eventPublisher.publishEvent(new TeamInviteCreatedEvent(savedInvite));

// 초대 정보를 응답 DTO로 변환하여 반환한다
return TeamInviteResponseDto.from(teamInvite);
}


public void kickOutMembers(Long memberId, Long teamId, User user) {
TeamMember teamMember = teamMembersRepository.findById(memberId).orElseThrow(() -> new TeamMemberExceptionHandler(ErrorCode.CANNOT_FIND_TEAMMEMBER));
Team team = teamRepository.findById(teamId).orElseThrow(() -> new TeamExceptionHandler(ErrorCode.TEAM_NOT_FOUND));
// 프로필 존재 확인
accountsCommonService.checkUserProfile(teamMember.getUser());

//방장에게만 강퇴 권한
if (team.getLeader().getId().equals(user.getId()))
teamMembersRepository.delete(teamMember);
else
throw new TeamMemberExceptionHandler(ErrorCode.NO_AUTHORIZATION);


//방장이 자기 자신을 강퇴 못하게 해주는 예외처리
if (user.getId().equals(memberId)) {
if (user.getId().equals(memberId))
throw new TeamMemberExceptionHandler(ErrorCode.CANNOT_KICK_OUT_YOURSELF);
}

//이미 강퇴당한 팀원 예외처리
if (teamMember.getId() == null)
throw new TeamMemberExceptionHandler(ErrorCode.ALREAY_KICKED_OUT);

teamMembersRepository.delete(teamMember);
}

public TeamMembersResponseDto acceptInvite(Long inviteId, User user) {
Expand All @@ -120,4 +101,19 @@ public void rejectInvite(Long inviteId, User user) {
}
teamInviteRepository.delete(invite);
}

private void checkIfAlreadyMember(Team team, User invitedUser) {
boolean isAlreadyMember = team.getTeamMembers().stream()
.anyMatch(teamMember -> teamMember.getUser().equals(invitedUser));
if (isAlreadyMember) {
throw new TeamMemberExceptionHandler(ErrorCode.TEAMMEMBER_EXISTS);
}
}

private void checkIfAlreadyInvited(Team team, User invitedUser) {
boolean isAlreadyInvited = teamInviteRepository.existsByTeamAndInvitedUser(team, invitedUser);
if (isAlreadyInvited) {
throw new TeamMemberExceptionHandler(ErrorCode.INVITATION_ALREADY_SENT);
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -25,37 +25,19 @@ public class TeamMembersService {
private final TeamRepository teamRepository;
private final ApplicationEventPublisher eventPublisher;


public TeamMemberPositionResponseDto allocatePosition(TeamMemberPositionRequestDto request, Long teamId, Long memberId, User user) {
Team team = teamRepository.findById(teamId).orElseThrow(() -> new TeamExceptionHandler(ErrorCode.TEAM_NOT_FOUND));
TeamMember teamMember = teamMembersRepository.findById(memberId).orElseThrow(() -> new TeamMemberExceptionHandler(ErrorCode.CANNOT_FIND_TEAMMEMBER));

if (!team.getId().equals(teamMember.getTeam().getId())) {
throw new TeamMemberExceptionHandler(ErrorCode.CANNOT_FIND_TEAMMEMBER);
}
validateTeamMemberIsInTeam(team, teamMember);
validateLeaderAuthorization(team, user);

Position requestedPosition = request.position();
// 요청한 포지션(requestedPosition)이 이미 다른 멤버에게 할당되어 있는지 확인
TeamMember existingMemberWithPosition = teamMembersRepository.findByTeamAndPosition(team, requestedPosition);
boolean teamMemberInTeam = teamMembersRepository.existsByTeamAndId(team, memberId);
if (team.getLeader().getId().equals(user.getId())) {
if (teamMemberInTeam) {
if (existingMemberWithPosition == null || !existingMemberWithPosition.equals(teamMember)) {
// 이미 다른 멤버가 요청한 포지션을 가지고 있으면 그 멤버의 포지션을 null로 설정
if (existingMemberWithPosition != null) {
existingMemberWithPosition.updatePosition(null);
teamMembersRepository.save(existingMemberWithPosition);
}
// 요청한 멤버에게 포지션 할당
teamMember.updatePosition(requestedPosition);
teamMembersRepository.save(teamMember);

// FCM 알림 전송
eventPublisher.publishEvent(new PositionAllocatedEvent(teamMember, requestedPosition));
}
} else
throw new TeamMemberExceptionHandler(ErrorCode.CANNOT_FIND_TEAMMEMBER);
} else
throw new TeamMemberExceptionHandler(ErrorCode.CANNOT_ALLOCATE);
TeamMember existingMemberWithPosition = findExistingMemberWithPosition(team, requestedPosition);

allocateTeamMemberPosition(team, teamMember, existingMemberWithPosition, requestedPosition);

return TeamMemberPositionResponseDto.from(request.toEntity(teamMember));
}

Expand All @@ -74,4 +56,39 @@ public void deallocatePosition(Long teamId, Long memberId, User user) {
} else
throw new TeamMemberExceptionHandler(ErrorCode.CANNOT_ALLOCATE);
}
}

private void validateTeamMemberIsInTeam(Team team, TeamMember teamMember) {
if (!team.getId().equals(teamMember.getTeam().getId())) {
throw new TeamMemberExceptionHandler(ErrorCode.TEAMMEMBER_NOT_IN_TEAM);
}
}

private void validateLeaderAuthorization(Team team, User user) {
if (!team.getLeader().getId().equals(user.getId())) {
throw new TeamMemberExceptionHandler(ErrorCode.CANNOT_ALLOCATE);
}
}

private TeamMember findExistingMemberWithPosition(Team team, Position requestedPosition) {
return teamMembersRepository.findByTeamAndPosition(team, requestedPosition);
}

private void allocateTeamMemberPosition(Team team, TeamMember teamMember, TeamMember existingMemberWithPosition, Position requestedPosition) {
boolean teamMemberInTeam = teamMembersRepository.existsByTeamAndId(team, teamMember.getId());

if (!teamMemberInTeam) {
throw new TeamMemberExceptionHandler(ErrorCode.CANNOT_FIND_TEAMMEMBER);
}

if (existingMemberWithPosition != null && !existingMemberWithPosition.equals(teamMember)) {
existingMemberWithPosition.updatePosition(null);
teamMembersRepository.save(existingMemberWithPosition);
}

teamMember.updatePosition(requestedPosition);
teamMembersRepository.save(teamMember);
// FCM 알림 전송
eventPublisher.publishEvent(new PositionAllocatedEvent(teamMember, requestedPosition));
}

}
Loading

0 comments on commit f426aaf

Please sign in to comment.