Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

HF-85 User, Auth Controller, Service 작성 #17

Merged
merged 15 commits into from
Jul 21, 2024
Merged
Show file tree
Hide file tree
Changes from 11 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
14 changes: 14 additions & 0 deletions src/main/java/gible/domain/auth/controller/AuthController.java
Original file line number Diff line number Diff line change
@@ -1,12 +1,16 @@
package gible.domain.auth.controller;


import gible.domain.auth.dto.RenewTokenReq;
import gible.domain.auth.dto.SignInReq;
import gible.domain.auth.dto.SignInRes;
import gible.domain.auth.service.AuthService;
import gible.domain.security.common.SecurityUserDetails;
import gible.global.util.api.SuccessRes;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
Expand All @@ -23,4 +27,14 @@ public ResponseEntity<SignInRes> login(@Valid @RequestBody SignInReq signInReq)
return ResponseEntity.ok().body(authService.login(signInReq));
}

@PostMapping("logout")
public ResponseEntity<?> logout(@AuthenticationPrincipal SecurityUserDetails userDetails){
authService.logout(userDetails.getId());
return ResponseEntity.ok().body(SuccessRes.from("로그아웃 성공"));
}
@PostMapping("/token")
public ResponseEntity<?> renewToken(@Valid @RequestBody RenewTokenReq renewTokenReq) {
return ResponseEntity.ok().body(authService.renewToken(renewTokenReq));
}

Tentennball marked this conversation as resolved.
Show resolved Hide resolved
}
9 changes: 9 additions & 0 deletions src/main/java/gible/domain/auth/dto/RenewTokenReq.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
package gible.domain.auth.dto;

import jakarta.validation.constraints.NotBlank;

public record RenewTokenReq (
@NotBlank(message = "리프레시 토큰은 필수 작성 항목입니다.")
String RefreshToken
){
}
25 changes: 22 additions & 3 deletions src/main/java/gible/domain/auth/service/AuthService.java
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package gible.domain.auth.service;

import gible.domain.auth.dto.KakaoUserInfo;
import gible.domain.auth.dto.RenewTokenReq;
import gible.domain.auth.dto.SignInReq;

import gible.domain.auth.dto.SignInRes;
Expand All @@ -12,6 +13,8 @@
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.UUID;

@Service
@RequiredArgsConstructor
public class AuthService {
Expand All @@ -24,14 +27,30 @@ public SignInRes login(SignInReq signInReq) {
if(user == null) {
throw new CustomException(ErrorType.NEED_SIGNUP);
}
String accessToken = jwtTokenProvider.generateAccessToken(user);
String refreshToken = jwtTokenProvider.generateRefreshToken(user);
return generateSignInRes(user);
}

return SignInRes.of(accessToken, refreshToken);
public SignInRes renewToken(RenewTokenReq renewTokenReq){
UUID uuid = UUID.randomUUID(); //레디스 로직수정필요
User user = userService.findById(uuid); //레디스 로직수정필요
return generateSignInRes(user);
}


private KakaoUserInfo getUserInfo(SignInReq signInReq) {
String accessToken = kakaoService.getAccessToken(signInReq);
return kakaoService.getUserInfo(accessToken);
}
public void logout(UUID userId) {
userService.deleteById(userId);
//레디스 리프레시토큰 삭제 로직
}
Tentennball marked this conversation as resolved.
Show resolved Hide resolved

private SignInRes generateSignInRes(User user){
String accessToken = jwtTokenProvider.generateAccessToken(user);
String refreshToken = jwtTokenProvider.generateRefreshToken(user);

return SignInRes.of(accessToken, refreshToken);
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,8 @@
import gible.domain.donation.dto.DonationReq;
import gible.domain.donation.dto.DonationSenderInfoRes;
import gible.domain.donation.service.DonationService;
import gible.global.util.api.SuccessRes;
import gible.domain.security.common.SecurityUserDetails;
import gible.global.util.api.ApiUtil;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import org.springframework.http.ResponseEntity;
Expand All @@ -28,7 +28,7 @@ public ResponseEntity<?> donate(@Valid @RequestBody DonationReq donationReq,
@AuthenticationPrincipal SecurityUserDetails userDetails) {

donationService.donate(donationReq, userDetails.getId(), postId);
return ResponseEntity.ok(ApiUtil.from("기부 성공."));
return ResponseEntity.ok(SuccessRes.from("기부 성공."));
}

/* 게시글에 대한 기부자 목록 불러오기 */
Expand Down
11 changes: 6 additions & 5 deletions src/main/java/gible/domain/event/controller/EventController.java
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
import gible.domain.event.dto.EventReq;
import gible.domain.event.dto.EventSummaryRes;
import gible.domain.event.service.EventService;
import gible.global.util.api.ApiUtil;
import gible.global.util.api.SuccessRes;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import org.springframework.data.domain.Page;
Expand All @@ -19,7 +19,8 @@
@RequiredArgsConstructor
@RequestMapping("/event")
@RestController
public class EventController {
public class
EventController {

private final EventService eventService;

Expand All @@ -28,7 +29,7 @@ public class EventController {
public ResponseEntity<?> saveEvent(@Valid @RequestBody EventReq eventReq) {

eventService.saveEvent(eventReq);
return ResponseEntity.created(null).body(ApiUtil.from("이벤트 작성 성공."));
return ResponseEntity.created(null).body(SuccessRes.from("이벤트 작성 성공."));
}

/* 이벤트 목록 조회 */
Expand All @@ -52,14 +53,14 @@ public ResponseEntity<?> updateEvent(@Valid @RequestBody EventReq updateEventReq
@PathVariable UUID eventId) {

eventService.updateEvent(updateEventReq, eventId);
return ResponseEntity.ok(ApiUtil.from("이벤트 수정 성공."));
return ResponseEntity.ok(SuccessRes.from("이벤트 수정 성공."));
}

/* 이벤트 삭제 */
@DeleteMapping("/{eventId}")
public ResponseEntity<?> deleteEvent(@PathVariable UUID eventId) {

eventService.deleteEvent(eventId);
return ResponseEntity.ok(ApiUtil.from("이벤트 삭제 성공."));
return ResponseEntity.ok(SuccessRes.from("이벤트 삭제 성공."));
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,8 @@
import gible.domain.post.dto.PostReq;
import gible.domain.post.dto.PostSummaryRes;
import gible.domain.post.service.PostService;
import gible.global.util.api.SuccessRes;
import gible.domain.security.common.SecurityUserDetails;
import gible.global.util.api.ApiUtil;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import org.springframework.data.domain.Page;
Expand All @@ -31,7 +31,7 @@ public ResponseEntity<?> savePost(@Valid @RequestBody PostReq postReq,
@AuthenticationPrincipal SecurityUserDetails userDetails) {

postService.savePost(postReq, userDetails.getId());
return ResponseEntity.created(null).body(ApiUtil.from("게시글 업로드 완료."));
return ResponseEntity.created(null).body(SuccessRes.from("게시글 업로드 완료."));
}

/* 게시글 목록 조회 + 검색 조회 */
Expand Down Expand Up @@ -59,15 +59,15 @@ public ResponseEntity<?> updatePost(@Valid @RequestBody PostReq postReq,
@PathVariable UUID postId) {

postService.updatePost(postReq, postId);
return ResponseEntity.ok(ApiUtil.from("게시글 수정 완료."));
return ResponseEntity.ok(SuccessRes.from("게시글 수정 완료."));
}

/* 게시글 삭제 */
@DeleteMapping("/{postId}")
public ResponseEntity<?> deletePost(@PathVariable UUID postId) {

postService.deletePost(postId);
return ResponseEntity.ok(ApiUtil.from("게시글 삭제 완료."));
return ResponseEntity.ok(SuccessRes.from("게시글 삭제 완료."));
}
}

Expand Down
Empty file.
40 changes: 40 additions & 0 deletions src/main/java/gible/domain/user/controller/UserController.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
package gible.domain.user.controller;

import gible.domain.event.dto.EventSummaryRes;
import gible.domain.security.common.SecurityUserDetails;
import gible.domain.user.dto.MyPageRes;
import gible.domain.user.dto.SignUpReq;
import gible.domain.user.service.UserService;
import gible.global.util.api.SuccessRes;
import lombok.RequiredArgsConstructor;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequiredArgsConstructor
@RequestMapping("/user")
public class UserController {
private final UserService userService;

@PostMapping("/signUp")
public ResponseEntity<?> SignUp(@RequestBody SignUpReq signUpReq){
userService.signUp(signUpReq);
return ResponseEntity.ok().body(SuccessRes.from("회원가입 성공"));
}
@GetMapping("")
public ResponseEntity<MyPageRes> getMyPage(
@AuthenticationPrincipal SecurityUserDetails userDetails
){
return ResponseEntity.ok().body(userService.getMyPage(userDetails.getId()));
}

@GetMapping("/participation-event")
public ResponseEntity<List<EventSummaryRes>> getParticipationEvent(
@AuthenticationPrincipal SecurityUserDetails userDetails
){
return ResponseEntity.ok().body(userService.getParticipationEvents(userDetails.getId()));
}
Tentennball marked this conversation as resolved.
Show resolved Hide resolved
}
11 changes: 11 additions & 0 deletions src/main/java/gible/domain/user/dto/MyPageRes.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
package gible.domain.user.dto;

public record MyPageRes(
String email,
String nickname,
int point
) {
public static MyPageRes of(final String email, final String nickname, final int point) {
return new MyPageRes(email, nickname, point);
}
}
8 changes: 4 additions & 4 deletions src/main/java/gible/domain/user/dto/SignUpReq.java
Original file line number Diff line number Diff line change
Expand Up @@ -5,13 +5,13 @@
import jakarta.validation.constraints.NotBlank;

public record SignUpReq(
@NotBlank
@NotBlank(message = "닉네임 입력은 필수입니다.")
String nickname,
@NotBlank
@NotBlank(message = "이메일 입력은 필수입니다.")
String email,
@NotBlank
@NotBlank(message = "이름 입력은 필수입니다.")
String name,
@NotBlank
@NotBlank(message = "전화번호 입력은 필수입니다.")
Tentennball marked this conversation as resolved.
Show resolved Hide resolved
String phoneNumber,
String role
) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,4 +8,6 @@

public interface UserRepository extends JpaRepository<User, UUID> {
Optional<User> findByEmail(String email);

boolean existsByEmail(String email);
}
42 changes: 39 additions & 3 deletions src/main/java/gible/domain/user/service/UserService.java
Original file line number Diff line number Diff line change
@@ -1,24 +1,60 @@
package gible.domain.user.service;

import gible.domain.event.dto.EventSummaryRes;
import gible.domain.participate.entity.Participate;
import gible.domain.participate.repository.ParticipateRepository;
import gible.domain.user.dto.MyPageRes;
import gible.domain.user.dto.SignUpReq;
import gible.domain.user.entity.User;
import gible.domain.user.repository.UserRepository;
import gible.exception.CustomException;
import gible.exception.error.ErrorType;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.UUID;

@Service
@RequiredArgsConstructor
public class UserService {
private final UserRepository userRepository;
private final ParticipateRepository participateRepository;

public User findById(UUID userId){
return userRepository.findById(userId).orElseThrow(()-> new CustomException(ErrorType.USER_NOT_FOUND));
@Transactional(readOnly = true)
public User findById(UUID userId) {
return userRepository.findById(userId).orElseThrow(() -> new CustomException(ErrorType.USER_NOT_FOUND));
}

public User findByEmail(String email){
@Transactional(readOnly = true)
public User findByEmail(String email) {
return userRepository.findByEmail(email).orElse(null);
}

@Transactional(readOnly = true)
public MyPageRes getMyPage(UUID userId) {
User user = findById(userId);
return MyPageRes.of(user.getEmail(), user.getNickname(), user.getPoint());
}

@Transactional(readOnly = true)
public List<EventSummaryRes> getParticipationEvents(UUID userId) {
return participateRepository.findByUser_Id(userId)
.stream().map(Participate::getEvent).toList()
.stream().map(EventSummaryRes::fromEntity).toList();
}

@Transactional
public void deleteById(UUID userId) {
userRepository.deleteById(userId);
}

@Transactional
public void signUp(@Valid SignUpReq signUpReq) {
Tentennball marked this conversation as resolved.
Show resolved Hide resolved
if(userRepository.existsByEmail(signUpReq.email()))
throw new CustomException(ErrorType.ALREADY_EXISTS_USER);
userRepository.save(SignUpReq.toEntity(signUpReq));
}
}
6 changes: 3 additions & 3 deletions src/main/java/gible/exception/GlobalExceptionHandler.java
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
package gible.exception;


import gible.exception.dto.ErrorDto;
import gible.exception.dto.ErrorRes;
import gible.exception.error.ErrorType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
Expand All @@ -25,13 +25,13 @@ public class GlobalExceptionHandler {
public ResponseEntity<?> handle(CustomException ex){
ErrorType errortype = ex.getErrortype();
log.warn("Error occurred : [errorCode={}, message={}]", errortype.getStatus(), errortype.getMessage());
return ResponseEntity.status(errortype.getStatus()).body(ErrorDto.of(errortype.getStatus(), errortype.getMessage()));
return ResponseEntity.status(errortype.getStatus()).body(ErrorRes.of(errortype.getStatus(), errortype.getMessage()));
}

/* 일반 예외 처리 */
@ExceptionHandler
protected ResponseEntity customServerException(Exception ex) {
ErrorDto error = new ErrorDto(INTERNAL_SERVER_ERROR.getStatus(), INTERNAL_SERVER_ERROR.getMessage());
ErrorRes error = new ErrorRes(INTERNAL_SERVER_ERROR.getStatus(), INTERNAL_SERVER_ERROR.getMessage());
log.warn("Error occurred : [errorCode={}, message={}]", error.status(), error.message());
return ResponseEntity.status(error.status()).body(error);
}
Expand Down
11 changes: 0 additions & 11 deletions src/main/java/gible/exception/dto/ErrorDto.java

This file was deleted.

11 changes: 11 additions & 0 deletions src/main/java/gible/exception/dto/ErrorRes.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
package gible.exception.dto;

public record ErrorRes(

int status,
String message
) {
public static ErrorRes of(int status, String message) {
return new ErrorRes(status, message);
}
}
1 change: 1 addition & 0 deletions src/main/java/gible/exception/error/ErrorType.java
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ public enum ErrorType {

// 이미 존재하는 값을 보냈을 때.
ALREADY_PARTICIPATE_POST(409, "이미 해당 이벤트에 참여하였습니다."),
ALREADY_EXISTS_USER(409, "이미 존재하는 유저입니다."),

// 서버 에러
INTERNAL_SERVER_ERROR(500, "서버 에러입니다. 서버 팀에 연락주세요.");
Expand Down
Loading