diff --git a/src/main/java/com/moabam/admin/application/admin/AdminMapper.java b/src/main/java/com/moabam/admin/application/admin/AdminMapper.java index d9cf0b35..648c2e4d 100644 --- a/src/main/java/com/moabam/admin/application/admin/AdminMapper.java +++ b/src/main/java/com/moabam/admin/application/admin/AdminMapper.java @@ -2,6 +2,10 @@ import com.moabam.admin.domain.admin.Admin; +import lombok.AccessLevel; +import lombok.NoArgsConstructor; + +@NoArgsConstructor(access = AccessLevel.PRIVATE) public class AdminMapper { public static Admin toAdmin(Long socialId) { diff --git a/src/main/java/com/moabam/admin/application/admin/AdminService.java b/src/main/java/com/moabam/admin/application/admin/AdminService.java index 892f15cf..01243bd7 100644 --- a/src/main/java/com/moabam/admin/application/admin/AdminService.java +++ b/src/main/java/com/moabam/admin/application/admin/AdminService.java @@ -4,27 +4,27 @@ import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; import com.moabam.admin.domain.admin.Admin; import com.moabam.admin.domain.admin.AdminRepository; -import com.moabam.api.application.auth.AuthorizationService; import com.moabam.api.application.auth.mapper.AuthMapper; import com.moabam.api.dto.auth.AuthorizationTokenInfoResponse; import com.moabam.api.dto.auth.LoginResponse; import com.moabam.global.error.exception.BadRequestException; +import com.moabam.global.error.exception.NotFoundException; import com.moabam.global.error.model.ErrorMessage; -import jakarta.servlet.http.HttpServletResponse; import lombok.RequiredArgsConstructor; @Service @RequiredArgsConstructor +@Transactional(readOnly = true) public class AdminService { @Value("${admin}") private String adminLoginKey; - private final AuthorizationService authorizationService; private final AdminRepository adminRepository; public void validate(String state) { @@ -33,12 +33,9 @@ public void validate(String state) { } } - public LoginResponse signUpOrLogin(HttpServletResponse httpServletResponse, - AuthorizationTokenInfoResponse authorizationTokenInfoResponse) { - LoginResponse loginResponse = login(authorizationTokenInfoResponse); - authorizationService.issueServiceToken(httpServletResponse, loginResponse.publicClaim()); - - return loginResponse; + @Transactional + public LoginResponse signUpOrLogin(AuthorizationTokenInfoResponse authorizationTokenInfoResponse) { + return login(authorizationTokenInfoResponse); } private LoginResponse login(AuthorizationTokenInfoResponse authorizationTokenInfoResponse) { @@ -53,4 +50,8 @@ private Admin signUp(Long socialId) { return adminRepository.save(admin); } + + public Admin findMember(Long id) { + return adminRepository.findById(id).orElseThrow(() -> new NotFoundException(ErrorMessage.MEMBER_NOT_FOUND)); + } } diff --git a/src/main/java/com/moabam/admin/domain/admin/Admin.java b/src/main/java/com/moabam/admin/domain/admin/Admin.java index d63cbeff..eeff1bc3 100644 --- a/src/main/java/com/moabam/admin/domain/admin/Admin.java +++ b/src/main/java/com/moabam/admin/domain/admin/Admin.java @@ -37,7 +37,7 @@ public class Admin extends BaseTimeEntity { @Enumerated(EnumType.STRING) @Column(name = "role", nullable = false) - @ColumnDefault("'USER'") + @ColumnDefault("'ADMIN'") private Role role; @Builder diff --git a/src/main/java/com/moabam/admin/presentation/admin/AdminController.java b/src/main/java/com/moabam/admin/presentation/admin/AdminController.java index 8ef4354b..cea5bb99 100644 --- a/src/main/java/com/moabam/admin/presentation/admin/AdminController.java +++ b/src/main/java/com/moabam/admin/presentation/admin/AdminController.java @@ -31,9 +31,11 @@ public LoginResponse authorizationTokenIssue(@RequestBody AuthorizationCodeRespo HttpServletResponse httpServletResponse) { adminService.validate(authorizationCodeResponse.state()); AuthorizationTokenResponse tokenResponse = authorizationService.requestAdminToken(authorizationCodeResponse); - AuthorizationTokenInfoResponse authorizationTokenInfoResponse = authorizationService.requestTokenInfo( - tokenResponse); + AuthorizationTokenInfoResponse authorizationTokenInfoResponse = + authorizationService.requestTokenInfo(tokenResponse); + LoginResponse loginResponse = adminService.signUpOrLogin(authorizationTokenInfoResponse); + authorizationService.issueServiceToken(httpServletResponse, loginResponse.publicClaim()); - return adminService.signUpOrLogin(httpServletResponse, authorizationTokenInfoResponse); + return loginResponse; } } diff --git a/src/main/java/com/moabam/api/application/auth/AuthorizationService.java b/src/main/java/com/moabam/api/application/auth/AuthorizationService.java index a2db2e9f..3966d2c4 100644 --- a/src/main/java/com/moabam/api/application/auth/AuthorizationService.java +++ b/src/main/java/com/moabam/api/application/auth/AuthorizationService.java @@ -9,11 +9,13 @@ import org.springframework.util.MultiValueMap; import org.springframework.web.util.UriComponentsBuilder; +import com.moabam.admin.application.admin.AdminService; import com.moabam.api.application.auth.mapper.AuthMapper; import com.moabam.api.application.auth.mapper.AuthorizationMapper; import com.moabam.api.application.member.MemberService; import com.moabam.api.domain.auth.repository.TokenRepository; import com.moabam.api.domain.member.Member; +import com.moabam.api.domain.member.Role; import com.moabam.api.dto.auth.AuthorizationCodeRequest; import com.moabam.api.dto.auth.AuthorizationCodeResponse; import com.moabam.api.dto.auth.AuthorizationTokenInfoResponse; @@ -24,8 +26,9 @@ import com.moabam.api.infrastructure.fcm.FcmService; import com.moabam.global.auth.model.AuthMember; import com.moabam.global.auth.model.PublicClaim; +import com.moabam.global.common.util.CookieUtils; import com.moabam.global.common.util.GlobalConstant; -import com.moabam.global.common.util.cookie.CookieUtils; +import com.moabam.global.config.AllowOriginConfig; import com.moabam.global.config.OAuthConfig; import com.moabam.global.config.TokenConfig; import com.moabam.global.error.exception.BadRequestException; @@ -47,9 +50,10 @@ public class AuthorizationService { private final TokenConfig tokenConfig; private final OAuth2AuthorizationServerRequestService oauth2AuthorizationServerRequestService; private final MemberService memberService; + private final AdminService adminService; private final JwtProviderService jwtProviderService; private final TokenRepository tokenRepository; - private final CookieUtils cookieUtils; + private final AllowOriginConfig allowOriginsConfig; public void redirectToLoginPage(HttpServletResponse httpServletResponse) { String authorizationCodeUri = getAuthorizationCodeUri(); @@ -87,24 +91,25 @@ public LoginResponse signUpOrLogin(HttpServletResponse httpServletResponse, public void issueServiceToken(HttpServletResponse response, PublicClaim publicClaim) { String accessToken = jwtProviderService.provideAccessToken(publicClaim); - String refreshToken = jwtProviderService.provideRefreshToken(); + String refreshToken = jwtProviderService.provideRefreshToken(publicClaim.role()); TokenSaveValue tokenSaveRequest = AuthMapper.toTokenSaveValue(refreshToken, null); - tokenRepository.saveToken(publicClaim.id(), tokenSaveRequest); + tokenRepository.saveToken(publicClaim.id(), tokenSaveRequest, publicClaim.role()); + String domain = getDomain(publicClaim.role()); + + response.addCookie(CookieUtils.typeCookie("Bearer", tokenConfig.getRefreshExpire(), domain)); response.addCookie( - cookieUtils.typeCookie("Bearer", tokenConfig.getRefreshExpire())); - response.addCookie( - cookieUtils.tokenCookie("access_token", accessToken, tokenConfig.getRefreshExpire())); + CookieUtils.tokenCookie("access_token", accessToken, tokenConfig.getRefreshExpire(), domain)); response.addCookie( - cookieUtils.tokenCookie("refresh_token", refreshToken, tokenConfig.getRefreshExpire())); + CookieUtils.tokenCookie("refresh_token", refreshToken, tokenConfig.getRefreshExpire(), domain)); } - public void validTokenPair(Long id, String oldRefreshToken) { - TokenSaveValue tokenSaveValue = tokenRepository.getTokenSaveValue(id); + public void validTokenPair(Long id, String oldRefreshToken, Role role) { + TokenSaveValue tokenSaveValue = tokenRepository.getTokenSaveValue(id, role); if (!tokenSaveValue.refreshToken().equals(oldRefreshToken)) { - tokenRepository.delete(id); + tokenRepository.delete(id, role); throw new UnauthorizedException(ErrorMessage.AUTHENTICATE_FAIL); } @@ -113,7 +118,7 @@ public void validTokenPair(Long id, String oldRefreshToken) { public void logout(AuthMember authMember, HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) { removeToken(httpServletRequest, httpServletResponse); - tokenRepository.delete(authMember.id()); + tokenRepository.delete(authMember.id(), authMember.role()); fcmService.deleteTokenByMemberId(authMember.id()); } @@ -122,12 +127,11 @@ public void removeToken(HttpServletRequest httpServletRequest, HttpServletRespon return; } - Arrays.stream(httpServletRequest.getCookies()) - .forEach(cookie -> { - if (cookie.getName().contains("token")) { - httpServletResponse.addCookie(cookieUtils.deleteCookie(cookie)); - } - }); + Arrays.stream(httpServletRequest.getCookies()).forEach(cookie -> { + if (cookie.getName().contains("token")) { + httpServletResponse.addCookie(CookieUtils.deleteCookie(cookie)); + } + }); } @Transactional @@ -137,12 +141,18 @@ public void unLinkMember(AuthMember authMember) { memberService.delete(member); } + private String getDomain(Role role) { + if (role.equals(Role.ADMIN)) { + return allowOriginsConfig.adminDomain(); + } + + return allowOriginsConfig.domain(); + } + private void unlinkRequest(String socialId) { try { - oauth2AuthorizationServerRequestService.unlinkMemberRequest( - oAuthConfig.provider().unlink(), - oAuthConfig.client().adminKey(), - unlinkRequestParam(socialId)); + oauth2AuthorizationServerRequestService.unlinkMemberRequest(oAuthConfig.provider().unlink(), + oAuthConfig.client().adminKey(), unlinkRequestParam(socialId)); log.info("회원 탈퇴 성공 : [socialId={}]", socialId); } catch (BadRequestException badRequestException) { log.warn("회원 탈퇴요청 실패 : 카카오 연결 오류"); @@ -174,8 +184,7 @@ private String generateQueryParamsWith(AuthorizationCodeRequest authorizationCod .queryParam("client_id", authorizationCodeRequest.clientId()) .queryParam("redirect_uri", authorizationCodeRequest.redirectUri()); - if (authorizationCodeRequest.scope() != null - && !authorizationCodeRequest.scope().isEmpty()) { + if (authorizationCodeRequest.scope() != null && !authorizationCodeRequest.scope().isEmpty()) { String scopes = String.join(",", authorizationCodeRequest.scope()); authorizationCodeUri.queryParam("scope", scopes); } @@ -194,8 +203,8 @@ private AuthorizationTokenResponse issueTokenToAuthorizationServer(String code, oAuthConfig, code, redirectUri); MultiValueMap uriParams = generateTokenRequest(authorizationTokenRequest); ResponseEntity authorizationTokenResponse = - oauth2AuthorizationServerRequestService.requestAuthorizationServer(oAuthConfig.provider().tokenUri(), - uriParams); + oauth2AuthorizationServerRequestService + .requestAuthorizationServer(oAuthConfig.provider().tokenUri(), uriParams); return authorizationTokenResponse.getBody(); } @@ -213,4 +222,14 @@ private MultiValueMap generateTokenRequest(AuthorizationTokenReq return contents; } + + public void validMemberExist(Long id, Role role) { + if (role.equals(Role.ADMIN)) { + adminService.findMember(id); + + return; + } + + memberService.findMember(id); + } } diff --git a/src/main/java/com/moabam/api/application/auth/JwtAuthenticationService.java b/src/main/java/com/moabam/api/application/auth/JwtAuthenticationService.java index eaf1d456..52c652f9 100644 --- a/src/main/java/com/moabam/api/application/auth/JwtAuthenticationService.java +++ b/src/main/java/com/moabam/api/application/auth/JwtAuthenticationService.java @@ -1,11 +1,13 @@ package com.moabam.api.application.auth; import java.nio.charset.StandardCharsets; +import java.security.Key; import org.json.JSONObject; import org.springframework.stereotype.Service; import com.moabam.api.application.auth.mapper.AuthorizationMapper; +import com.moabam.api.domain.member.Role; import com.moabam.global.auth.model.PublicClaim; import com.moabam.global.config.TokenConfig; import com.moabam.global.error.exception.UnauthorizedException; @@ -22,10 +24,12 @@ public class JwtAuthenticationService { private final TokenConfig tokenConfig; - public boolean isTokenExpire(String token) { + public boolean isTokenExpire(String token, Role role) { try { + Key key = getSecret(role); + Jwts.parserBuilder() - .setSigningKey(tokenConfig.getKey()) + .setSigningKey(key) .build() .parseClaimsJws(token); return false; @@ -36,6 +40,14 @@ public boolean isTokenExpire(String token) { } } + private Key getSecret(Role role) { + if (role.equals(Role.ADMIN)) { + return tokenConfig.getAdminKey(); + } + + return tokenConfig.getKey(); + } + public PublicClaim parseClaim(String token) { String claims = token.split("\\.")[1]; byte[] claimsBytes = Decoders.BASE64URL.decode(claims); diff --git a/src/main/java/com/moabam/api/application/auth/JwtProviderService.java b/src/main/java/com/moabam/api/application/auth/JwtProviderService.java index 4ea924dd..816985f2 100644 --- a/src/main/java/com/moabam/api/application/auth/JwtProviderService.java +++ b/src/main/java/com/moabam/api/application/auth/JwtProviderService.java @@ -1,9 +1,11 @@ package com.moabam.api.application.auth; +import java.security.Key; import java.util.Date; import org.springframework.stereotype.Service; +import com.moabam.api.domain.member.Role; import com.moabam.global.auth.model.PublicClaim; import com.moabam.global.config.TokenConfig; @@ -22,23 +24,23 @@ public String provideAccessToken(PublicClaim publicClaim) { return generateIdToken(publicClaim, tokenConfig.getAccessExpire()); } - public String provideRefreshToken() { - return generateCommonInfo(tokenConfig.getRefreshExpire()); + public String provideRefreshToken(Role role) { + return generateCommonInfo(tokenConfig.getRefreshExpire(), role); } private String generateIdToken(PublicClaim publicClaim, long expireTime) { - return commonInfo(expireTime) + return commonInfo(expireTime, publicClaim.role()) .claim("id", publicClaim.id()) .claim("nickname", publicClaim.nickname()) .claim("role", publicClaim.role()) .compact(); } - private String generateCommonInfo(long expireTime) { - return commonInfo(expireTime).compact(); + private String generateCommonInfo(long expireTime, Role role) { + return commonInfo(expireTime, role).compact(); } - private JwtBuilder commonInfo(long expireTime) { + private JwtBuilder commonInfo(long expireTime, Role role) { Date issueDate = new Date(); Date expireDate = new Date(issueDate.getTime() + expireTime); @@ -48,6 +50,14 @@ private JwtBuilder commonInfo(long expireTime) { .setIssuer(tokenConfig.getIss()) .setIssuedAt(issueDate) .setExpiration(expireDate) - .signWith(tokenConfig.getKey(), SignatureAlgorithm.HS256); + .signWith(getSecretKey(role), SignatureAlgorithm.HS256); + } + + private Key getSecretKey(Role role) { + if (role.equals(Role.ADMIN)) { + return tokenConfig.getAdminKey(); + } + + return tokenConfig.getKey(); } } diff --git a/src/main/java/com/moabam/api/application/member/BadgeService.java b/src/main/java/com/moabam/api/application/member/BadgeService.java new file mode 100644 index 00000000..e89dc5dd --- /dev/null +++ b/src/main/java/com/moabam/api/application/member/BadgeService.java @@ -0,0 +1,32 @@ +package com.moabam.api.application.member; + +import java.util.Optional; + +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +import com.moabam.api.domain.member.Badge; +import com.moabam.api.domain.member.BadgeType; +import com.moabam.api.domain.member.repository.BadgeRepository; + +import lombok.RequiredArgsConstructor; + +@Service +@RequiredArgsConstructor +@Transactional(readOnly = true) +public class BadgeService { + + private final BadgeRepository badgeRepository; + + public void createBadge(Long memberId, long certifyCount) { + Optional badgeType = BadgeType.getBadgeFrom(certifyCount); + + if (badgeType.isEmpty() + || badgeRepository.existsByMemberIdAndType(memberId, badgeType.get())) { + return; + } + + Badge badge = MemberMapper.toBadge(memberId, badgeType.get()); + badgeRepository.save(badge); + } +} diff --git a/src/main/java/com/moabam/api/application/member/MemberMapper.java b/src/main/java/com/moabam/api/application/member/MemberMapper.java index 67fd8a92..7d80c808 100644 --- a/src/main/java/com/moabam/api/application/member/MemberMapper.java +++ b/src/main/java/com/moabam/api/application/member/MemberMapper.java @@ -13,6 +13,7 @@ import com.moabam.api.domain.item.Inventory; import com.moabam.api.domain.item.Item; import com.moabam.api.domain.item.ItemType; +import com.moabam.api.domain.member.Badge; import com.moabam.api.domain.member.BadgeType; import com.moabam.api.domain.member.Member; import com.moabam.api.dto.member.BadgeResponse; @@ -96,6 +97,13 @@ public static RankingInfo toRankingInfo(Member member) { .build(); } + public static Badge toBadge(Long memberId, BadgeType badgeType) { + return Badge.builder() + .type(badgeType) + .memberId(memberId) + .build(); + } + private static List badgedNames(Set badgeTypes) { return BadgeType.memberBadgeMap(badgeTypes); } diff --git a/src/main/java/com/moabam/api/application/ranking/RankingMapper.java b/src/main/java/com/moabam/api/application/ranking/RankingMapper.java index 06ad3389..817ccdc8 100644 --- a/src/main/java/com/moabam/api/application/ranking/RankingMapper.java +++ b/src/main/java/com/moabam/api/application/ranking/RankingMapper.java @@ -25,7 +25,7 @@ public static TopRankingInfo topRankingResponse(int rank, long score, RankingInf public static TopRankingInfo topRankingResponse(int rank, UpdateRanking updateRanking) { return TopRankingInfo.builder() - .rank(rank) + .rank(rank + 1) .score(updateRanking.score()) .nickname(updateRanking.rankingInfo().nickname()) .image(updateRanking.rankingInfo().image()) @@ -33,11 +33,7 @@ public static TopRankingInfo topRankingResponse(int rank, UpdateRanking updateRa .build(); } - public static TopRankingResponse topRankingResponses(TopRankingInfo myRanking, - List topRankings) { - return TopRankingResponse.builder() - .topRankings(topRankings) - .myRanking(myRanking) - .build(); + public static TopRankingResponse topRankingResponses(TopRankingInfo myRanking, List topRankings) { + return TopRankingResponse.builder().topRankings(topRankings).myRanking(myRanking).build(); } } diff --git a/src/main/java/com/moabam/api/application/ranking/RankingService.java b/src/main/java/com/moabam/api/application/ranking/RankingService.java index aa48370d..65e620a3 100644 --- a/src/main/java/com/moabam/api/application/ranking/RankingService.java +++ b/src/main/java/com/moabam/api/application/ranking/RankingService.java @@ -35,8 +35,8 @@ public void addRanking(RankingInfo rankingInfo, Long totalCertifyCount) { } public void updateScores(List updateRankings) { - updateRankings.forEach(updateRanking -> - zSetRedisRepository.add(RANKING, updateRanking.rankingInfo(), updateRanking.score())); + updateRankings.forEach( + updateRanking -> zSetRedisRepository.add(RANKING, updateRanking.rankingInfo(), updateRanking.score())); } public void changeInfos(RankingInfo before, RankingInfo after) { @@ -50,15 +50,14 @@ public void removeRanking(RankingInfo rankingInfo) { public TopRankingResponse getMemberRanking(UpdateRanking myRankingInfo) { List topRankings = getTopRankings(); Long myRanking = zSetRedisRepository.reverseRank(RANKING, myRankingInfo.rankingInfo()); - TopRankingInfo myRankingInfoResponse = - RankingMapper.topRankingResponse(myRanking.intValue(), myRankingInfo); + TopRankingInfo myRankingInfoResponse = RankingMapper.topRankingResponse(myRanking.intValue(), myRankingInfo); return RankingMapper.topRankingResponses(myRankingInfoResponse, topRankings); } private List getTopRankings() { - Set> topRankings = - zSetRedisRepository.rangeJson(RANKING, START_INDEX, LIMIT_INDEX); + Set> topRankings = zSetRedisRepository.rangeJson(RANKING, START_INDEX, + LIMIT_INDEX); Set scoreSet = new HashSet<>(); List topRankingInfo = new ArrayList<>(); diff --git a/src/main/java/com/moabam/api/application/room/CertificationService.java b/src/main/java/com/moabam/api/application/room/CertificationService.java index c34c7be5..c4e86434 100644 --- a/src/main/java/com/moabam/api/application/room/CertificationService.java +++ b/src/main/java/com/moabam/api/application/room/CertificationService.java @@ -14,6 +14,7 @@ import org.springframework.transaction.annotation.Transactional; import com.moabam.api.application.bug.BugService; +import com.moabam.api.application.member.BadgeService; import com.moabam.api.application.member.MemberService; import com.moabam.api.application.room.mapper.CertificationsMapper; import com.moabam.api.domain.bug.BugType; @@ -53,6 +54,7 @@ public class CertificationService { private final DailyRoomCertificationRepository dailyRoomCertificationRepository; private final DailyMemberCertificationRepository dailyMemberCertificationRepository; private final MemberService memberService; + private final BadgeService badgeService; private final BugService bugService; private final ClockHolder clockHolder; @@ -139,6 +141,7 @@ private void certifyMember(Long memberId, Long roomId, Participant participant, roomId, participant); dailyMemberCertificationRepository.save(dailyMemberCertification); member.increaseTotalCertifyCount(); + badgeService.createBadge(member.getId(), member.getTotalCertifyCount()); participant.updateCertifyCount(); saveNewCertifications(memberId, urls); diff --git a/src/main/java/com/moabam/api/domain/auth/repository/TokenRepository.java b/src/main/java/com/moabam/api/domain/auth/repository/TokenRepository.java index 3286d0e4..e104dad0 100644 --- a/src/main/java/com/moabam/api/domain/auth/repository/TokenRepository.java +++ b/src/main/java/com/moabam/api/domain/auth/repository/TokenRepository.java @@ -5,6 +5,7 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Repository; +import com.moabam.api.domain.member.Role; import com.moabam.api.dto.auth.TokenSaveValue; import com.moabam.api.infrastructure.redis.HashRedisRepository; @@ -20,23 +21,23 @@ public TokenRepository(HashRedisRepository hashRedisRepository) { this.hashRedisRepository = hashRedisRepository; } - public void saveToken(Long memberId, TokenSaveValue tokenSaveRequest) { - String tokenKey = parseTokenKey(memberId); + public void saveToken(Long memberId, TokenSaveValue tokenSaveRequest, Role role) { + String tokenKey = parseTokenKey(memberId, role); hashRedisRepository.save(tokenKey, tokenSaveRequest, Duration.ofDays(EXPIRE_DAYS)); } - public TokenSaveValue getTokenSaveValue(Long memberId) { - String tokenKey = parseTokenKey(memberId); + public TokenSaveValue getTokenSaveValue(Long memberId, Role role) { + String tokenKey = parseTokenKey(memberId, role); return (TokenSaveValue)hashRedisRepository.get(tokenKey); } - public void delete(Long memberId) { - String tokenKey = parseTokenKey(memberId); + public void delete(Long memberId, Role role) { + String tokenKey = parseTokenKey(memberId, role); hashRedisRepository.delete(tokenKey); } - private String parseTokenKey(Long memberId) { - return "auth_" + memberId; + private String parseTokenKey(Long memberId, Role role) { + return role.name() + "_" + memberId; } } diff --git a/src/main/java/com/moabam/api/domain/member/BadgeType.java b/src/main/java/com/moabam/api/domain/member/BadgeType.java index 82a7ebd1..e0819f9a 100644 --- a/src/main/java/com/moabam/api/domain/member/BadgeType.java +++ b/src/main/java/com/moabam/api/domain/member/BadgeType.java @@ -2,6 +2,7 @@ import java.util.Arrays; import java.util.List; +import java.util.Optional; import java.util.Set; import com.moabam.api.dto.member.BadgeResponse; @@ -11,16 +12,15 @@ @Getter public enum BadgeType { - MORNING_BIRTH("MORNING", "오목눈이 탄생"), - MORNING_ADULT("MORNING", "어른 오목눈이"), - NIGHT_BIRTH("NIGHT", "부엉이 탄생"), - NIGHT_ADULT("NIGHT", "어른 부엉이"); + BIRTH(10, "탄생 축하 뱃지"), + LEVEL10(100, "10레벨 뱃지"), + LEVEL50(500, "50레벨 뱃지"); - private final String period; + private final long certifyCount; private final String korean; - BadgeType(String period, String korean) { - this.period = period; + BadgeType(long certifyCount, String korean) { + this.certifyCount = certifyCount; this.korean = korean; } @@ -32,4 +32,10 @@ public static List memberBadgeMap(Set badgeTypes) { .build()) .toList(); } + + public static Optional getBadgeFrom(long certifyCount) { + return Arrays.stream(BadgeType.values()) + .filter(badgeType -> badgeType.certifyCount == certifyCount) + .findFirst(); + } } diff --git a/src/main/java/com/moabam/api/domain/member/repository/BadgeRepository.java b/src/main/java/com/moabam/api/domain/member/repository/BadgeRepository.java index dd16ebff..ac313e25 100644 --- a/src/main/java/com/moabam/api/domain/member/repository/BadgeRepository.java +++ b/src/main/java/com/moabam/api/domain/member/repository/BadgeRepository.java @@ -3,7 +3,10 @@ import org.springframework.data.jpa.repository.JpaRepository; import com.moabam.api.domain.member.Badge; +import com.moabam.api.domain.member.BadgeType; public interface BadgeRepository extends JpaRepository { + boolean existsByMemberIdAndType(Long memberId, BadgeType type); + } diff --git a/src/main/java/com/moabam/global/auth/filter/AuthorizationFilter.java b/src/main/java/com/moabam/global/auth/filter/AuthorizationFilter.java index 325afe37..ecc5438e 100644 --- a/src/main/java/com/moabam/global/auth/filter/AuthorizationFilter.java +++ b/src/main/java/com/moabam/global/auth/filter/AuthorizationFilter.java @@ -13,8 +13,10 @@ import com.moabam.api.application.auth.AuthorizationService; import com.moabam.api.application.auth.JwtAuthenticationService; import com.moabam.api.application.auth.mapper.AuthorizationMapper; +import com.moabam.api.domain.member.Role; import com.moabam.global.auth.model.AuthorizationThreadLocal; import com.moabam.global.auth.model.PublicClaim; +import com.moabam.global.error.exception.BadRequestException; import com.moabam.global.error.exception.UnauthorizedException; import com.moabam.global.error.model.ErrorMessage; @@ -39,8 +41,9 @@ public class AuthorizationFilter extends OncePerRequestFilter { @Override protected void doFilterInternal(@NotNull HttpServletRequest httpServletRequest, - @NotNull HttpServletResponse httpServletResponse, - @NotNull FilterChain filterChain) throws ServletException, IOException { + @NotNull HttpServletResponse httpServletResponse, @NotNull FilterChain filterChain) throws + ServletException, + IOException { if (isPermit(httpServletRequest)) { filterChain.doFilter(httpServletRequest, httpServletResponse); @@ -73,32 +76,45 @@ private void invoke(HttpServletRequest httpServletRequest, HttpServletResponse h throw new UnauthorizedException(ErrorMessage.GRANT_FAILED); } - handleTokenAuthenticate(cookies, httpServletResponse); + handleTokenAuthenticate(cookies, httpServletResponse, httpServletRequest); } private boolean isTokenTypeBearer(Cookie[] cookies) { return "Bearer".equals(extractTokenFromCookie(cookies, "token_type")); } - private void handleTokenAuthenticate(Cookie[] cookies, - HttpServletResponse httpServletResponse) { + private void handleTokenAuthenticate(Cookie[] cookies, HttpServletResponse httpServletResponse, + HttpServletRequest httpServletRequest) { String accessToken = extractTokenFromCookie(cookies, "access_token"); PublicClaim publicClaim = authenticationService.parseClaim(accessToken); - if (authenticationService.isTokenExpire(accessToken)) { + if (authenticationService.isTokenExpire(accessToken, publicClaim.role())) { String refreshToken = extractTokenFromCookie(cookies, "refresh_token"); - if (authenticationService.isTokenExpire(refreshToken)) { + if (authenticationService.isTokenExpire(refreshToken, publicClaim.role())) { throw new UnauthorizedException(ErrorMessage.AUTHENTICATE_FAIL); } - authorizationService.validTokenPair(publicClaim.id(), refreshToken); + validInvalidMember(publicClaim, refreshToken, httpServletRequest); authorizationService.issueServiceToken(httpServletResponse, publicClaim); } AuthorizationThreadLocal.setAuthMember(AuthorizationMapper.toAuthMember(publicClaim)); } + private void validInvalidMember(PublicClaim publicClaim, String refreshToken, + HttpServletRequest httpServletRequest) { + boolean isAdminPath = httpServletRequest.getRequestURI().contains("admins"); + + if (!((publicClaim.role().equals(Role.ADMIN) && isAdminPath) || (publicClaim.role().equals(Role.USER) + && !isAdminPath))) { + throw new BadRequestException(ErrorMessage.INVALID_REQUEST_ROLE); + } + + authorizationService.validTokenPair(publicClaim.id(), refreshToken, publicClaim.role()); + authorizationService.validMemberExist(publicClaim.id(), publicClaim.role()); + } + private Cookie[] getCookiesOrThrow(HttpServletRequest httpServletRequest) { return Optional.ofNullable(httpServletRequest.getCookies()) .orElseThrow(() -> new UnauthorizedException(ErrorMessage.GRANT_FAILED)); diff --git a/src/main/java/com/moabam/global/auth/filter/CorsFilter.java b/src/main/java/com/moabam/global/auth/filter/CorsFilter.java index f363c2df..70508dbd 100644 --- a/src/main/java/com/moabam/global/auth/filter/CorsFilter.java +++ b/src/main/java/com/moabam/global/auth/filter/CorsFilter.java @@ -66,10 +66,7 @@ protected void doFilterInternal(HttpServletRequest httpServletRequest, HttpServl } public String secureMatch(String refer) { - return allowOriginsConfig.origin().stream() - .filter(refer::contains) - .findFirst() - .orElse(null); + return allowOriginsConfig.origin().stream().filter(refer::contains).findFirst().orElse(null); } public boolean isOption(String method) { diff --git a/src/main/java/com/moabam/global/common/util/CookieUtils.java b/src/main/java/com/moabam/global/common/util/CookieUtils.java index 892268da..5f59441d 100644 --- a/src/main/java/com/moabam/global/common/util/CookieUtils.java +++ b/src/main/java/com/moabam/global/common/util/CookieUtils.java @@ -7,10 +7,11 @@ @NoArgsConstructor(access = AccessLevel.PRIVATE) public class CookieUtils { - public static Cookie tokenCookie(String name, String value, long expireTime) { + public static Cookie tokenCookie(String name, String value, long expireTime, String domain) { Cookie cookie = new Cookie(name, value); cookie.setSecure(true); cookie.setHttpOnly(true); + cookie.setDomain(domain); cookie.setPath("/"); cookie.setMaxAge((int)expireTime); cookie.setAttribute("SameSite", "Lax"); @@ -18,10 +19,11 @@ public static Cookie tokenCookie(String name, String value, long expireTime) { return cookie; } - public static Cookie typeCookie(String value, long expireTime) { + public static Cookie typeCookie(String value, long expireTime, String domain) { Cookie cookie = new Cookie("token_type", value); cookie.setSecure(true); cookie.setHttpOnly(true); + cookie.setDomain(domain); cookie.setPath("/"); cookie.setMaxAge((int)expireTime); cookie.setAttribute("SameSite", "Lax"); diff --git a/src/main/java/com/moabam/global/config/AllowOriginConfig.java b/src/main/java/com/moabam/global/config/AllowOriginConfig.java index d2ae8db6..b580a99f 100644 --- a/src/main/java/com/moabam/global/config/AllowOriginConfig.java +++ b/src/main/java/com/moabam/global/config/AllowOriginConfig.java @@ -6,7 +6,8 @@ @ConfigurationProperties(prefix = "allows") public record AllowOriginConfig( - List origin -) { + String adminDomain, + String domain, + List origin) { } diff --git a/src/main/java/com/moabam/global/config/TokenConfig.java b/src/main/java/com/moabam/global/config/TokenConfig.java index fe6bdc91..4bbe5a1e 100644 --- a/src/main/java/com/moabam/global/config/TokenConfig.java +++ b/src/main/java/com/moabam/global/config/TokenConfig.java @@ -16,13 +16,17 @@ public class TokenConfig { private final long accessExpire; private final long refreshExpire; private final String secretKey; + private final String adminSecret; private final Key key; + private final Key adminKey; - public TokenConfig(String iss, long accessExpire, long refreshExpire, String secretKey) { + public TokenConfig(String iss, long accessExpire, long refreshExpire, String secretKey, String adminSecret) { this.iss = iss; this.accessExpire = accessExpire; this.refreshExpire = refreshExpire; this.secretKey = secretKey; + this.adminSecret = adminSecret; this.key = Keys.hmacShaKeyFor(secretKey.getBytes(StandardCharsets.UTF_8)); + this.adminKey = Keys.hmacShaKeyFor(adminSecret.getBytes(StandardCharsets.UTF_8)); } } diff --git a/src/main/java/com/moabam/global/error/model/ErrorMessage.java b/src/main/java/com/moabam/global/error/model/ErrorMessage.java index 3684e3ec..ee5584c7 100644 --- a/src/main/java/com/moabam/global/error/model/ErrorMessage.java +++ b/src/main/java/com/moabam/global/error/model/ErrorMessage.java @@ -12,6 +12,7 @@ public enum ErrorMessage { INVALID_REQUEST_VALUE_TYPE_FORMAT("'%s' 값은 유효한 %s 값이 아닙니다."), NOT_FOUND_AVAILABLE_PORT("사용 가능한 포트를 찾을 수 없습니다. (10000 ~ 65535)"), ERROR_EXECUTING_EMBEDDED_REDIS("Embedded Redis 실행 중 오류가 발생했습니다."), + INVALID_REQUEST_ROLE("회원은 회원에, 어드민은 어드민에 연결해야 합니다."), REPORT_REQUEST_ERROR("신고 요청하고자 하는 방이나 대상이 존재하지 않습니다."), diff --git a/src/main/resources/config b/src/main/resources/config index 77b52691..3aa15e1b 160000 --- a/src/main/resources/config +++ b/src/main/resources/config @@ -1 +1 @@ -Subproject commit 77b52691bc52d2c0506cc039ee8ec21d1292380d +Subproject commit 3aa15e1b92cc4573ccb5f18f120fb98ab66b48fa diff --git a/src/main/resources/static/docs/coupon.html b/src/main/resources/static/docs/coupon.html index b0e56d22..a52ba6e9 100644 --- a/src/main/resources/static/docs/coupon.html +++ b/src/main/resources/static/docs/coupon.html @@ -461,7 +461,7 @@

요청

POST /admins/coupons HTTP/1.1
 Content-Type: application/json;charset=UTF-8
-Content-Length: 178
+Content-Length: 186
 Host: localhost:8080
 
 {
@@ -540,7 +540,7 @@ 

응답

Access-Control-Allow-Credentials: true Access-Control-Max-Age: 3600 Content-Type: application/json -Content-Length: 192 +Content-Length: 202 { "id" : 24, @@ -571,7 +571,7 @@

요청

POST /coupons/search HTTP/1.1
 Content-Type: application/json;charset=UTF-8
-Content-Length: 41
+Content-Length: 44
 Host: localhost:8080
 
 {
@@ -590,7 +590,7 @@ 

응답

Access-Control-Allow-Credentials: true Access-Control-Max-Age: 3600 Content-Type: application/json -Content-Length: 193 +Content-Length: 203 [ { "id" : 25, @@ -637,7 +637,7 @@

응답

Access-Control-Allow-Credentials: true Access-Control-Max-Age: 3600 Content-Type: application/json -Content-Length: 63 +Content-Length: 65 { "message" : "이미 쿠폰 발급에 성공했습니다!" @@ -716,7 +716,7 @@

응답

diff --git a/src/main/resources/static/docs/index.html b/src/main/resources/static/docs/index.html index 154f140e..4c8f2a12 100644 --- a/src/main/resources/static/docs/index.html +++ b/src/main/resources/static/docs/index.html @@ -616,7 +616,7 @@

diff --git a/src/main/resources/static/docs/notification.html b/src/main/resources/static/docs/notification.html index a6327a68..d4ddae0c 100644 --- a/src/main/resources/static/docs/notification.html +++ b/src/main/resources/static/docs/notification.html @@ -513,7 +513,7 @@

응답

diff --git a/src/test/java/com/moabam/api/application/auth/AuthorizationServiceTest.java b/src/test/java/com/moabam/api/application/auth/AuthorizationServiceTest.java index 93f6c5a3..b746b6d6 100644 --- a/src/test/java/com/moabam/api/application/auth/AuthorizationServiceTest.java +++ b/src/test/java/com/moabam/api/application/auth/AuthorizationServiceTest.java @@ -23,10 +23,12 @@ import org.springframework.mock.web.MockHttpServletResponse; import org.springframework.test.util.ReflectionTestUtils; +import com.moabam.admin.application.admin.AdminService; import com.moabam.api.application.auth.mapper.AuthorizationMapper; import com.moabam.api.application.member.MemberService; import com.moabam.api.domain.auth.repository.TokenRepository; import com.moabam.api.domain.member.Member; +import com.moabam.api.domain.member.Role; import com.moabam.api.dto.auth.AuthorizationCodeRequest; import com.moabam.api.dto.auth.AuthorizationCodeResponse; import com.moabam.api.dto.auth.AuthorizationTokenInfoResponse; @@ -36,8 +38,8 @@ import com.moabam.api.infrastructure.fcm.FcmService; import com.moabam.global.auth.model.AuthMember; import com.moabam.global.auth.model.PublicClaim; -import com.moabam.global.common.util.cookie.CookieDevUtils; -import com.moabam.global.common.util.cookie.CookieUtils; +import com.moabam.global.common.util.CookieUtils; +import com.moabam.global.config.AllowOriginConfig; import com.moabam.global.config.OAuthConfig; import com.moabam.global.config.TokenConfig; import com.moabam.global.error.exception.BadRequestException; @@ -64,6 +66,9 @@ class AuthorizationServiceTest { @Mock MemberService memberService; + @Mock + AdminService adminService; + @Mock JwtProviderService jwtProviderService; @@ -73,19 +78,22 @@ class AuthorizationServiceTest { @Mock TokenRepository tokenRepository; - CookieUtils cookieUtils; + AllowOriginConfig allowOriginsConfig; OAuthConfig oauthConfig; TokenConfig tokenConfig; AuthorizationService noPropertyService; OAuthConfig noOAuthConfig; + String domain = "Test"; @BeforeEach public void initParams() { - cookieUtils = new CookieDevUtils(); - tokenConfig = new TokenConfig(null, 100000, 150000, - "testtesttesttesttesttesttesttesttesttesttesttesttesttesttesttest"); + String secretKey = "testtesttesttesttesttesttesttesttesttesttesttesttesttesttesttest"; + String adminKey = "testtesttesttesttesttesttesttesttesttesttesttesttesttesttesttest"; + + allowOriginsConfig = new AllowOriginConfig(domain, domain, List.of("test", "test")); + ReflectionTestUtils.setField(authorizationService, "allowOriginsConfig", allowOriginsConfig); + tokenConfig = new TokenConfig(null, 100000, 150000, secretKey, adminKey); ReflectionTestUtils.setField(authorizationService, "tokenConfig", tokenConfig); - ReflectionTestUtils.setField(authorizationService, "cookieUtils", cookieUtils); oauthConfig = new OAuthConfig( new OAuthConfig.Provider("https://authorization/url", "http://redirect/url", "http://token/url", @@ -98,7 +106,8 @@ public void initParams() { new OAuthConfig.Provider(null, null, null, null, null, null), new OAuthConfig.Client(null, null, null, null, null, null)); noPropertyService = new AuthorizationService(fcmService, noOAuthConfig, tokenConfig, - oAuth2AuthorizationServerRequestService, memberService, jwtProviderService, tokenRepository, cookieUtils); + oAuth2AuthorizationServerRequestService, memberService, adminService, + jwtProviderService, tokenRepository, allowOriginsConfig); } @DisplayName("인가코드 URI 생성 매퍼 실패") @@ -222,7 +231,7 @@ void signUp_success(boolean isSignUp) { AuthorizationTokenInfoResponse authorizationTokenInfoResponse = AuthorizationResponseFixture.authorizationTokenInfoResponse(); LoginResponse loginResponse = LoginResponse.builder() - .publicClaim(PublicClaim.builder().id(1L).nickname("nickname").build()) + .publicClaim(PublicClaim.builder().id(1L).nickname("nickname").role(Role.USER).build()) .isSignUp(isSignUp) .build(); @@ -255,22 +264,25 @@ void signUp_success(boolean isSignUp) { @Test void valid_token_in_redis() { // Given - willReturn(TokenSaveValueFixture.tokenSaveValue("token")).given(tokenRepository).getTokenSaveValue(1L); + willReturn(TokenSaveValueFixture.tokenSaveValue("token")) + .given(tokenRepository).getTokenSaveValue(1L, Role.USER); // When + Then - assertThatNoException().isThrownBy(() -> authorizationService.validTokenPair(1L, "token")); + assertThatNoException().isThrownBy(() -> + authorizationService.validTokenPair(1L, "token", Role.USER)); } @DisplayName("이전 토큰과 동일한지 검증") @Test void valid_token_failby_notEquals_token() { // Given - willReturn(TokenSaveValueFixture.tokenSaveValue("token")).given(tokenRepository).getTokenSaveValue(1L); + willReturn(TokenSaveValueFixture.tokenSaveValue("token")) + .given(tokenRepository).getTokenSaveValue(1L, Role.USER); // When + Then - assertThatThrownBy(() -> authorizationService.validTokenPair(1L, "oldToken")).isInstanceOf( + assertThatThrownBy(() -> authorizationService.validTokenPair(1L, "oldToken", Role.USER)).isInstanceOf( UnauthorizedException.class).hasMessage(ErrorMessage.AUTHENTICATE_FAIL.getMessage()); - verify(tokenRepository).delete(1L); + verify(tokenRepository).delete(1L, Role.USER); } @DisplayName("토큰 삭제 성공") @@ -278,8 +290,10 @@ void valid_token_failby_notEquals_token() { void error_with_expire_token(@WithMember AuthMember authMember) { // given MockHttpServletRequest httpServletRequest = new MockHttpServletRequest(); - httpServletRequest.setCookies(cookieUtils.tokenCookie("access_token", "value", 100000), - cookieUtils.tokenCookie("refresh_token", "value", 100000), cookieUtils.typeCookie("Bearer", 100000)); + httpServletRequest.setCookies( + CookieUtils.tokenCookie("access_token", "value", 100000, domain), + CookieUtils.tokenCookie("refresh_token", "value", 100000, domain), + CookieUtils.typeCookie("Bearer", 100000, domain)); MockHttpServletResponse httpServletResponse = new MockHttpServletResponse(); @@ -292,7 +306,7 @@ void error_with_expire_token(@WithMember AuthMember authMember) { assertThat(cookie.getMaxAge()).isZero(); assertThat(cookie.getValue()).isEqualTo("value"); - verify(tokenRepository).delete(authMember.id()); + verify(tokenRepository).delete(authMember.id(), Role.USER); } @DisplayName("토큰 없어서 삭제 실패") diff --git a/src/test/java/com/moabam/api/application/auth/JwtAuthenticationServiceTest.java b/src/test/java/com/moabam/api/application/auth/JwtAuthenticationServiceTest.java index 9c56f174..37149fb2 100644 --- a/src/test/java/com/moabam/api/application/auth/JwtAuthenticationServiceTest.java +++ b/src/test/java/com/moabam/api/application/auth/JwtAuthenticationServiceTest.java @@ -16,8 +16,7 @@ import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.junit.jupiter.MockitoExtension; -import com.moabam.api.application.auth.JwtAuthenticationService; -import com.moabam.api.application.auth.JwtProviderService; +import com.moabam.api.domain.member.Role; import com.moabam.global.auth.model.PublicClaim; import com.moabam.global.config.TokenConfig; import com.moabam.global.error.exception.UnauthorizedException; @@ -32,6 +31,7 @@ class JwtAuthenticationServiceTest { String originIss = "PARK"; String originSecretKey = "testestestestestestestestestesttestestestestestestestestestest"; + String adminKey = "testestestestestestestestestesttestestestestestestestestestest"; long originId = 1L; long originAccessExpire = 100000; long originRefreshExpire = 150000; @@ -42,7 +42,7 @@ class JwtAuthenticationServiceTest { @BeforeEach void initConfig() { - tokenConfig = new TokenConfig(originIss, originAccessExpire, originRefreshExpire, originSecretKey); + tokenConfig = new TokenConfig(originIss, originAccessExpire, originRefreshExpire, originSecretKey, adminKey); jwtProviderService = new JwtProviderService(tokenConfig); jwtAuthenticationService = new JwtAuthenticationService(tokenConfig); } @@ -55,7 +55,7 @@ void token_authentication_success() { // when, then assertThatNoException().isThrownBy(() -> - jwtAuthenticationService.isTokenExpire(token)); + jwtAuthenticationService.isTokenExpire(token, Role.USER)); } @DisplayName("토큰 인증 시간 만료 테스트") @@ -63,14 +63,14 @@ void token_authentication_success() { void token_authentication_time_expire() { // Given PublicClaim publicClaim = PublicClaimFixture.publicClaim(); - TokenConfig tokenConfig = new TokenConfig(originIss, 0, 0, originSecretKey); + TokenConfig tokenConfig = new TokenConfig(originIss, 0, 0, originSecretKey, adminKey); JwtAuthenticationService jwtAuthenticationService = new JwtAuthenticationService(tokenConfig); JwtProviderService jwtProviderService = new JwtProviderService(tokenConfig); String token = jwtProviderService.provideAccessToken(publicClaim); // When assertThatNoException().isThrownBy(() -> { - boolean result = jwtAuthenticationService.isTokenExpire(token); + boolean result = jwtAuthenticationService.isTokenExpire(token, Role.USER); // Then assertThat(result).isTrue(); @@ -98,7 +98,7 @@ void token_authenticate_failBy_payload() { parts[2]); // Then - Assertions.assertThatThrownBy(() -> jwtAuthenticationService.isTokenExpire(newToken)) + Assertions.assertThatThrownBy(() -> jwtAuthenticationService.isTokenExpire(newToken, Role.USER)) .isInstanceOf(UnauthorizedException.class); } @@ -121,7 +121,7 @@ void token_authenticate_failBy_key() { .compact(); // When + Then - assertThatThrownBy(() -> jwtAuthenticationService.isTokenExpire(token)) + assertThatThrownBy(() -> jwtAuthenticationService.isTokenExpire(token, Role.USER)) .isExactlyInstanceOf(UnauthorizedException.class); } diff --git a/src/test/java/com/moabam/api/application/auth/JwtProviderServiceTest.java b/src/test/java/com/moabam/api/application/auth/JwtProviderServiceTest.java index 9c985f57..4a85f46a 100644 --- a/src/test/java/com/moabam/api/application/auth/JwtProviderServiceTest.java +++ b/src/test/java/com/moabam/api/application/auth/JwtProviderServiceTest.java @@ -12,6 +12,7 @@ import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.ValueSource; +import com.moabam.api.domain.member.Role; import com.moabam.global.auth.model.PublicClaim; import com.moabam.global.config.TokenConfig; import com.moabam.support.fixture.PublicClaimFixture; @@ -24,6 +25,7 @@ class JwtProviderServiceTest { String iss = "PARK"; String secretKey = "testestestestestestestestestesttestestestestestestestestestest"; + String adminKey = "testestestestestestestestestesttestestestestestestestestestest"; long id = 1L; @DisplayName("access 토큰 생성 성공") @@ -32,7 +34,7 @@ void create_access_token_success() throws JSONException { // given long accessExpire = 10000L; - TokenConfig tokenConfig = new TokenConfig("PARK", accessExpire, 0L, secretKey); + TokenConfig tokenConfig = new TokenConfig("PARK", accessExpire, 0L, secretKey, adminKey); JwtProviderService jwtProviderService = new JwtProviderService(tokenConfig); PublicClaim publicClaim = PublicClaimFixture.publicClaim(); @@ -97,11 +99,11 @@ void create_refresh_token_success() throws JSONException { // given long refreshExpire = 15000L; - TokenConfig tokenConfig = new TokenConfig("PARK", 0L, refreshExpire, secretKey); + TokenConfig tokenConfig = new TokenConfig("PARK", 0L, refreshExpire, secretKey, adminKey); JwtProviderService jwtProviderService = new JwtProviderService(tokenConfig); // when - String refreshToken = jwtProviderService.provideRefreshToken(); + String refreshToken = jwtProviderService.provideRefreshToken(Role.USER); String[] parts = refreshToken.split("\\."); String headers = new String(Base64.getDecoder().decode(parts[0])); @@ -128,7 +130,7 @@ void create_access_token_fail() { // given long accessExpire = -1L; - TokenConfig tokenConfig = new TokenConfig("PARK", accessExpire, 0L, secretKey); + TokenConfig tokenConfig = new TokenConfig("PARK", accessExpire, 0L, secretKey, adminKey); JwtProviderService jwtProviderService = new JwtProviderService(tokenConfig); PublicClaim publicClaim = PublicClaimFixture.publicClaim(); @@ -149,7 +151,7 @@ void create_token_fail() { // given long refreshExpire = -1L; - TokenConfig tokenConfig = new TokenConfig("PARK", 0L, refreshExpire, secretKey); + TokenConfig tokenConfig = new TokenConfig("PARK", 0L, refreshExpire, secretKey, adminKey); JwtProviderService jwtProviderService = new JwtProviderService(tokenConfig); PublicClaim publicClaim = PublicClaimFixture.publicClaim(); diff --git a/src/test/java/com/moabam/api/application/room/CertificationServiceTest.java b/src/test/java/com/moabam/api/application/room/CertificationServiceTest.java index f35b1483..e02eac44 100644 --- a/src/test/java/com/moabam/api/application/room/CertificationServiceTest.java +++ b/src/test/java/com/moabam/api/application/room/CertificationServiceTest.java @@ -21,6 +21,7 @@ import com.moabam.api.application.bug.BugService; import com.moabam.api.application.image.ImageService; +import com.moabam.api.application.member.BadgeService; import com.moabam.api.application.member.MemberService; import com.moabam.api.application.room.mapper.CertificationsMapper; import com.moabam.api.domain.bug.BugType; @@ -82,6 +83,9 @@ class CertificationServiceTest { @Mock private ImageService imageService; + @Mock + private BadgeService badgeService; + @Mock private ClockHolder clockHolder; diff --git a/src/test/java/com/moabam/api/domain/member/BadgeRepositoryTest.java b/src/test/java/com/moabam/api/domain/member/BadgeRepositoryTest.java new file mode 100644 index 00000000..a250f84b --- /dev/null +++ b/src/test/java/com/moabam/api/domain/member/BadgeRepositoryTest.java @@ -0,0 +1,84 @@ +package com.moabam.api.domain.member; + +import static org.assertj.core.api.Assertions.*; + +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; +import org.springframework.beans.factory.annotation.Autowired; + +import com.moabam.api.application.member.BadgeService; +import com.moabam.api.domain.member.repository.BadgeRepository; +import com.moabam.api.domain.member.repository.MemberRepository; +import com.moabam.support.annotation.QuerydslRepositoryTest; +import com.moabam.support.fixture.MemberFixture; + +@QuerydslRepositoryTest +class BadgeRepositoryTest { + + @Autowired + BadgeRepository badgeRepository; + + @Autowired + MemberRepository memberRepository; + + @DisplayName("인증 횟수에 따른 값 뱃지 확인") + @Test + void get_badge_by_certifyCount() { + assertThat(BadgeType.getBadgeFrom(10).get()).isEqualTo(BadgeType.BIRTH); + assertThat(BadgeType.getBadgeFrom(100).get()).isEqualTo(BadgeType.LEVEL10); + assertThat(BadgeType.getBadgeFrom(500).get()).isEqualTo(BadgeType.LEVEL50); + assertThat(BadgeType.getBadgeFrom(9)).isEmpty(); + } + + @DisplayName("뱃지 생성 성공") + @ParameterizedTest + @ValueSource(ints = {10, 100, 500}) + void member_get_badge_success(int certifyCount) { + // given + BadgeService badgeService = new BadgeService(badgeRepository); + + Member member = MemberFixture.member(); + for (int i = 0; i < certifyCount; i++) { + member.increaseTotalCertifyCount(); + } + + memberRepository.save(member); + + // when + badgeService.createBadge(member.getId(), member.getTotalCertifyCount()); + BadgeType expectedType = BadgeType.getBadgeFrom(certifyCount).get(); + + // then + assertThat(badgeRepository.existsByMemberIdAndType(member.getId(), expectedType)) + .isTrue(); + } + + @DisplayName("뱃지가 있으면 저장하지 않는다.") + @ParameterizedTest + @ValueSource(ints = {10, 100, 500}) + void already_exist_bage_then_no_save(int certifyCount) { + // given + BadgeService badgeService = new BadgeService(badgeRepository); + + Member member = MemberFixture.member(); + for (int i = 0; i < certifyCount; i++) { + member.increaseTotalCertifyCount(); + } + + memberRepository.save(member); + + // when + BadgeType expectedType = BadgeType.getBadgeFrom(certifyCount).get(); + + Badge badge = Badge.builder().memberId(member.getId()).type(expectedType).build(); + badgeRepository.save(badge); + + // then + assertThatNoException() + .isThrownBy(() -> badgeService.createBadge(member.getId(), member.getTotalCertifyCount())); + assertThat(badgeRepository.existsByMemberIdAndType(member.getId(), expectedType)) + .isTrue(); + } +} diff --git a/src/test/java/com/moabam/api/domain/member/MemberRepositoryTest.java b/src/test/java/com/moabam/api/domain/member/MemberRepositoryTest.java index 90729351..ee18e08c 100644 --- a/src/test/java/com/moabam/api/domain/member/MemberRepositoryTest.java +++ b/src/test/java/com/moabam/api/domain/member/MemberRepositoryTest.java @@ -137,11 +137,10 @@ void search_info_success() { member.enterRoom(RoomType.MORNING); memberRepository.save(member); - Badge morningBirth = BadgeFixture.badge(member.getId(), BadgeType.MORNING_BIRTH); - Badge morningAdult = BadgeFixture.badge(member.getId(), BadgeType.MORNING_ADULT); - Badge nightBirth = BadgeFixture.badge(member.getId(), BadgeType.NIGHT_BIRTH); - Badge nightAdult = BadgeFixture.badge(member.getId(), BadgeType.NIGHT_ADULT); - List badges = List.of(morningBirth, morningAdult, nightBirth, nightAdult); + Badge birth = BadgeFixture.badge(member.getId(), BadgeType.BIRTH); + Badge level50 = BadgeFixture.badge(member.getId(), BadgeType.LEVEL50); + Badge level10 = BadgeFixture.badge(member.getId(), BadgeType.LEVEL10); + List badges = List.of(birth, level10, level50); badgeRepository.saveAll(badges); // when diff --git a/src/test/java/com/moabam/api/infrastructure/redis/TokenRepostiroyTest.java b/src/test/java/com/moabam/api/infrastructure/redis/TokenRepostiroyTest.java index d720226f..006d392e 100644 --- a/src/test/java/com/moabam/api/infrastructure/redis/TokenRepostiroyTest.java +++ b/src/test/java/com/moabam/api/infrastructure/redis/TokenRepostiroyTest.java @@ -15,6 +15,7 @@ import org.mockito.junit.jupiter.MockitoExtension; import com.moabam.api.domain.auth.repository.TokenRepository; +import com.moabam.api.domain.member.Role; import com.moabam.api.dto.auth.TokenSaveValue; import com.moabam.support.fixture.TokenSaveValueFixture; @@ -35,7 +36,7 @@ void save_token_suceess() { // When + Then Assertions.assertThatNoException() - .isThrownBy(() -> tokenRepository.saveToken(1L, TokenSaveValueFixture.tokenSaveValue())); + .isThrownBy(() -> tokenRepository.saveToken(1L, TokenSaveValueFixture.tokenSaveValue(), Role.USER)); } @DisplayName("토큰 조회 성공") @@ -46,7 +47,7 @@ void token_get_success() { .given(hashRedisRepository).get(anyString()); // when - TokenSaveValue tokenSaveValue = tokenRepository.getTokenSaveValue(123L); + TokenSaveValue tokenSaveValue = tokenRepository.getTokenSaveValue(123L, Role.USER); // then assertAll( @@ -60,6 +61,6 @@ void token_get_success() { void delete_token_suceess() { // When + Then Assertions.assertThatNoException() - .isThrownBy(() -> tokenRepository.delete(1L)); + .isThrownBy(() -> tokenRepository.delete(1L, Role.USER)); } } diff --git a/src/test/java/com/moabam/api/presentation/MemberControllerTest.java b/src/test/java/com/moabam/api/presentation/MemberControllerTest.java index 6297567c..80efe377 100644 --- a/src/test/java/com/moabam/api/presentation/MemberControllerTest.java +++ b/src/test/java/com/moabam/api/presentation/MemberControllerTest.java @@ -58,6 +58,7 @@ import com.moabam.api.domain.member.Badge; import com.moabam.api.domain.member.BadgeType; import com.moabam.api.domain.member.Member; +import com.moabam.api.domain.member.Role; import com.moabam.api.domain.member.repository.BadgeRepository; import com.moabam.api.domain.member.repository.MemberRepository; import com.moabam.api.domain.member.repository.MemberSearchRepository; @@ -167,14 +168,14 @@ void setUp() { void logout_success() throws Exception { // given TokenSaveValue tokenSaveValue = TokenSaveValueFixture.tokenSaveValue(); - tokenRepository.saveToken(member.getId(), tokenSaveValue); + tokenRepository.saveToken(member.getId(), tokenSaveValue, Role.USER); // expected ResultActions result = mockMvc.perform(get("/members/logout")); result.andExpect(status().is2xxSuccessful()); - Assertions.assertThatThrownBy(() -> tokenRepository.getTokenSaveValue(member.getId())) + Assertions.assertThatThrownBy(() -> tokenRepository.getTokenSaveValue(member.getId(), Role.USER)) .isInstanceOf(UnauthorizedException.class); } @@ -264,10 +265,10 @@ void unlink_social_member_failby_meber_is_manger() throws Exception { @Test void search_my_info_success() throws Exception { // given - Badge morningBirth = BadgeFixture.badge(member.getId(), BadgeType.MORNING_BIRTH); - Badge morningAdult = BadgeFixture.badge(member.getId(), BadgeType.MORNING_ADULT); - Badge nightBirth = BadgeFixture.badge(member.getId(), BadgeType.NIGHT_BIRTH); - List badges = List.of(morningBirth, morningAdult, nightBirth); + Badge birth = BadgeFixture.badge(member.getId(), BadgeType.BIRTH); + Badge level50 = BadgeFixture.badge(member.getId(), BadgeType.LEVEL50); + Badge level10 = BadgeFixture.badge(member.getId(), BadgeType.LEVEL10); + List badges = List.of(birth, level10, level50); badgeRepository.saveAll(badges); Item night = ItemFixture.nightMageSkin(); @@ -301,14 +302,12 @@ void search_my_info_success() throws Exception { // MockMvcResultMatchers.jsonPath("$.birds.MORNING").value(morningInven.getItem().getImage()), // MockMvcResultMatchers.jsonPath("$.birds.NIGHT").value(nightInven.getItem().getImage()), - MockMvcResultMatchers.jsonPath("$.badges[0].badge").value("오목눈이 탄생"), + MockMvcResultMatchers.jsonPath("$.badges[0].badge").value("탄생 축하 뱃지"), MockMvcResultMatchers.jsonPath("$.badges[0].unlock").value(true), - MockMvcResultMatchers.jsonPath("$.badges[1].badge").value("어른 오목눈이"), + MockMvcResultMatchers.jsonPath("$.badges[1].badge").value("10레벨 뱃지"), MockMvcResultMatchers.jsonPath("$.badges[1].unlock").value(true), - MockMvcResultMatchers.jsonPath("$.badges[2].badge").value("부엉이 탄생"), + MockMvcResultMatchers.jsonPath("$.badges[2].badge").value("50레벨 뱃지"), MockMvcResultMatchers.jsonPath("$.badges[2].unlock").value(true), - MockMvcResultMatchers.jsonPath("$.badges[3].badge").value("어른 부엉이"), - MockMvcResultMatchers.jsonPath("$.badges[3].unlock").value(false), MockMvcResultMatchers.jsonPath("$.goldenBug").value(member.getBug().getGoldenBug()), MockMvcResultMatchers.jsonPath("$.morningBug").value(member.getBug().getMorningBug()), MockMvcResultMatchers.jsonPath("$.nightBug").value(member.getBug().getNightBug()) @@ -352,14 +351,12 @@ void search_my_info_with_no_badge_success() throws Exception { // MockMvcResultMatchers.jsonPath("$.birds.MORNING").value(morningInven.getItem().getImage()), // MockMvcResultMatchers.jsonPath("$.birds.NIGHT").value(nightInven.getItem().getImage()), - MockMvcResultMatchers.jsonPath("$.badges[0].badge").value("오목눈이 탄생"), + MockMvcResultMatchers.jsonPath("$.badges[0].badge").value("탄생 축하 뱃지"), MockMvcResultMatchers.jsonPath("$.badges[0].unlock").value(false), - MockMvcResultMatchers.jsonPath("$.badges[1].badge").value("어른 오목눈이"), + MockMvcResultMatchers.jsonPath("$.badges[1].badge").value("10레벨 뱃지"), MockMvcResultMatchers.jsonPath("$.badges[1].unlock").value(false), - MockMvcResultMatchers.jsonPath("$.badges[2].badge").value("부엉이 탄생"), + MockMvcResultMatchers.jsonPath("$.badges[2].badge").value("50레벨 뱃지"), MockMvcResultMatchers.jsonPath("$.badges[2].unlock").value(false), - MockMvcResultMatchers.jsonPath("$.badges[3].badge").value("어른 부엉이"), - MockMvcResultMatchers.jsonPath("$.badges[3].unlock").value(false), MockMvcResultMatchers.jsonPath("$.goldenBug").value(member.getBug().getGoldenBug()), MockMvcResultMatchers.jsonPath("$.morningBug").value(member.getBug().getMorningBug()), MockMvcResultMatchers.jsonPath("$.nightBug").value(member.getBug().getNightBug()) @@ -374,11 +371,9 @@ void search_friend_info_success() throws Exception { Member friend = MemberFixture.member("123456789"); memberRepository.save(friend); - Badge morningBirth = BadgeFixture.badge(friend.getId(), BadgeType.MORNING_BIRTH); - Badge morningAdult = BadgeFixture.badge(friend.getId(), BadgeType.MORNING_ADULT); - Badge nightBirth = BadgeFixture.badge(friend.getId(), BadgeType.NIGHT_BIRTH); - Badge nightAdult = BadgeFixture.badge(friend.getId(), BadgeType.NIGHT_ADULT); - List badges = List.of(morningBirth, morningAdult, nightBirth, nightAdult); + Badge birth = BadgeFixture.badge(friend.getId(), BadgeType.BIRTH); + Badge level10 = BadgeFixture.badge(friend.getId(), BadgeType.LEVEL10); + List badges = List.of(birth, level10); badgeRepository.saveAll(badges); Item night = ItemFixture.nightMageSkin(); @@ -387,10 +382,10 @@ void search_friend_info_success() throws Exception { itemRepository.saveAll(List.of(night, morning, killer)); Inventory nightInven = InventoryFixture.inventory(friend.getId(), night); - nightInven.select(member); + nightInven.select(friend); Inventory morningInven = InventoryFixture.inventory(friend.getId(), morning); - morningInven.select(member); + morningInven.select(friend); Inventory killerInven = InventoryFixture.inventory(friend.getId(), killer); friend.changeDefaultSkintUrl(morning); @@ -415,14 +410,12 @@ void search_friend_info_success() throws Exception { MockMvcResultMatchers.jsonPath("$.birds.MORNING").value(morningInven.getItem().getAwakeImage()), MockMvcResultMatchers.jsonPath("$.birds.NIGHT").value(nightInven.getItem().getAwakeImage()), - MockMvcResultMatchers.jsonPath("$.badges[0].badge").value("오목눈이 탄생"), + MockMvcResultMatchers.jsonPath("$.badges[0].badge").value("탄생 축하 뱃지"), MockMvcResultMatchers.jsonPath("$.badges[0].unlock").value(true), - MockMvcResultMatchers.jsonPath("$.badges[1].badge").value("어른 오목눈이"), + MockMvcResultMatchers.jsonPath("$.badges[1].badge").value("10레벨 뱃지"), MockMvcResultMatchers.jsonPath("$.badges[1].unlock").value(true), - MockMvcResultMatchers.jsonPath("$.badges[2].badge").value("부엉이 탄생"), - MockMvcResultMatchers.jsonPath("$.badges[2].unlock").value(true), - MockMvcResultMatchers.jsonPath("$.badges[3].badge").value("어른 부엉이"), - MockMvcResultMatchers.jsonPath("$.badges[3].unlock").value(true) + MockMvcResultMatchers.jsonPath("$.badges[2].badge").value("50레벨 뱃지"), + MockMvcResultMatchers.jsonPath("$.badges[2].unlock").value(false) ).andDo(print()); } diff --git a/src/test/java/com/moabam/api/presentation/RankingControllerTest.java b/src/test/java/com/moabam/api/presentation/RankingControllerTest.java index f9b866d4..6399e91c 100644 --- a/src/test/java/com/moabam/api/presentation/RankingControllerTest.java +++ b/src/test/java/com/moabam/api/presentation/RankingControllerTest.java @@ -79,7 +79,7 @@ void top_ranking() throws Exception { .andExpect(status().isOk()) .andExpect(jsonPath("$.topRankings", hasSize(10))) .andExpect(jsonPath("$.myRanking.nickname", is(members.get(0).getNickname()))) - .andExpect(jsonPath("$.myRanking.rank", is(21))); + .andExpect(jsonPath("$.myRanking.rank", is(22))); // then diff --git a/src/test/java/com/moabam/api/presentation/RoomControllerTest.java b/src/test/java/com/moabam/api/presentation/RoomControllerTest.java index f4c4fc1d..36acce1b 100644 --- a/src/test/java/com/moabam/api/presentation/RoomControllerTest.java +++ b/src/test/java/com/moabam/api/presentation/RoomControllerTest.java @@ -8,6 +8,7 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; import java.time.LocalDate; +import java.time.LocalDateTime; import java.util.ArrayList; import java.util.List; @@ -18,9 +19,11 @@ import org.junit.jupiter.api.TestInstance; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.CsvSource; +import org.mockito.BDDMockito; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.mock.mockito.SpyBean; import org.springframework.test.web.servlet.MockMvc; import org.springframework.transaction.annotation.Transactional; @@ -48,6 +51,7 @@ import com.moabam.api.dto.room.CreateRoomRequest; import com.moabam.api.dto.room.EnterRoomRequest; import com.moabam.api.dto.room.ModifyRoomRequest; +import com.moabam.global.common.util.SystemClockHolder; import com.moabam.support.annotation.WithMember; import com.moabam.support.common.WithoutFilterSupporter; import com.moabam.support.fixture.BugFixture; @@ -98,6 +102,9 @@ class RoomControllerTest extends WithoutFilterSupporter { @Autowired private InventoryRepository inventoryRepository; + @SpyBean + private SystemClockHolder clockHolder; + Member member; @BeforeAll @@ -424,6 +431,7 @@ void enter_room_with_password_success() throws Exception { @Test void enter_room_with_no_password_success() throws Exception { // given + BDDMockito.given(clockHolder.times()).willReturn(LocalDateTime.of(2023, 12, 3, 14, 30, 0)); Room room = RoomFixture.room(); roomRepository.save(room); diff --git a/src/test/java/com/moabam/global/common/util/CookieMakeTest.java b/src/test/java/com/moabam/global/common/util/CookieMakeTest.java index 63cd7a79..5af52083 100644 --- a/src/test/java/com/moabam/global/common/util/CookieMakeTest.java +++ b/src/test/java/com/moabam/global/common/util/CookieMakeTest.java @@ -13,11 +13,13 @@ @ExtendWith(MockitoExtension.class) class CookieMakeTest { + String domain = "test"; + @DisplayName("prod환경에서 cookie 생성 테스트") @Test void create_test() { // Given - Cookie cookie = CookieUtils.tokenCookie("access_token", "value", 10000); + Cookie cookie = CookieUtils.tokenCookie("access_token", "value", 10000, domain); // When + Then assertAll( @@ -33,7 +35,7 @@ void create_test() { @Test void delete_test() { // given - Cookie cookie = CookieUtils.tokenCookie("access_token", "value", 10000); + Cookie cookie = CookieUtils.tokenCookie("access_token", "value", 10000, domain); // when Cookie deletedCookie = CookieUtils.deleteCookie(cookie); @@ -49,7 +51,7 @@ void delete_test() { @Test void typeCookie_create_test() { // Given + When - Cookie cookie = CookieUtils.typeCookie("Bearer", 10000); + Cookie cookie = CookieUtils.typeCookie("Bearer", 10000, domain); // then assertThat(cookie.getName()).isEqualTo("token_type"); diff --git a/src/test/java/com/moabam/global/filter/AuthorizationFilterTest.java b/src/test/java/com/moabam/global/filter/AuthorizationFilterTest.java index 31f6303a..24e0c5c4 100644 --- a/src/test/java/com/moabam/global/filter/AuthorizationFilterTest.java +++ b/src/test/java/com/moabam/global/filter/AuthorizationFilterTest.java @@ -21,6 +21,7 @@ import com.moabam.api.application.auth.AuthorizationService; import com.moabam.api.application.auth.JwtAuthenticationService; import com.moabam.api.application.auth.JwtProviderService; +import com.moabam.api.domain.member.Role; import com.moabam.global.auth.filter.AuthorizationFilter; import com.moabam.global.auth.model.AuthMember; import com.moabam.global.auth.model.AuthorizationThreadLocal; @@ -98,7 +99,7 @@ void filter_have_any_access_token_error() throws ServletException, IOException { httpServletRequest.addHeader("token_type", "Bearer"); // when - String token = jwtProviderService.provideRefreshToken(); + String token = jwtProviderService.provideRefreshToken(Role.USER); httpServletRequest.setCookies(new Cookie("refresh_token", token)); authorizationFilter.doFilter(httpServletRequest, httpServletResponse, mockFilterChain); @@ -128,7 +129,7 @@ void filter_have_any_refresh_token_error() throws ServletException, IOException new Cookie("access_token", token)); when(jwtAuthenticationService.parseClaim(token)).thenReturn(publicClaim); - when(jwtAuthenticationService.isTokenExpire(token)).thenReturn(true); + when(jwtAuthenticationService.isTokenExpire(token, Role.USER)).thenReturn(true); authorizationFilter.doFilter(httpServletRequest, httpServletResponse, mockFilterChain); @@ -152,15 +153,15 @@ void issue_new_token_success() throws ServletException, IOException { // when String accessToken = jwtProviderService.provideAccessToken(publicClaim); - String refreshToken = jwtProviderService.provideRefreshToken(); + String refreshToken = jwtProviderService.provideRefreshToken(Role.USER); httpServletRequest.setCookies( new Cookie("token_type", "Bearer"), new Cookie("access_token", accessToken), new Cookie("refresh_token", refreshToken)); when(jwtAuthenticationService.parseClaim(accessToken)).thenReturn(publicClaim); - when(jwtAuthenticationService.isTokenExpire(accessToken)).thenReturn(true); - when(jwtAuthenticationService.isTokenExpire(refreshToken)).thenReturn(false); + when(jwtAuthenticationService.isTokenExpire(accessToken, Role.USER)).thenReturn(true); + when(jwtAuthenticationService.isTokenExpire(refreshToken, Role.USER)).thenReturn(false); authorizationFilter.doFilter(httpServletRequest, httpServletResponse, mockFilterChain); diff --git a/src/test/java/com/moabam/support/common/WithFilterSupporter.java b/src/test/java/com/moabam/support/common/WithFilterSupporter.java index 69b5f114..cd92c8cf 100644 --- a/src/test/java/com/moabam/support/common/WithFilterSupporter.java +++ b/src/test/java/com/moabam/support/common/WithFilterSupporter.java @@ -13,6 +13,7 @@ import org.springframework.web.context.WebApplicationContext; import com.moabam.api.application.auth.JwtProviderService; +import com.moabam.api.domain.member.Role; import com.moabam.global.common.util.cookie.CookieUtils; import com.moabam.global.config.TokenConfig; import com.moabam.support.fixture.PublicClaimFixture; @@ -47,7 +48,7 @@ void setUpMockMvc(RestDocumentationContextProvider contextProvider) { jwtProviderService.provideAccessToken(PublicClaimFixture.publicClaim()), tokenConfig.getRefreshExpire())) .cookie(cookieUtils.tokenCookie("refresh_token", - jwtProviderService.provideRefreshToken(), + jwtProviderService.provideRefreshToken(Role.USER), tokenConfig.getRefreshExpire()))) .build(); } diff --git a/src/test/java/com/moabam/support/common/WithoutFilterSupporter.java b/src/test/java/com/moabam/support/common/WithoutFilterSupporter.java index 18d726cc..a58671cb 100644 --- a/src/test/java/com/moabam/support/common/WithoutFilterSupporter.java +++ b/src/test/java/com/moabam/support/common/WithoutFilterSupporter.java @@ -30,7 +30,7 @@ public class WithoutFilterSupporter { @SpyBean private CorsFilter corsFilter; - @SpyBean + @MockBean private AllowOriginConfig allowOriginConfig; @BeforeEach diff --git a/src/test/java/com/moabam/support/fixture/JwtProviderFixture.java b/src/test/java/com/moabam/support/fixture/JwtProviderFixture.java index 7a3c530a..50fa714c 100644 --- a/src/test/java/com/moabam/support/fixture/JwtProviderFixture.java +++ b/src/test/java/com/moabam/support/fixture/JwtProviderFixture.java @@ -7,12 +7,14 @@ public class JwtProviderFixture { public static final String originIss = "PARK"; public static final String originSecretKey = "testestestestestestestestestesttestestestestestestestestestest"; + public static final String adminKey = "testestestestestestestestestesttestestestestestestestestestest"; public static final long originId = 1L; public static final long originAccessExpire = 100000; public static final long originRefreshExpire = 150000; public static JwtProviderService jwtProviderService() { - TokenConfig tokenConfig = new TokenConfig(originIss, originAccessExpire, originRefreshExpire, originSecretKey); + TokenConfig tokenConfig = + new TokenConfig(originIss, originAccessExpire, originRefreshExpire, originSecretKey, adminKey); return new JwtProviderService(tokenConfig); } diff --git a/src/test/java/com/moabam/support/fixture/MemberInfoSearchFixture.java b/src/test/java/com/moabam/support/fixture/MemberInfoSearchFixture.java index e4bfa647..6f43c132 100644 --- a/src/test/java/com/moabam/support/fixture/MemberInfoSearchFixture.java +++ b/src/test/java/com/moabam/support/fixture/MemberInfoSearchFixture.java @@ -22,9 +22,9 @@ public static List friendMemberInfo() { public static List friendMemberInfo(long total) { return List.of( - new MemberInfo(NICKNAME, PROFILE_IMAGE, MORNING_EGG, NIGHT_EGG, INTRO, total, BadgeType.MORNING_BIRTH, + new MemberInfo(NICKNAME, PROFILE_IMAGE, MORNING_EGG, NIGHT_EGG, INTRO, total, BadgeType.BIRTH, 0, 0, 0), - new MemberInfo(NICKNAME, PROFILE_IMAGE, MORNING_EGG, NIGHT_EGG, INTRO, total, BadgeType.NIGHT_BIRTH, + new MemberInfo(NICKNAME, PROFILE_IMAGE, MORNING_EGG, NIGHT_EGG, INTRO, total, BadgeType.LEVEL10, 0, 0, 0) ); } @@ -32,9 +32,9 @@ public static List friendMemberInfo(long total) { public static List myInfo(String morningImage, String nightImage) { return List.of( new MemberInfo(NICKNAME, PROFILE_IMAGE, morningImage, nightImage, INTRO, TOTAL_CERTIFY_COUNT, - BadgeType.MORNING_BIRTH, 0, 0, 0), + BadgeType.BIRTH, 0, 0, 0), new MemberInfo(NICKNAME, PROFILE_IMAGE, morningImage, nightImage, INTRO, TOTAL_CERTIFY_COUNT, - BadgeType.NIGHT_BIRTH, 0, 0, 0) + BadgeType.LEVEL10, 0, 0, 0) ); } } diff --git a/src/test/resources/application.yml b/src/test/resources/application.yml index c485b58d..7083d3d7 100644 --- a/src/test/resources/application.yml +++ b/src/test/resources/application.yml @@ -70,8 +70,11 @@ token: access-expire: 100000 refresh-expire: 150000 secret-key: testestestestestestestestestesttestestestestestestestestestest + admin-secret: testestestestestestestestestesttestestestestestestestestestest allows: + admin-domain: "localhost" + domain: "localhost" origin: - "https://test.com" - "https://test.com"