Skip to content

Commit

Permalink
Merge pull request #36 from Happy-New-Here/main
Browse files Browse the repository at this point in the history
a
  • Loading branch information
yooonwodyd authored Dec 24, 2023
2 parents df50e38 + 3db00d4 commit b1fa934
Show file tree
Hide file tree
Showing 16 changed files with 174 additions and 156 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
import com.example.HappyNewHere.dto.request.AccountRequestDto;
import com.example.HappyNewHere.service.AccountService;
import com.example.HappyNewHere.service.KakaoService;
import com.example.HappyNewHere.utils.AuthenticateUtils;
import com.example.HappyNewHere.utils.JwtUtils;
import lombok.RequiredArgsConstructor;
import org.springframework.data.domain.Page;
Expand All @@ -21,7 +22,7 @@
@RequiredArgsConstructor
@CrossOrigin
public class AccountController {

private final AuthenticateUtils authenticateUtils;
private final AccountService accountService;
private final KakaoService kakaoService;

Expand All @@ -39,7 +40,8 @@ public ResponseEntity<?> login(
@GetMapping("/userInfo")
public ResponseEntity<?> personalInfo(Authentication authentication
) {
return ResponseEntity.ok().body(accountService.findAccount(Long.parseLong(authentication.getName())));
Long accountId = authenticateUtils.getLongId(authentication);
return ResponseEntity.ok().body(accountService.findAccount(accountId));
}

// 유저 id 뿐만 아니라 발급한 토큰 또한 필요함.
Expand All @@ -49,8 +51,9 @@ public ResponseEntity<?> personalInfo(
@RequestParam String userId,
@RequestParam String stateMsg
) {
accountService.addUserId(Long.parseLong(authentication.getName()), userId);
accountService.addStateMsg(Long.parseLong(authentication.getName()), stateMsg);
Long accountId = authenticateUtils.getLongId(authentication);
accountService.addUserId(accountId, userId);
accountService.addStateMsg(accountId, stateMsg);
return ResponseEntity.ok().build();
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ public class CalenderController {

@GetMapping("{userId}")
public ResponseEntity showCalender(
@PathVariable String userId,
@PathVariable(name = "userId") String userId,
Authentication authentication){

//TODO: 헤더에서 accountId 가져오기
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,21 +6,18 @@
import com.example.HappyNewHere.utils.AuthenticateUtils;
import java.util.List;

import lombok.RequiredArgsConstructor;
import org.springframework.security.core.Authentication;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping(value="/message")
@CrossOrigin
@RequiredArgsConstructor
public class MessageController {
private final MessageService messageService;
private final AuthenticateUtils authenticateUtils;

// 권한들 넣어주셈요
public MessageController(MessageService messageService, AuthenticateUtils authenticateUtils) {
this.messageService = messageService;
this.authenticateUtils = authenticateUtils;
}

@PostMapping("/create")
public MessageDto createMessage(
Expand All @@ -31,23 +28,23 @@ public MessageDto createMessage(
return messageService.createMessage(userId,messageRequestDto);
}

@GetMapping("/read/{userId}")
public List<MessageDto> findAllMessages(@PathVariable String userId) {
return messageService.findAllMessages(userId);
}

@GetMapping("/read/{userId}/{messageId}")
public MessageDto findMessage(@PathVariable String userId, @PathVariable Long messageId) {
return messageService.findOneMessage(messageId);
}

@PutMapping("/update")
public Long updateMessage(@RequestBody MessageDto messageDto) {
return messageService.updateMessage(messageDto);
}

@DeleteMapping("/delete/{messageId}")
public Long deleteMessage(@PathVariable Long messageId) {
return messageService.deleteMessage(messageId);
}
// @GetMapping("/read/{userId}")
// public List<MessageDto> findAllMessages(@PathVariable String userId) {
// return messageService.findAllMessages(userId);
// }
//
// @GetMapping("/read/{userId}/{messageId}")
// public MessageDto findMessage(@PathVariable String userId, @PathVariable Long messageId) {
// return messageService.findOneMessage(messageId);
// }
//
// @PutMapping("/update")
// public Long updateMessage(@RequestBody MessageDto messageDto) {
// return messageService.updateMessage(messageDto);
// }
//
// @DeleteMapping("/delete/{messageId}")
// public Long deleteMessage(@PathVariable Long messageId) {
// return messageService.deleteMessage(messageId);
// }
}
4 changes: 2 additions & 2 deletions src/main/java/com/example/HappyNewHere/domain/Account.java
Original file line number Diff line number Diff line change
Expand Up @@ -28,8 +28,8 @@ public Account(Long accountId, String nickname, String userId, String profileImg
this.stateMsg = stateMsg;
}

public static Account of(Long accountId, AccountRequestDto accountRequestDto) {
return new Account(accountId, accountRequestDto.nickname(), accountRequestDto.userId(), accountRequestDto.profileImg(), accountRequestDto.stateMsg());
public static Account of(Long accountId, AccountRequestDto accountRequestDto, String profileImg) {
return new Account(accountId, accountRequestDto.nickname(), accountRequestDto.userId(), profileImg, accountRequestDto.stateMsg());
}

public Account(Long accountId) {
Expand Down
37 changes: 15 additions & 22 deletions src/main/java/com/example/HappyNewHere/domain/Messages.java
Original file line number Diff line number Diff line change
Expand Up @@ -14,38 +14,31 @@

@Entity
@Data
@NoArgsConstructor
public class Messages {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long messageId;
private LocalDateTime createdDate;
private String context;
private String sender; // SenderUserId
private String receiver; // ReciverUserId
private Long sender; // kakooId
private Long receiver; //kakaoid
private int paperNum;
private boolean anonymous;

// dto -> entity
public Messages(MessageDto messageDto) {
this.messageId = messageDto.getMessageId();
this.createdDate = messageDto.getCreatedDate();
this.context = messageDto.getContext();
this.sender = messageDto.getSender();
this.receiver = messageDto.getReceiver();
this.paperNum = messageDto.getPaperNum();
this.anonymous = messageDto.isAnonymous(); // 왜 바로접근가능??
}

private Messages() {
}
private Messages(LocalDateTime createdDate, String context, Long sender, Long receiver, int paperNum, boolean anonymous) {
this.createdDate = createdDate;
this.context = context;
this.sender = sender;
this.receiver = receiver;
this.paperNum = paperNum;
this.anonymous = anonymous;
}

// patch로 변경 ..?
public void update(MessageDto messageDto) {
this.messageId = messageDto.getMessageId();
this.createdDate = messageDto.getCreatedDate();
this.context = messageDto.getContext();
this.sender = messageDto.getSender();
this.receiver = messageDto.getReceiver();
this.paperNum = messageDto.getPaperNum();
this.anonymous = messageDto.isAnonymous();
public static Messages of(LocalDateTime createdDate, String context, Long sender, Long receiver, int paperNum, boolean anonymous) {
return new Messages( createdDate, context, sender, receiver, paperNum, anonymous);
}

}
26 changes: 15 additions & 11 deletions src/main/java/com/example/HappyNewHere/dto/MessageDto.java
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,10 @@
import com.example.HappyNewHere.domain.Messages;
import java.time.LocalDateTime;
import lombok.Data;
import lombok.NoArgsConstructor;

@Data
@NoArgsConstructor
public class MessageDto {
private Long messageId;
private LocalDateTime createdDate;
Expand All @@ -13,17 +16,6 @@ public class MessageDto {
private int paperNum;
private boolean anonymous;

// entity -> dto
public MessageDto(Messages messages) {
this.messageId = messages.getMessageId();
this.createdDate = messages.getCreatedDate();
this.context = messages.getContext();
this.sender = messages.getSender();
this.receiver = messages.getReceiver();
this.paperNum = messages.getPaperNum();
this.anonymous = messages.isAnonymous();
}

public MessageDto(Long messageId, LocalDateTime createdDate, String context, String sender, String receiver,
int paperNum, boolean anonymous) {
this.messageId = messageId;
Expand All @@ -34,4 +26,16 @@ public MessageDto(Long messageId, LocalDateTime createdDate, String context, Str
this.paperNum = paperNum;
this.anonymous = anonymous;
}

public static MessageDto from(Messages messages,String sender,String receiver) {
return new MessageDto(
messages.getMessageId(),
messages.getCreatedDate(),
messages.getContext(),
sender,
receiver,
messages.getPaperNum(),
messages.isAnonymous()
);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -12,18 +12,18 @@ public class MessageRequestDto {
private boolean anonymous;

// entity -> dto
public MessageRequestDto(Messages messages) {
this.context = messages.getContext();
this.receiver = messages.getReceiver();
this.paperNum = messages.getPaperNum();
this.anonymous = messages.isAnonymous();
}

public MessageRequestDto(String context, String receiver,
int paperNum, boolean anonymous) {
this.context = context;
this.receiver = receiver;
this.paperNum = paperNum;
this.anonymous = anonymous;
}
// public MessageRequestDto(Messages messages) {
// this.context = messages.getContext();
// this.receiver = messages.getReceiver();
// this.paperNum = messages.getPaperNum();
// this.anonymous = messages.isAnonymous();
// }
//
// public MessageRequestDto(String context, String receiver,
// int paperNum, boolean anonymous) {
// this.context = context;
// this.receiver = receiver;
// this.paperNum = paperNum;
// this.anonymous = anonymous;
// }
}
Original file line number Diff line number Diff line change
Expand Up @@ -13,10 +13,10 @@ public record MsgResponseDto(
boolean anonymous,
LocalDateTime day
) {
public static MsgResponseDto of(Messages messages, String senderNickname){
public static MsgResponseDto of(Messages messages,String senderUserId, String senderNickname){
return new MsgResponseDto(
messages.getContext(),
messages.getSender(),
senderUserId,
senderNickname,
messages.getPaperNum(),
messages.isAnonymous(),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
public enum ErrorCode {
USER_NOT_FOUND(400,HttpStatus.NOT_FOUND, "유저를 찾을 수 없습니다"),
INVALID_PERMISSION(401,HttpStatus.UNAUTHORIZED, "권한이 없습니다"),
DUPLICATED_USER_NAME(400,HttpStatus.CONFLICT, "유저명이 중복됩니다"),
DUPLICATED_USER_NAME(400,HttpStatus.CONFLICT, "유저명이 중복되거나 null일 수 있습니다."),
DATABASE_ERROR(400,HttpStatus.INTERNAL_SERVER_ERROR, "DB에러가 발생하였습니다");
private int status;
private HttpStatus error;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,5 +8,5 @@

@Repository
public interface MessageRepository extends JpaRepository<Messages, Long> {
List<Messages> findByReceiver(String receiver);
List<Messages> findByReceiver(Long receiver);
}
38 changes: 20 additions & 18 deletions src/main/java/com/example/HappyNewHere/service/AccountService.java
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ public class AccountService {
private final AccountRepository accountRepository;
@Value("${jwt.secret}")
private String secretKey;
private Long expiredMs = 1000*60*60L; //한시간
private Long expiredMs = 1000*60*60*24L; //한시간

@Transactional
public Account save(AccountDto accountDto) {
Expand All @@ -50,7 +50,7 @@ public AccountDto addUserId(Long accountId, String userId) {
if(!account.isPresent())
throw new HappyException(ErrorCode.USER_NOT_FOUND);

if(!checkUserId(userId))
if(!checkUserId(userId,account.get()))
throw new HappyException(ErrorCode.DUPLICATED_USER_NAME);

account.get().setUserId(userId);
Expand All @@ -74,8 +74,10 @@ public String saveAccount(UserInfo userInfo){
account.setNickname(userInfo.getProperties().getNickname());

if (userInfo.getProperties().getProfile_image().equals("http://k.kakaocdn.net/dn/1G9kp/btsAot8liOn/8CWudi3uy07rvFNUkk3ER0/img_640x640.jpg")){

account.setProfileImg("https://dang-na-dong.s3.ap-northeast-2.amazonaws.com/Snowman.png");
if (Math.random()>=0.5)
account.setProfileImg("https://dang-na-dong.s3.ap-northeast-2.amazonaws.com/Snowman.png");
else
account.setProfileImg("https://dang-na-dong.s3.ap-northeast-2.amazonaws.com/Presents.png");
}
else{
account.setProfileImg(userInfo.getProperties().getProfile_image());
Expand Down Expand Up @@ -104,23 +106,23 @@ public AccountDto updateAccount(Long accountId, AccountRequestDto accountRequest
Optional<Account> account = accountRepository.findById(accountId);
if(!account.isPresent())
throw new HappyException(ErrorCode.USER_NOT_FOUND);
if(!checkUserId(accountRequestDto.userId()))
//중복된 유저 확인
if(!checkUserId(accountRequestDto.userId(),account.get()))
throw new HappyException(ErrorCode.DUPLICATED_USER_NAME);
// 있다면 userId가 동일한지 확인하고 다르다면 예외 반환
if(!account.get().getUserId().equals(accountRequestDto.userId()))
throw new HappyException(ErrorCode.INVALID_PERMISSION);
// 이미 존재하는 유저이며, userId가 동일하다면 해당 유저의 정보를 수정한다.
return AccountDto.from(accountRepository.save(Account.of(accountId, accountRequestDto)));

return AccountDto.from(accountRepository.save(Account.of(accountId, accountRequestDto, account.get().getProfileImg())));
}

//userId 중복체크
public boolean checkUserId(String userId){
if(userId.equals(null) || userId.equals("")){
return true;
}
if (accountRepository.findByUserId(userId).isPresent()) {
//수정될userId 중복체크
public boolean checkUserId(String userId, Account owner){
if(userId==null || userId.equals(""))
return false;
}
return true;
Optional<Account> account = accountRepository.findByUserId(userId);
if (account.isEmpty())
return true;
if(owner.getUserId().equals(userId))
return true;

return false;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@
import com.example.HappyNewHere.domain.Messages;
import com.example.HappyNewHere.dto.CalenderDto;
import com.example.HappyNewHere.dto.response.MsgResponseDto;
import com.example.HappyNewHere.exception.ErrorCode;
import com.example.HappyNewHere.exception.HappyException;
import com.example.HappyNewHere.repository.AccountRepository;
import com.example.HappyNewHere.repository.CalenderRepository;
import com.example.HappyNewHere.repository.MessageRepository;
Expand Down Expand Up @@ -42,19 +44,20 @@ public CalenderDto showCalender(Long accountId, String userId){
else calenderDto.setOwner(false);

//3. 메세지 목록 담기(일치하는 멤버가 아니거나 25일이 아니면 null로 두기)
LocalDateTime now = LocalDateTime.now();
if(calenderDto.isOwner()
//&& now.getYear()==2024
// && LocalDateTime.now().getYear()==2024
){
List<Messages> messages = messageRepository.findByReceiver(userId);
List<Messages> messages = messageRepository.findByReceiver(viewer.get().getAccountId());
for(Messages msg : messages){
calenderDto.getMessagesList().add(toMsgDto(msg));
}
}
return calenderDto;
}
public MsgResponseDto toMsgDto(Messages messages){
return MsgResponseDto.of(messages,accountRepository.findByUserId(messages.getSender()).get().getNickname());
Optional<Account> account = accountRepository.findById(messages.getSender());
if (account.isEmpty()) throw new HappyException(ErrorCode.USER_NOT_FOUND);
return MsgResponseDto.of(messages,account.get().getUserId(),account.get().getNickname());
}


Expand Down
Loading

0 comments on commit b1fa934

Please sign in to comment.