Skip to content

Commit

Permalink
Merge pull request #57 from softeerbootcamp4th/feat/#49-api
Browse files Browse the repository at this point in the history
Feat/#49 api
  • Loading branch information
wjddn2165 authored Aug 7, 2024
2 parents 41fdc9e + 12ea9cd commit ea74105
Show file tree
Hide file tree
Showing 16 changed files with 202 additions and 206 deletions.
2 changes: 1 addition & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -3,4 +3,4 @@
/Server/build/
/.idea/
/Server/out/
/Server/src/main/resources/application.properties
/Server/src/main/resources/application-local.yml
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
package JGS.CasperEvent.domain.event.controller.adminController;

import JGS.CasperEvent.domain.event.dto.RequestDto.AdminRequestDto;
import JGS.CasperEvent.domain.event.service.AdminService.AdminService;
import jakarta.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
Expand All @@ -17,9 +19,9 @@ public AdminController(AdminService adminService) {
}

@PostMapping("/join")
public ResponseEntity<String> postAdmin(@RequestBody String body){
public ResponseEntity<String> postAdmin(@RequestBody @Valid AdminRequestDto adminRequestDto){
return ResponseEntity
.status(HttpStatus.CREATED)
.body(adminService.postAdmin(body));
.body(adminService.postAdmin(adminRequestDto));
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,10 @@
import JGS.CasperEvent.domain.event.dto.ResponseDto.GetLotteryParticipant;
import JGS.CasperEvent.domain.event.service.RedisService.RedisService;
import JGS.CasperEvent.domain.event.service.eventService.LotteryEventService;
import JGS.CasperEvent.global.entity.BaseUser;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.validation.Valid;
import org.apache.coyote.BadRequestException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
Expand All @@ -32,20 +34,20 @@ public LotteryEventController(LotteryEventService lotteryEventService, RedisServ
@PostMapping
public ResponseEntity<GetCasperBot> postCasperBot(
HttpServletRequest request,
@RequestBody @Valid PostCasperBot postCasperBot) {
String userId = request.getAttribute("userId").toString();
@RequestBody @Valid PostCasperBot postCasperBot) throws BadRequestException {
BaseUser user = (BaseUser) request.getAttribute("user");
return ResponseEntity
.status(HttpStatus.CREATED)
.body(lotteryEventService.postCasperBot(userId, postCasperBot));
.body(lotteryEventService.postCasperBot(user, postCasperBot));
}

// 응모 여부 조회 API
@GetMapping("/applied")
public ResponseEntity<GetLotteryParticipant> GetLotteryParticipant(HttpServletRequest request) throws UserPrincipalNotFoundException {
String userId = request.getAttribute("userId").toString();
BaseUser user = (BaseUser) request.getAttribute("user");
return ResponseEntity
.status(HttpStatus.OK)
.body(lotteryEventService.getLotteryParticipant(userId));
.body(lotteryEventService.getLotteryParticipant(user));
}

// 최근 100개 캐스퍼 봇 조회
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
package JGS.CasperEvent.domain.event.dto.RequestDto;

import jakarta.validation.constraints.NotNull;
import lombok.Getter;

@Getter
public class AdminRequestDto {

@NotNull
private String adminId;

@NotNull
private String password;

}
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package JGS.CasperEvent.domain.event.entity.participants;

import JGS.CasperEvent.global.entity.BaseUser;
import com.fasterxml.jackson.annotation.JsonBackReference;
import jakarta.persistence.*;
import lombok.Getter;

Expand All @@ -13,6 +14,7 @@ public class LotteryParticipants {

@OneToOne
@JoinColumn(name = "base_user_id")
@JsonBackReference
private BaseUser baseUser;

private int linkClickedCount;
Expand All @@ -21,16 +23,22 @@ public class LotteryParticipants {

private Long casperId;

public void updateCasperId(Long casperId){
public void updateCasperId(Long casperId) {
this.casperId = casperId;
}

public LotteryParticipants() {

}

public void expectationAdded(){
public void expectationAdded() {
expectations++;
appliedCount = Math.max(10, appliedCount + 1);
}

public void linkClickedCountAdded() {
linkClickedCount++;
appliedCount = Math.max(10, appliedCount + 1);
}

public LotteryParticipants(BaseUser baseUser) {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,13 +1,12 @@
package JGS.CasperEvent.domain.event.service.AdminService;

import JGS.CasperEvent.domain.event.dto.RequestDto.AdminRequestDto;
import JGS.CasperEvent.domain.event.entity.admin.Admin;
import JGS.CasperEvent.domain.event.repository.AdminRepository;
import JGS.CasperEvent.global.enums.CustomErrorCode;
import JGS.CasperEvent.global.enums.Role;
import JGS.CasperEvent.global.error.exception.CustomException;
import JGS.CasperEvent.global.jwt.dto.AdminLoginDto;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

Expand All @@ -22,14 +21,12 @@ public Admin verifyAdmin(AdminLoginDto adminLoginDto) {
return adminRepository.findById(adminLoginDto.getId()).orElseThrow(NoSuchElementException::new);
}

public String postAdmin(String body) {
public String postAdmin(AdminRequestDto adminRequestDto) {

JsonParser jsonParser = new JsonParser();

JsonObject adminObject = (JsonObject) jsonParser.parse(body);

String adminId = adminObject.get("id").getAsString();
String password = adminObject.get("password").getAsString();
String adminId = adminRequestDto.getAdminId();
//Todo: 비밀번호 암호화 필요
String password = adminRequestDto.getPassword();

Admin admin = adminRepository.findById(adminId).orElse(null);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
import JGS.CasperEvent.global.enums.CustomErrorCode;
import JGS.CasperEvent.global.error.exception.CustomException;
import JGS.CasperEvent.global.jwt.repository.UserRepository;
import org.apache.coyote.BadRequestException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
Expand Down Expand Up @@ -41,10 +42,11 @@ public LotteryEventService(LotteryEventRepository lotteryEventRepository,
this.userRepository = userRepository;
}

public GetCasperBot postCasperBot(String userId, PostCasperBot postCasperBot) throws CustomException {
LotteryParticipants participants = registerUserIfNeed(userId);
public GetCasperBot postCasperBot(BaseUser user, PostCasperBot postCasperBot) throws CustomException, BadRequestException {
LotteryParticipants participants = registerUserIfNeed(user);

CasperBot casperBot = new CasperBot(postCasperBot, participants.getBaseUser().getId());
participants.updateCasperId(casperBot.getCasperId());

if (casperBot.getExpectation() != null) participants.expectationAdded();
lotteryParticipantsRepository.save(participants);
Expand All @@ -55,13 +57,9 @@ public GetCasperBot postCasperBot(String userId, PostCasperBot postCasperBot) th
return casperBotDto;
}


// TODO: 응모 횟수 로직 작성
public GetLotteryParticipant getLotteryParticipant(String userId) throws UserPrincipalNotFoundException {
LotteryParticipants participant = lotteryParticipantsRepository.findById(userId).orElse(null);

if (participant == null) throw new UserPrincipalNotFoundException("응모 내역이 없습니다.");

public GetLotteryParticipant getLotteryParticipant(BaseUser user) throws UserPrincipalNotFoundException {
LotteryParticipants participant = lotteryParticipantsRepository.findByBaseUser(user)
.orElseThrow(() -> new UserPrincipalNotFoundException("응모 내역이 없습니다."));
return GetLotteryParticipant.of(participant, getCasperBot(participant.getCasperId()));
}

Expand All @@ -72,11 +70,18 @@ public GetCasperBot getCasperBot(Long casperId) {
}


public LotteryParticipants registerUserIfNeed(String userId) {
BaseUser baseUser = userRepository.findById(userId).get();
public LotteryParticipants registerUserIfNeed(BaseUser user) {
LotteryParticipants participant = lotteryParticipantsRepository.findByBaseUser(user).orElse(null);

if (participant == null) {
participant = new LotteryParticipants(user);
lotteryParticipantsRepository.save(participant);
}

user.updateLotteryParticipants(participant);
userRepository.save(user);

return lotteryParticipantsRepository.findByBaseUser(baseUser)
.orElseGet(() -> lotteryParticipantsRepository.save(new LotteryParticipants(baseUser)));
return participant;
}

}
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
package JGS.CasperEvent.global.entity;

import JGS.CasperEvent.domain.event.entity.participants.LotteryParticipants;
import JGS.CasperEvent.domain.event.entity.participants.RushParticipants;
import JGS.CasperEvent.global.enums.Role;
import com.fasterxml.jackson.annotation.JsonManagedReference;
import jakarta.persistence.*;
import lombok.Getter;

Expand All @@ -14,11 +14,13 @@ public class BaseUser extends BaseEntity {
String id;
Role role;

@JsonManagedReference
@OneToOne(mappedBy = "baseUser", cascade = CascadeType.ALL)
private LotteryParticipants lotteryParticipants;

@OneToOne(mappedBy = "baseUser", cascade = CascadeType.ALL)
private RushParticipants rushParticipants;
public void updateLotteryParticipants(LotteryParticipants lotteryParticipant) {
this.lotteryParticipants = lotteryParticipant;
}

public BaseUser(String id, Role role) {
this.id = id;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,8 @@ public enum CustomErrorCode {
CONFLICT("이미 존재하는 ID입니다.", 409),
JWT_PARSE_EXCEPTION("Json 파싱 오류입니다.", 400),
JWT_EXCEPTION("JWT 오류입니다.", 400),
JWT_EXPIRED("만료된 토큰입니다.", 400);
JWT_EXPIRED("만료된 토큰입니다.", 400),
JWT_MISSING("인증 토큰이 존재하지 않습니다.", 401);



Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@
@RequiredArgsConstructor
public class JwtAuthorizationFilter implements Filter {

private final String[] whiteListUris = new String[]{"/event/auth", "/event/rush", "/event/lottery/caspers", "/admin/join", "/admin/auth", "/h2", "/h2/*", "/swagger-ui/*", "/v3/api-docs", "/v3/api-docs/*"};
private final String[] whiteListUris = new String[]{"/health, /event/auth", "/event/rush", "/event/lottery/caspers", "/admin/join", "/admin/auth", "/h2", "/h2/*", "/swagger-ui/*", "/v3/api-docs", "/v3/api-docs/*"};
private final String[] blackListUris = new String[]{"/event/rush/*"};

private final JwtProvider jwtProvider;
Expand All @@ -47,7 +47,7 @@ public void doFilter(ServletRequest request, ServletResponse response, FilterCha
}

if (!isContainToken(httpServletRequest)) {
httpServletResponse.sendError(HttpStatus.UNAUTHORIZED.value(), "인증 오류");
sendError(httpServletResponse, CustomErrorCode.JWT_MISSING);
return;
}

Expand Down Expand Up @@ -107,7 +107,7 @@ private void sendError(HttpServletResponse response, CustomErrorCode errorCode)
ErrorResponse errorResponse = new ErrorResponse(errorCode, errorCode.getMessage());
String jsonResponse = objectMapper.writeValueAsString(errorResponse);

response.setContentType("application/json");
response.setContentType("application/json; charset=UTF-8");
response.setStatus(errorCode.getStatus());
response.getWriter().write(jsonResponse);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -28,9 +28,7 @@ public void doFilter(ServletRequest request, ServletResponse response, FilterCha
try {
UserLoginDto userLoginDto = objectMapper.readValue(request.getReader(), UserLoginDto.class);
BaseUser user = userService.verifyUser(userLoginDto);

request.setAttribute(AUTHENTICATE_USER, user);

chain.doFilter(request, response);
} catch (Exception e) {
log.error("Fail User Verify");
Expand Down
19 changes: 0 additions & 19 deletions Server/src/main/resources/application-local.yml

This file was deleted.

Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,9 @@
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.filter.CharacterEncodingFilter;
Expand All @@ -14,7 +16,9 @@
import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;

@WebMvcTest(HealthController.class)
@SpringBootTest
@AutoConfigureMockMvc
@ActiveProfiles("local")
class CasperEventApplicationTests {
@Autowired
private MockMvc mockMvc;
Expand All @@ -33,7 +37,7 @@ public void setup(){
void HealthTest() throws Exception {
mockMvc.perform(get("/health"))
.andExpect(status().isOk())
.andExpect(content().string("true"))
.andExpect(content().string("Server OK"))
.andDo(print());

}
Expand Down
Binary file not shown.
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ void createAdminSuccessTest() throws Exception {
""", adminId);

//when
ResultActions perform = mockMvc.perform(post("/admin/auth")
ResultActions perform = mockMvc.perform(post("/admin/join")
.contentType(MediaType.APPLICATION_JSON)
.content(adminRequest));

Expand Down
Loading

0 comments on commit ea74105

Please sign in to comment.