Skip to content

Commit

Permalink
feat: ✨ 인가 서비스 추가 (#22)
Browse files Browse the repository at this point in the history
* fix: 🐛 빠진 코드 추가

* fix: 🐛 email 칼럼 다시 추가

* feat: ✨ 인가 서비스 추가 (#21)
  • Loading branch information
LEEJaeHyeok97 authored Sep 27, 2024
1 parent fe06e3c commit 9317289
Show file tree
Hide file tree
Showing 7 changed files with 52 additions and 15 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -20,11 +20,12 @@ public class CalendarService {
private final UserRepository userRepository;


public CheckGoalProgressResponse searchCheckGoalProgress(Long userId, YearMonth date) {
User user = userRepository.findById(userId)
public CheckGoalProgressResponse searchCheckGoalProgress(String username, YearMonth date) {
System.out.println("username = " + username);
User user = userRepository.findByUsername(username)
.orElseThrow(() -> new EntityNotFoundException("User not found"));

CheckGoalProgressResponse checkGoalProgressResponse = calendarRepository.findByIdAndDate(userId, date);
CheckGoalProgressResponse checkGoalProgressResponse = calendarRepository.findByIdAndDate(user.getId(), date);

return checkGoalProgressResponse;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,8 @@ public CheckGoalProgressResponse findByIdAndDate(Long userId, YearMonth date) {
calendar.date.between(startDate, endDate)
)
.fetch();



String goal = userInfo.getGoal();

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
package com.goormdari.domain.calendar.exception;

public class InvalidTokenException extends RuntimeException {
public InvalidTokenException() {
super("토큰이 비어있습니다.");
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@

import com.goormdari.domain.calendar.application.CalendarService;
import com.goormdari.domain.calendar.dto.response.CheckGoalProgressResponse;
import com.goormdari.domain.calendar.exception.InvalidTokenException;
import com.goormdari.global.config.security.jwt.JWTUtil;
import com.goormdari.global.payload.ErrorResponse;
import com.goormdari.global.payload.ResponseCustom;
import io.swagger.v3.oas.annotations.Operation;
Expand All @@ -25,6 +27,8 @@ public class CalendarController {
// 마이페이지-목표점검 부분 api 입니다.
private final CalendarService calendarService;

private final JWTUtil jwtUtil;


@Operation(summary = "목표 점검 화면 조회", description = "목표 점검 화면을 조회합니다.")
@ApiResponses(value = {
Expand All @@ -33,10 +37,20 @@ public class CalendarController {
})
@GetMapping("/{date}")
public ResponseCustom<CheckGoalProgressResponse> checkGoalProgress(
@Parameter(description = "Accesstoken을 입력해주세요.", required = true) @RequestHeader Long userId,
@Parameter(description = "Accesstoken을 입력해주세요.", required = true) @RequestHeader("Authorization") String token,
@Parameter(description = "조회할 날짜를 입력해주세요.(ex. 2024-08)", required = false) @PathVariable(required = false) YearMonth date
) {
return ResponseCustom.OK(calendarService.searchCheckGoalProgress(userId, date));

if (token == null) {
throw new InvalidTokenException();
}

String jwt = token.startsWith("Bearer ") ? token.substring(7) : token;
if (!jwtUtil.validateToken(jwt)) {
throw new IllegalArgumentException("Invalid token");
}
String username = jwtUtil.extractUsername(jwt);
return ResponseCustom.OK(calendarService.searchCheckGoalProgress(username, date));
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -28,8 +28,8 @@ public class TeamService {


@Transactional
public CreateTeamResponse createNewTeam(final Long userId, final CreateTeamRequest createTeamRequest) {
User user = userRepository.findById(userId)
public CreateTeamResponse createNewTeam(final String username, final CreateTeamRequest createTeamRequest) {
User user = userRepository.findByUsername(username)
.orElseThrow(() -> new NotFoundException("User not found"));

if (user.getTeam() != null) {
Expand Down Expand Up @@ -61,15 +61,15 @@ public CreateTeamResponse createNewTeam(final Long userId, final CreateTeamReque
}


public Message sendCode(Long userId, Long guestId) {
public Message sendCode(String username, Long guestId) {

User hostUser = userRepository.findById(userId)
User hostUser = userRepository.findByUsername(username)
.orElseThrow(() -> new NotFoundException("User not found"));

User guestUser = userRepository.findById(guestId)
.orElseThrow(() -> new NotFoundException("Guest not found"));

String joinCode = userRepository.findJoinCodeByUserId(userId);
String joinCode = userRepository.findJoinCodeByUserId(hostUser.getId());

emailClient.sendOneEmail(hostUser.getNickname(), guestUser.getEmail(), joinCode);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
import com.goormdari.domain.team.application.TeamService;
import com.goormdari.domain.team.dto.request.CreateTeamRequest;
import com.goormdari.domain.team.dto.response.CreateTeamResponse;
import com.goormdari.global.config.security.jwt.JWTUtil;
import com.goormdari.global.payload.ErrorResponse;
import com.goormdari.global.payload.Message;
import com.goormdari.global.payload.ResponseCustom;
Expand All @@ -25,17 +26,24 @@ public class TeamController {

private final TeamService teamService;

private final JWTUtil jwtUtil;

@Operation(summary = "팀(방) 생성", description = "팀(방)을 생성합니다.")
@ApiResponses(value = {
@ApiResponse(responseCode = "200", description = "팀(방) 생성 성공", content = {@Content(mediaType = "application/json", schema = @Schema(implementation = CreateTeamResponse.class))}),
@ApiResponse(responseCode = "400", description = "팀(방) 생성 실패", content = {@Content(mediaType = "application/json", schema = @Schema(implementation = ErrorResponse.class))}),
})
@PostMapping
public ResponseCustom<CreateTeamResponse> createTeam(
@Parameter(description = "Accesstoken을 입력해주세요.", required = true) @RequestHeader Long userId,
@Parameter(description = "Accesstoken을 입력해주세요.", required = true) @RequestHeader("Authorization") String token,
@Parameter(description = "Schemas의 CreateTeamRequest를 참고해주세요.", required = true) @Valid @RequestBody CreateTeamRequest createTeamRequest
) {
return ResponseCustom.OK(teamService.createNewTeam(userId, createTeamRequest));
String jwt = token.startsWith("Bearer ") ? token.substring(7) : token;
if (!jwtUtil.validateToken(jwt)) {
throw new IllegalArgumentException("Invalid token");
}
String username = jwtUtil.extractUsername(jwt);
return ResponseCustom.OK(teamService.createNewTeam(username, createTeamRequest));
}

@Operation(summary = "팀(방) 참여코드 전달", description = "팀(방) 참여코드를 이메일로 전달합니다.")
Expand All @@ -45,9 +53,14 @@ public ResponseCustom<CreateTeamResponse> createTeam(
})
@PostMapping("/email/{guestId}")
public ResponseCustom<Message> sendJoinCode(
@Parameter(description = "Accesstoken을 입력해주세요.", required = true) @RequestHeader Long userId,
@Parameter(description = "Accesstoken을 입력해주세요.", required = true) @RequestHeader("Authorization") String token,
@Parameter(description = "초대할 유저의 id를 입력해주세요.", required = true) @PathVariable Long guestId
) {
return ResponseCustom.OK(teamService.sendCode(userId, guestId));
String jwt = token.startsWith("Bearer ") ? token.substring(7) : token;
if (!jwtUtil.validateToken(jwt)) {
throw new IllegalArgumentException("Invalid token");
}
String username = jwtUtil.extractUsername(jwt);
return ResponseCustom.OK(teamService.sendCode(username, guestId));
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ public String generateToken(String username, String role) {
}

public String extractUsername(String token) {
return extractClaim(token, Claims::getSubject);
return extractClaim(token, claims -> claims.get("username", String.class));
}

public <T> T extractClaim(String token, Function<Claims, T> claimsResolver) {
Expand Down

0 comments on commit 9317289

Please sign in to comment.