code
stringlengths
41
34.3k
lang
stringclasses
8 values
review
stringlengths
1
4.74k
@@ -0,0 +1,47 @@ +package nextstep.security.authentication; + +import java.util.List; +import java.util.Map; +import org.springframework.boot.context.properties.ConfigurationProperties; + +@ConfigurationProperties(prefix = "spring.security.oauth2.client") +public class OAuth2ClientProperties { + + private Map<String, Registration> registrations; + private Map<String, Provider> providers; + + public Map<String, Registration> getRegistrations() { + return registrations; + } + + public void setRegistrations(Map<String, Registration> registrations) { + this.registrations = registrations; + } + + public Map<String, Provider> getProviders() { + return providers; + } + + public void setProviders(Map<String, Provider> providers) { + this.providers = providers; + } + + public record Registration( + String provider, + String clientId, + String clientSecret, + String redirectUri, + String authorizationGrantType, + List<String> scope + ) { + } + + public record Provider( + String name, + String authorizationUri, + String tokenUri, + String userInfoUri, + String accessTokenUri + ) { + } +}
Java
๋‹จ์ˆœํ•œ ์„ค์ • ํŒŒ์ผ์€ record๋ฅผ ํ™œ์šฉํ•˜๋ฉด ์ฝ”๋“œ๊ฐ€ ๊น”๋”ํ•ด์งˆ ๊ฒƒ ๊ฐ™์•„์š”~
@@ -0,0 +1,95 @@ +package nextstep.security.authentication; + +import jakarta.servlet.FilterChain; +import jakarta.servlet.ServletException; +import jakarta.servlet.ServletRequest; +import jakarta.servlet.ServletResponse; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; +import java.io.IOException; +import java.util.Set; +import nextstep.app.domain.Member; +import nextstep.app.domain.MemberRepository; +import nextstep.security.authentication.OAuth2ClientProperties.Provider; +import nextstep.security.authentication.OAuth2ClientProperties.Registration; +import nextstep.security.context.HttpSessionSecurityContextRepository; +import nextstep.security.context.SecurityContextHolder; +import org.springframework.http.HttpMethod; +import org.springframework.web.filter.GenericFilterBean; + +public class OAuth2AuthenticationFilter extends GenericFilterBean { + + private static final String REQUEST_URI = "/login/oauth2/code"; + + private final OAuth2ClientProperties oAuth2ClientProperties; + private final OAuth2AccessTokenClient oAuth2AccessTokenClient; + private final MemberRepository memberRepository; + private final OAuth2UserInfoClient oAuth2UserInfoClient; + + public OAuth2AuthenticationFilter(OAuth2ClientProperties oAuth2ClientProperties, + MemberRepository memberRepository, + OAuth2AccessTokenClient oAuth2AccessTokenClient, + OAuth2UserInfoClient oAuth2UserInfoClient) { + this.oAuth2AccessTokenClient = oAuth2AccessTokenClient; + this.oAuth2UserInfoClient = oAuth2UserInfoClient; + this.oAuth2ClientProperties = oAuth2ClientProperties; + this.memberRepository = memberRepository; + } + + @Override + public void doFilter(ServletRequest request, ServletResponse response, + FilterChain filterChain) throws IOException, ServletException { + HttpServletRequest httpRequest = (HttpServletRequest) request; + HttpServletResponse httpResponse = (HttpServletResponse) response; + + String requestURI = httpRequest.getRequestURI(); + String method = httpRequest.getMethod(); + + String registrationSource = null; + if (requestURI.startsWith(REQUEST_URI)) { + registrationSource = getRegistrationId(requestURI); + } + + if (registrationSource != null && method.equals(HttpMethod.GET.name())) { + Registration registration = oAuth2ClientProperties.getRegistrations().get(registrationSource); + Provider provider = oAuth2ClientProperties.getProviders().get(registrationSource); + + String code = httpRequest.getParameter("code"); + + String accessToken = oAuth2AccessTokenClient.getAccessToken(code, registration, provider); + + OAuth2UserInfo userInfo = oAuth2UserInfoClient.getUserInfo(accessToken, provider); + + String email = userInfo.getEmail(); + Member member = memberRepository.findByEmail(email) + .orElse(new Member( + email, "", userInfo.getName(), userInfo.getPictureUrl(), Set.of("USER") + )); + + UsernamePasswordAuthenticationToken authentication = + UsernamePasswordAuthenticationToken.authenticated( + member.getEmail(), null, member.getRoles()); + + SecurityContextHolder.getContext().setAuthentication(authentication); + + httpRequest.getSession(true).setAttribute( + HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY, + SecurityContextHolder.getContext() + ); + + httpResponse.sendRedirect("/"); + return; + } + + filterChain.doFilter(request, response); + } + + private String getRegistrationId(String requestURI) { + for (String registrationId : oAuth2ClientProperties.getRegistrations().keySet()) { + if (requestURI.contains(registrationId)) { + return registrationId; + } + } + return null; + } +}
Java
์ง€๊ธˆ์€ ํด๋ž˜์Šค ๋‚ด๋ถ€์—์„œ ๊ฐ์ฒด๋ฅผ ์ง์ ‘ ์ƒ์„ฑํ•˜๊ณ  ์žˆ๋Š”๋ฐ, ์Šคํ”„๋ง ์ฒ ํ•™์—์„œ๋Š” ๋‚ด๋ถ€์—์„œ ๊ฐ์ฒด๋ฅผ ์ƒ์„ฑํ•˜๊ธฐ ๋ณด๋‹จ ์ƒ์„ฑ์ž ์ฃผ์ž…์„ ํ†ตํ•ด DI ๋ฐ›๋Š” ๊ฒƒ์„ ๊ถŒ์žฅํ•˜๊ณ  ์žˆ์Šต๋‹ˆ๋‹ค. ์ƒ์„ฑ์ž ์ฃผ์ž… ๋ฐฉ์‹์œผ๋กœ ๋ณ€๊ฒฝํ•  ๊ฒฝ์šฐ ์–ด๋–ค ์žฅ์ ์ด ์žˆ์„์ง€ ๊ณ ๋ฏผํ•ด ๋ณด์•„์š”.
@@ -0,0 +1,95 @@ +package nextstep.security.authentication; + +import jakarta.servlet.FilterChain; +import jakarta.servlet.ServletException; +import jakarta.servlet.ServletRequest; +import jakarta.servlet.ServletResponse; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; +import java.io.IOException; +import java.util.Set; +import nextstep.app.domain.Member; +import nextstep.app.domain.MemberRepository; +import nextstep.security.authentication.OAuth2ClientProperties.Provider; +import nextstep.security.authentication.OAuth2ClientProperties.Registration; +import nextstep.security.context.HttpSessionSecurityContextRepository; +import nextstep.security.context.SecurityContextHolder; +import org.springframework.http.HttpMethod; +import org.springframework.web.filter.GenericFilterBean; + +public class OAuth2AuthenticationFilter extends GenericFilterBean { + + private static final String REQUEST_URI = "/login/oauth2/code"; + + private final OAuth2ClientProperties oAuth2ClientProperties; + private final OAuth2AccessTokenClient oAuth2AccessTokenClient; + private final MemberRepository memberRepository; + private final OAuth2UserInfoClient oAuth2UserInfoClient; + + public OAuth2AuthenticationFilter(OAuth2ClientProperties oAuth2ClientProperties, + MemberRepository memberRepository, + OAuth2AccessTokenClient oAuth2AccessTokenClient, + OAuth2UserInfoClient oAuth2UserInfoClient) { + this.oAuth2AccessTokenClient = oAuth2AccessTokenClient; + this.oAuth2UserInfoClient = oAuth2UserInfoClient; + this.oAuth2ClientProperties = oAuth2ClientProperties; + this.memberRepository = memberRepository; + } + + @Override + public void doFilter(ServletRequest request, ServletResponse response, + FilterChain filterChain) throws IOException, ServletException { + HttpServletRequest httpRequest = (HttpServletRequest) request; + HttpServletResponse httpResponse = (HttpServletResponse) response; + + String requestURI = httpRequest.getRequestURI(); + String method = httpRequest.getMethod(); + + String registrationSource = null; + if (requestURI.startsWith(REQUEST_URI)) { + registrationSource = getRegistrationId(requestURI); + } + + if (registrationSource != null && method.equals(HttpMethod.GET.name())) { + Registration registration = oAuth2ClientProperties.getRegistrations().get(registrationSource); + Provider provider = oAuth2ClientProperties.getProviders().get(registrationSource); + + String code = httpRequest.getParameter("code"); + + String accessToken = oAuth2AccessTokenClient.getAccessToken(code, registration, provider); + + OAuth2UserInfo userInfo = oAuth2UserInfoClient.getUserInfo(accessToken, provider); + + String email = userInfo.getEmail(); + Member member = memberRepository.findByEmail(email) + .orElse(new Member( + email, "", userInfo.getName(), userInfo.getPictureUrl(), Set.of("USER") + )); + + UsernamePasswordAuthenticationToken authentication = + UsernamePasswordAuthenticationToken.authenticated( + member.getEmail(), null, member.getRoles()); + + SecurityContextHolder.getContext().setAuthentication(authentication); + + httpRequest.getSession(true).setAttribute( + HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY, + SecurityContextHolder.getContext() + ); + + httpResponse.sendRedirect("/"); + return; + } + + filterChain.doFilter(request, response); + } + + private String getRegistrationId(String requestURI) { + for (String registrationId : oAuth2ClientProperties.getRegistrations().keySet()) { + if (requestURI.contains(registrationId)) { + return registrationId; + } + } + return null; + } +}
Java
์ง€๊ธˆ์€ OAuth ์ œ๊ณต์ž๋ฅผ ์ถ”๊ฐ€ํ•  ๋•Œ๋งˆ๋‹ค ํ•ด๋‹น ์ฝ”๋“œ๋ฅผ ์ˆ˜์ •ํ•ด์•ผ ํ•˜๋Š” ๋ฌธ์ œ๊ฐ€ ์žˆ๋„ค์š”! OAuth2ClientProperties์—์„œ ๋™์ ์œผ๋กœ ์ฐพ์•„ ์ฒ˜๋ฆฌํ•˜๋„๋ก ๊ฐœ์„ ํ•ด๋ณด๋ฉด ์–ด๋–จ๊นŒ์š”?
@@ -0,0 +1,33 @@ +spring: + security: + oauth2: + client: + registrations: + github: + provider: "github" + client-id: "Ov23lijfjg9lkGyYVDXN" + client-secret: "YOUR_GITHUB_CLIENT_SECRET" + scope: + - read:user + redirect-uri: "http://localhost:8080/login/oauth2/code/github" + authorization-grant-type: authorization_code + google: + provider: "google" + client-id: "349246449409-h7hgk8kms3k8d7tgal8nesbh24h34t0d.apps.googleusercontent.com" + client-secret: "YOUR_GOOGLE_CLIENT_SECRET" + scope: + - email + - profile + redirect-uri: "http://localhost:8080/login/oauth2/code/google" + authorization-grant-type: authorization_code + providers: + github: + authorization-uri: "https://github.com/login/oauth/authorize?" + token-uri: "https://github.com/login/oauth/access_token" + access-token-uri: "http://localhost:8089/login/oauth/access_token" + user-info-uri: "https://api.github.com/user" + google: + authorization-uri: "https://accounts.google.com/o/oauth2/v2/auth?" + token-uri: "https://oauth2.googleapis.com/token" + access-token-uri: "http://localhost:8089/login/oauth/access_token" + user-info-uri: "https://www.googleapis.com/oauth2/v3/userinfo"
Unknown
์†Œ์†Œํ•˜์ง€๋งŒ.. IntelliJ๋ฅผ ์‚ฌ์šฉํ•˜์‹ค ๊ฒฝ์šฐ ์ž๋™์œผ๋กœ ๊ฐœํ–‰์„ ์ถ”๊ฐ€ํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค! https://velog.io/@d-h-k/intellij-%ED%8C%8C%EC%9D%BC%EB%81%9D%EC%97%90-%EA%B0%9C%ED%96%89%EC%9D%84-%EC%9E%90%EB%8F%99%EC%9C%BC%EB%A1%9C-%EC%B6%94%EA%B0%80%ED%95%98%EB%8A%94-%EB%B0%A9%EB%B2%95
@@ -0,0 +1,71 @@ +package nextstep.security.authentication; + +import jakarta.servlet.FilterChain; +import jakarta.servlet.ServletException; +import jakarta.servlet.ServletRequest; +import jakarta.servlet.ServletResponse; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; +import java.io.IOException; +import java.util.Map; +import nextstep.security.authentication.OAuth2ClientProperties.Provider; +import nextstep.security.authentication.OAuth2ClientProperties.Registration; +import org.springframework.http.HttpMethod; +import org.springframework.web.filter.GenericFilterBean; +import org.springframework.web.util.UriComponentsBuilder; + +public class OAuth2LoginRedirectFilter extends GenericFilterBean { + + private static final String REQUEST_URI = "/oauth2/authorization"; + + private final Map<String, Registration> registrations; + private final Map<String, Provider> providers; + + public OAuth2LoginRedirectFilter(OAuth2ClientProperties properties) { + this.registrations = properties.getRegistrations(); + this.providers = properties.getProviders(); + } + + @Override + public void doFilter(ServletRequest request, + ServletResponse response, + FilterChain chain) throws IOException, ServletException { + HttpServletRequest httpServletRequest = (HttpServletRequest) request; + HttpServletResponse httpServletResponse = (HttpServletResponse) response; + + String requestURI = httpServletRequest.getRequestURI(); + String method = httpServletRequest.getMethod(); + + String registrationSource = null; + if (requestURI.startsWith(REQUEST_URI)) { + registrationSource = getRegistrationId(requestURI); + } + + if (registrationSource != null && method.equals(HttpMethod.GET.name())) { + Registration registration = registrations.get(registrationSource); + Provider provider = providers.get(registrationSource); + + String redirectUri = UriComponentsBuilder.fromHttpUrl(provider.authorizationUri()) + .queryParam("client_id", registration.clientId()) + .queryParam("scope", String.join(" ", registration.scope())) + .queryParam("response_type", "code") + .queryParam("redirect_uri", registration.redirectUri()) + .build() + .toUriString(); + + httpServletResponse.sendRedirect(redirectUri); + return; + } + + chain.doFilter(request, response); + } + + private String getRegistrationId(String requestURI) { + for (String registrationId : registrations.keySet()) { + if (requestURI.contains(registrationId)) { + return registrationId; + } + } + return null; + } +}
Java
OAuth2 ์ŠคํŽ™์—์„œ๋Š” scope๋ฅผ ๊ณต๋ฐฑ์œผ๋กœ ๊ตฌ๋ถ„ํ•˜๋Š” ๊ฒƒ์ด ํ‘œ์ค€์ž…๋‹ˆ๋‹ค. ์ง€๊ธˆ์€ ์‰ผํ‘œ๋กœ ๊ตฌ๋ถ„ํ•˜๊ณ  ์žˆ๋Š”๋ฐ, ํ‘œ์ค€์— ๋งž๊ฒŒ ์ˆ˜์ •ํ•ด๋ณด๋ฉด ์–ด๋–จ๊นŒ์š”? ์ฐธ๊ณ : https://datatracker.ietf.org/doc/html/rfc6749#section-3.3 ![image](https://github.com/user-attachments/assets/6d590f38-dc07-46df-9b83-9cb916389362)
@@ -0,0 +1,71 @@ +package nextstep.security.authentication; + +import jakarta.servlet.FilterChain; +import jakarta.servlet.ServletException; +import jakarta.servlet.ServletRequest; +import jakarta.servlet.ServletResponse; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; +import java.io.IOException; +import java.util.Map; +import nextstep.security.authentication.OAuth2ClientProperties.Provider; +import nextstep.security.authentication.OAuth2ClientProperties.Registration; +import org.springframework.http.HttpMethod; +import org.springframework.web.filter.GenericFilterBean; +import org.springframework.web.util.UriComponentsBuilder; + +public class OAuth2LoginRedirectFilter extends GenericFilterBean { + + private static final String REQUEST_URI = "/oauth2/authorization"; + + private final Map<String, Registration> registrations; + private final Map<String, Provider> providers; + + public OAuth2LoginRedirectFilter(OAuth2ClientProperties properties) { + this.registrations = properties.getRegistrations(); + this.providers = properties.getProviders(); + } + + @Override + public void doFilter(ServletRequest request, + ServletResponse response, + FilterChain chain) throws IOException, ServletException { + HttpServletRequest httpServletRequest = (HttpServletRequest) request; + HttpServletResponse httpServletResponse = (HttpServletResponse) response; + + String requestURI = httpServletRequest.getRequestURI(); + String method = httpServletRequest.getMethod(); + + String registrationSource = null; + if (requestURI.startsWith(REQUEST_URI)) { + registrationSource = getRegistrationId(requestURI); + } + + if (registrationSource != null && method.equals(HttpMethod.GET.name())) { + Registration registration = registrations.get(registrationSource); + Provider provider = providers.get(registrationSource); + + String redirectUri = UriComponentsBuilder.fromHttpUrl(provider.authorizationUri()) + .queryParam("client_id", registration.clientId()) + .queryParam("scope", String.join(" ", registration.scope())) + .queryParam("response_type", "code") + .queryParam("redirect_uri", registration.redirectUri()) + .build() + .toUriString(); + + httpServletResponse.sendRedirect(redirectUri); + return; + } + + chain.doFilter(request, response); + } + + private String getRegistrationId(String requestURI) { + for (String registrationId : registrations.keySet()) { + if (requestURI.contains(registrationId)) { + return registrationId; + } + } + return null; + } +}
Java
authorization_grant_type ๊ฐ’์„ ์ถ”๊ฐ€ํ•ด์ฃผ์‹  ์ด์œ ๊ฐ€ ์žˆ์„๊นŒ์š”?
@@ -0,0 +1,71 @@ +package nextstep.security.authentication; + +import jakarta.servlet.FilterChain; +import jakarta.servlet.ServletException; +import jakarta.servlet.ServletRequest; +import jakarta.servlet.ServletResponse; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; +import java.io.IOException; +import java.util.Map; +import nextstep.security.authentication.OAuth2ClientProperties.Provider; +import nextstep.security.authentication.OAuth2ClientProperties.Registration; +import org.springframework.http.HttpMethod; +import org.springframework.web.filter.GenericFilterBean; +import org.springframework.web.util.UriComponentsBuilder; + +public class OAuth2LoginRedirectFilter extends GenericFilterBean { + + private static final String REQUEST_URI = "/oauth2/authorization"; + + private final Map<String, Registration> registrations; + private final Map<String, Provider> providers; + + public OAuth2LoginRedirectFilter(OAuth2ClientProperties properties) { + this.registrations = properties.getRegistrations(); + this.providers = properties.getProviders(); + } + + @Override + public void doFilter(ServletRequest request, + ServletResponse response, + FilterChain chain) throws IOException, ServletException { + HttpServletRequest httpServletRequest = (HttpServletRequest) request; + HttpServletResponse httpServletResponse = (HttpServletResponse) response; + + String requestURI = httpServletRequest.getRequestURI(); + String method = httpServletRequest.getMethod(); + + String registrationSource = null; + if (requestURI.startsWith(REQUEST_URI)) { + registrationSource = getRegistrationId(requestURI); + } + + if (registrationSource != null && method.equals(HttpMethod.GET.name())) { + Registration registration = registrations.get(registrationSource); + Provider provider = providers.get(registrationSource); + + String redirectUri = UriComponentsBuilder.fromHttpUrl(provider.authorizationUri()) + .queryParam("client_id", registration.clientId()) + .queryParam("scope", String.join(" ", registration.scope())) + .queryParam("response_type", "code") + .queryParam("redirect_uri", registration.redirectUri()) + .build() + .toUriString(); + + httpServletResponse.sendRedirect(redirectUri); + return; + } + + chain.doFilter(request, response); + } + + private String getRegistrationId(String requestURI) { + for (String registrationId : registrations.keySet()) { + if (requestURI.contains(registrationId)) { + return registrationId; + } + } + return null; + } +}
Java
provider.getAuthorizationUri()์— ๋Œ€ํ•œ ๊ฐ’๋„ UriComponentsBuilder์—์„œ ๊ฐ™์ด ์ƒ์„ฑํ•ด๋ณด๋ฉด ์ข‹๊ฒ ์Šต๋‹ˆ๋‹ค~
@@ -0,0 +1,27 @@ +package nextstep.security.authentication; + +import java.util.Map; +import nextstep.security.authentication.OAuth2ClientProperties.Provider; +import org.springframework.http.HttpEntity; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpMethod; +import org.springframework.http.ResponseEntity; +import org.springframework.web.client.RestTemplate; + +public class OAuth2UserInfoClient { + + private final RestTemplate restTemplate = new RestTemplate(); + + public OAuth2UserInfo getUserInfo(String accessToken, Provider provider) { + HttpHeaders httpHeaders = new HttpHeaders(); + httpHeaders.add("Authorization", "Bearer " + accessToken); + + HttpEntity<Void> request = new HttpEntity<>(httpHeaders); + ResponseEntity<Map> response = restTemplate.exchange(provider.userInfoUri(), HttpMethod.GET, + request, Map.class); + + Map<String, Object> attributes = response.getBody(); + + return OAuth2UserInfoFactory.getOAuth2UserInfo(provider.name(), attributes); + } +}
Java
์ง€๊ธˆ์€ Map์˜ ํ˜•ํƒœ๋กœ ์‘๋‹ตํ•˜๊ณ  ์žˆ๋Š”๋ฐ, ์ด๋Ÿฌํ•œ ์ฝ”๋“œ๋Š” ํƒ€์ž… ์•ˆ์ •์„ฑ์ด ๋ถ€์กฑํ•˜๊ณ  ๊ฐ€๋…์„ฑ์ด ๋–จ์–ด์ง€๊ฒŒ ๋ฉ๋‹ˆ๋‹ค. OAuth ์ œ๊ณต์ž๋งˆ๋‹ค ๋‹ค๋ฅธ ์‘๋‹ต ์ •๋ณด๊ฐ€ ์žˆ์„ ์ˆ˜ ์žˆ๋Š” ์ƒํ™ฉ์—์„œ ์•ˆ์ •์„ฑ๊ณผ ์œ ์—ฐ์„ฑ์„ ์–ด๋–ป๊ฒŒ ๊ฐ™์ด ๊ฐ€์ ธ๊ฐˆ ์ˆ˜ ์žˆ์„์ง€ ๊ณ ๋ฏผํ•ด๋ณด๋ฉด ์žฌ๋ฏธ์žˆ๊ฒ ๋„ค์š” ใ…Žใ…Ž
@@ -0,0 +1,47 @@ +package nextstep.security.authentication; + +import java.util.List; +import java.util.Map; +import org.springframework.boot.context.properties.ConfigurationProperties; + +@ConfigurationProperties(prefix = "spring.security.oauth2.client") +public class OAuth2ClientProperties { + + private Map<String, Registration> registrations; + private Map<String, Provider> providers; + + public Map<String, Registration> getRegistrations() { + return registrations; + } + + public void setRegistrations(Map<String, Registration> registrations) { + this.registrations = registrations; + } + + public Map<String, Provider> getProviders() { + return providers; + } + + public void setProviders(Map<String, Provider> providers) { + this.providers = providers; + } + + public record Registration( + String provider, + String clientId, + String clientSecret, + String redirectUri, + String authorizationGrantType, + List<String> scope + ) { + } + + public record Provider( + String name, + String authorizationUri, + String tokenUri, + String userInfoUri, + String accessTokenUri + ) { + } +}
Java
ํ™•์‹คํžˆ ์—„์ฒญ ๊น”๋”ํ•ด์ง€๋„ค์š”!
@@ -0,0 +1,33 @@ +spring: + security: + oauth2: + client: + registrations: + github: + provider: "github" + client-id: "Ov23lijfjg9lkGyYVDXN" + client-secret: "YOUR_GITHUB_CLIENT_SECRET" + scope: + - read:user + redirect-uri: "http://localhost:8080/login/oauth2/code/github" + authorization-grant-type: authorization_code + google: + provider: "google" + client-id: "349246449409-h7hgk8kms3k8d7tgal8nesbh24h34t0d.apps.googleusercontent.com" + client-secret: "YOUR_GOOGLE_CLIENT_SECRET" + scope: + - email + - profile + redirect-uri: "http://localhost:8080/login/oauth2/code/google" + authorization-grant-type: authorization_code + providers: + github: + authorization-uri: "https://github.com/login/oauth/authorize?" + token-uri: "https://github.com/login/oauth/access_token" + access-token-uri: "http://localhost:8089/login/oauth/access_token" + user-info-uri: "https://api.github.com/user" + google: + authorization-uri: "https://accounts.google.com/o/oauth2/v2/auth?" + token-uri: "https://oauth2.googleapis.com/token" + access-token-uri: "http://localhost:8089/login/oauth/access_token" + user-info-uri: "https://www.googleapis.com/oauth2/v3/userinfo"
Unknown
ํ—‰ ์ด๋Ÿฐ ๊ทœ์น™์ด ์žˆ๋Š”์ง€๋„ ๋ชฐ๋ž๋„ค์š” ,, ์ข‹์€ ์ธ์‚ฌ์ดํŠธ ๊ฐ์‚ฌํ•ฉ๋‹ˆ๋‹ค!
@@ -0,0 +1,95 @@ +package nextstep.security.authentication; + +import jakarta.servlet.FilterChain; +import jakarta.servlet.ServletException; +import jakarta.servlet.ServletRequest; +import jakarta.servlet.ServletResponse; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; +import java.io.IOException; +import java.util.Set; +import nextstep.app.domain.Member; +import nextstep.app.domain.MemberRepository; +import nextstep.security.authentication.OAuth2ClientProperties.Provider; +import nextstep.security.authentication.OAuth2ClientProperties.Registration; +import nextstep.security.context.HttpSessionSecurityContextRepository; +import nextstep.security.context.SecurityContextHolder; +import org.springframework.http.HttpMethod; +import org.springframework.web.filter.GenericFilterBean; + +public class OAuth2AuthenticationFilter extends GenericFilterBean { + + private static final String REQUEST_URI = "/login/oauth2/code"; + + private final OAuth2ClientProperties oAuth2ClientProperties; + private final OAuth2AccessTokenClient oAuth2AccessTokenClient; + private final MemberRepository memberRepository; + private final OAuth2UserInfoClient oAuth2UserInfoClient; + + public OAuth2AuthenticationFilter(OAuth2ClientProperties oAuth2ClientProperties, + MemberRepository memberRepository, + OAuth2AccessTokenClient oAuth2AccessTokenClient, + OAuth2UserInfoClient oAuth2UserInfoClient) { + this.oAuth2AccessTokenClient = oAuth2AccessTokenClient; + this.oAuth2UserInfoClient = oAuth2UserInfoClient; + this.oAuth2ClientProperties = oAuth2ClientProperties; + this.memberRepository = memberRepository; + } + + @Override + public void doFilter(ServletRequest request, ServletResponse response, + FilterChain filterChain) throws IOException, ServletException { + HttpServletRequest httpRequest = (HttpServletRequest) request; + HttpServletResponse httpResponse = (HttpServletResponse) response; + + String requestURI = httpRequest.getRequestURI(); + String method = httpRequest.getMethod(); + + String registrationSource = null; + if (requestURI.startsWith(REQUEST_URI)) { + registrationSource = getRegistrationId(requestURI); + } + + if (registrationSource != null && method.equals(HttpMethod.GET.name())) { + Registration registration = oAuth2ClientProperties.getRegistrations().get(registrationSource); + Provider provider = oAuth2ClientProperties.getProviders().get(registrationSource); + + String code = httpRequest.getParameter("code"); + + String accessToken = oAuth2AccessTokenClient.getAccessToken(code, registration, provider); + + OAuth2UserInfo userInfo = oAuth2UserInfoClient.getUserInfo(accessToken, provider); + + String email = userInfo.getEmail(); + Member member = memberRepository.findByEmail(email) + .orElse(new Member( + email, "", userInfo.getName(), userInfo.getPictureUrl(), Set.of("USER") + )); + + UsernamePasswordAuthenticationToken authentication = + UsernamePasswordAuthenticationToken.authenticated( + member.getEmail(), null, member.getRoles()); + + SecurityContextHolder.getContext().setAuthentication(authentication); + + httpRequest.getSession(true).setAttribute( + HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY, + SecurityContextHolder.getContext() + ); + + httpResponse.sendRedirect("/"); + return; + } + + filterChain.doFilter(request, response); + } + + private String getRegistrationId(String requestURI) { + for (String registrationId : oAuth2ClientProperties.getRegistrations().keySet()) { + if (requestURI.contains(registrationId)) { + return registrationId; + } + } + return null; + } +}
Java
์žฅ์ ์œผ๋กœ๋Š” ๊ฒฐ๊ตญ ๊ตฌํ˜„์ฒด์— ์˜์กดํ•˜์ง€ ์•Š๋Š” ๊ตฌ์กฐ๋กœ ๋ณ€๊ฒฝ๋˜๊ธฐ ๋•Œ๋ฌธ์—, ๊ฒฐํ•ฉ๋„๋ฅผ ๋‚ฎ์ถ”๊ณ  ์œ ์—ฐํ•˜๊ฒŒ ํ™•์žฅํ•ด ๋‚˜๊ฐˆ ์ˆ˜ ์žˆ์„ ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค! ๋˜ํ•œ TestDouble ๊ตฌํ˜„ํ•˜๊ธฐ๋„ ํ›จ ์ˆ˜์›”ํ•  ๊ฒƒ ๊ฐ™์•„์š”! ์žฌ์—ฐ๋‹˜์ด ์ƒ๊ฐํ•˜์‹œ๋Š” ์ด๊ฑฐ ์™ธ์—๋„ ์–ป์„ ์ˆ˜ ์žˆ๋Š” ์ค‘์š” ์ด์ ์ด ์žˆ์œผ์‹ค๊นŒ์š”? ( ๋ฐ˜์˜์€ [c887083](https://github.com/next-step/spring-security-oauth2/pull/7/commits/c8870831fea1cb685a7614a49c33229242b8e442) ๋กœ ์ง„ํ–‰ํ–ˆ์Šต๋‹ˆ๋‹ค.)
@@ -0,0 +1,71 @@ +package nextstep.security.authentication; + +import jakarta.servlet.FilterChain; +import jakarta.servlet.ServletException; +import jakarta.servlet.ServletRequest; +import jakarta.servlet.ServletResponse; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; +import java.io.IOException; +import java.util.Map; +import nextstep.security.authentication.OAuth2ClientProperties.Provider; +import nextstep.security.authentication.OAuth2ClientProperties.Registration; +import org.springframework.http.HttpMethod; +import org.springframework.web.filter.GenericFilterBean; +import org.springframework.web.util.UriComponentsBuilder; + +public class OAuth2LoginRedirectFilter extends GenericFilterBean { + + private static final String REQUEST_URI = "/oauth2/authorization"; + + private final Map<String, Registration> registrations; + private final Map<String, Provider> providers; + + public OAuth2LoginRedirectFilter(OAuth2ClientProperties properties) { + this.registrations = properties.getRegistrations(); + this.providers = properties.getProviders(); + } + + @Override + public void doFilter(ServletRequest request, + ServletResponse response, + FilterChain chain) throws IOException, ServletException { + HttpServletRequest httpServletRequest = (HttpServletRequest) request; + HttpServletResponse httpServletResponse = (HttpServletResponse) response; + + String requestURI = httpServletRequest.getRequestURI(); + String method = httpServletRequest.getMethod(); + + String registrationSource = null; + if (requestURI.startsWith(REQUEST_URI)) { + registrationSource = getRegistrationId(requestURI); + } + + if (registrationSource != null && method.equals(HttpMethod.GET.name())) { + Registration registration = registrations.get(registrationSource); + Provider provider = providers.get(registrationSource); + + String redirectUri = UriComponentsBuilder.fromHttpUrl(provider.authorizationUri()) + .queryParam("client_id", registration.clientId()) + .queryParam("scope", String.join(" ", registration.scope())) + .queryParam("response_type", "code") + .queryParam("redirect_uri", registration.redirectUri()) + .build() + .toUriString(); + + httpServletResponse.sendRedirect(redirectUri); + return; + } + + chain.doFilter(request, response); + } + + private String getRegistrationId(String requestURI) { + for (String registrationId : registrations.keySet()) { + if (requestURI.contains(registrationId)) { + return registrationId; + } + } + return null; + } +}
Java
๋†€๋ž๊ฒŒ๋„ ์—ฌ๊ธฐ grant_type ๋งˆ์ € yml์— ๋“ฑ๋กํ•˜๊ณ ์ž ```yml github: provider: "github" client-id: "Ov23lijfjg9lkGyYVDXN" client-secret: "YOUR_GITHUB_CLIENT_SECRET" scope: - read:user redirect-uri: "http://localhost:8080/login/oauth2/code/github" authorization-grant-type: authorization_code ``` ์ž‘์„ฑ ํ•œ ํ›„ // **as-is** ```java public String getAccessToken(String code, Registration registration, Provider provider) { HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_JSON); Map<String, String> params = new HashMap<>(); params.put("code", code); params.put("client_id", registration.clientId()); params.put("client_secret", registration.clientSecret()); params.put("redirect_uri", registration.redirectUri()); params.put("grant_type", "authorization_code"); ``` // **to-be** ```java public String getAccessToken(String code, Registration registration, Provider provider) { HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_JSON); Map<String, String> params = new HashMap<>(); params.put("code", code); params.put("client_id", registration.clientId()); params.put("client_secret", registration.clientSecret()); params.put("redirect_uri", registration.redirectUri()); params.put("grant_type", registration.authorizationGrantType()); ``` ๋กœ ํ•˜๋ ค๋˜๊ฒŒ ์–ด์ฉŒ๋‹ค๊ฐ€ ํ˜๋Ÿฌ๊ฐ„๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค...๐Ÿ˜ฑ
@@ -0,0 +1,71 @@ +package nextstep.security.authentication; + +import jakarta.servlet.FilterChain; +import jakarta.servlet.ServletException; +import jakarta.servlet.ServletRequest; +import jakarta.servlet.ServletResponse; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; +import java.io.IOException; +import java.util.Map; +import nextstep.security.authentication.OAuth2ClientProperties.Provider; +import nextstep.security.authentication.OAuth2ClientProperties.Registration; +import org.springframework.http.HttpMethod; +import org.springframework.web.filter.GenericFilterBean; +import org.springframework.web.util.UriComponentsBuilder; + +public class OAuth2LoginRedirectFilter extends GenericFilterBean { + + private static final String REQUEST_URI = "/oauth2/authorization"; + + private final Map<String, Registration> registrations; + private final Map<String, Provider> providers; + + public OAuth2LoginRedirectFilter(OAuth2ClientProperties properties) { + this.registrations = properties.getRegistrations(); + this.providers = properties.getProviders(); + } + + @Override + public void doFilter(ServletRequest request, + ServletResponse response, + FilterChain chain) throws IOException, ServletException { + HttpServletRequest httpServletRequest = (HttpServletRequest) request; + HttpServletResponse httpServletResponse = (HttpServletResponse) response; + + String requestURI = httpServletRequest.getRequestURI(); + String method = httpServletRequest.getMethod(); + + String registrationSource = null; + if (requestURI.startsWith(REQUEST_URI)) { + registrationSource = getRegistrationId(requestURI); + } + + if (registrationSource != null && method.equals(HttpMethod.GET.name())) { + Registration registration = registrations.get(registrationSource); + Provider provider = providers.get(registrationSource); + + String redirectUri = UriComponentsBuilder.fromHttpUrl(provider.authorizationUri()) + .queryParam("client_id", registration.clientId()) + .queryParam("scope", String.join(" ", registration.scope())) + .queryParam("response_type", "code") + .queryParam("redirect_uri", registration.redirectUri()) + .build() + .toUriString(); + + httpServletResponse.sendRedirect(redirectUri); + return; + } + + chain.doFilter(request, response); + } + + private String getRegistrationId(String requestURI) { + for (String registrationId : registrations.keySet()) { + if (requestURI.contains(registrationId)) { + return registrationId; + } + } + return null; + } +}
Java
[8071959](https://github.com/next-step/spring-security-oauth2/pull/7/commits/807195919a73c89b2ec6c0d52063d15b7ee1d46f) ๋กœ ๋ฐ˜์˜ํ–ˆ์Šต๋‹ˆ๋‹ค.
@@ -0,0 +1,27 @@ +package nextstep.security.authentication; + +import java.util.Map; +import nextstep.security.authentication.OAuth2ClientProperties.Provider; +import org.springframework.http.HttpEntity; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpMethod; +import org.springframework.http.ResponseEntity; +import org.springframework.web.client.RestTemplate; + +public class OAuth2UserInfoClient { + + private final RestTemplate restTemplate = new RestTemplate(); + + public OAuth2UserInfo getUserInfo(String accessToken, Provider provider) { + HttpHeaders httpHeaders = new HttpHeaders(); + httpHeaders.add("Authorization", "Bearer " + accessToken); + + HttpEntity<Void> request = new HttpEntity<>(httpHeaders); + ResponseEntity<Map> response = restTemplate.exchange(provider.userInfoUri(), HttpMethod.GET, + request, Map.class); + + Map<String, Object> attributes = response.getBody(); + + return OAuth2UserInfoFactory.getOAuth2UserInfo(provider.name(), attributes); + } +}
Java
[cde6bc2](https://github.com/next-step/spring-security-oauth2/pull/7/commits/cde6bc20d18375290b619a33c29a5f859e3a541e) ๋กœ ์ง„ํ–‰ํ•ด๋ณด์•˜์Šต๋‹ˆ๋‹ค! ํ˜„ ๊ตฌ์กฐ์ƒ ๊ฐ™์€ ๊ฐ’์„ ๋ฐ˜ํ™˜ํ•˜๊ณ  ์žˆ๊ธฐ ๋•Œ๋ฌธ์— ๊ฐ„๊ณผํ•˜๊ณ  ์žˆ๋˜ ๋ถ€๋ถ„์ธ๋ฐ์š”. ํ•˜๋ฉด ํ• ์ˆ˜๋ก ํ™•์‹คํžˆ ์ด๋Ÿฐ ํ”„๋ ˆ์ž„์›Œํฌ์—์„œ๋Š” ํ™•์žฅ์„ฑ ์žˆ๊ฒŒ ๊ตฌ์„ฑํ•˜๋Š”๊ฒŒ ์ค‘์š”ํ•˜๋‹ค๊ณ  ๋А๊ปด์ง€๋„ค์š”!
@@ -0,0 +1,95 @@ +package nextstep.security.authentication; + +import jakarta.servlet.FilterChain; +import jakarta.servlet.ServletException; +import jakarta.servlet.ServletRequest; +import jakarta.servlet.ServletResponse; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; +import java.io.IOException; +import java.util.Set; +import nextstep.app.domain.Member; +import nextstep.app.domain.MemberRepository; +import nextstep.security.authentication.OAuth2ClientProperties.Provider; +import nextstep.security.authentication.OAuth2ClientProperties.Registration; +import nextstep.security.context.HttpSessionSecurityContextRepository; +import nextstep.security.context.SecurityContextHolder; +import org.springframework.http.HttpMethod; +import org.springframework.web.filter.GenericFilterBean; + +public class OAuth2AuthenticationFilter extends GenericFilterBean { + + private static final String REQUEST_URI = "/login/oauth2/code"; + + private final OAuth2ClientProperties oAuth2ClientProperties; + private final OAuth2AccessTokenClient oAuth2AccessTokenClient; + private final MemberRepository memberRepository; + private final OAuth2UserInfoClient oAuth2UserInfoClient; + + public OAuth2AuthenticationFilter(OAuth2ClientProperties oAuth2ClientProperties, + MemberRepository memberRepository, + OAuth2AccessTokenClient oAuth2AccessTokenClient, + OAuth2UserInfoClient oAuth2UserInfoClient) { + this.oAuth2AccessTokenClient = oAuth2AccessTokenClient; + this.oAuth2UserInfoClient = oAuth2UserInfoClient; + this.oAuth2ClientProperties = oAuth2ClientProperties; + this.memberRepository = memberRepository; + } + + @Override + public void doFilter(ServletRequest request, ServletResponse response, + FilterChain filterChain) throws IOException, ServletException { + HttpServletRequest httpRequest = (HttpServletRequest) request; + HttpServletResponse httpResponse = (HttpServletResponse) response; + + String requestURI = httpRequest.getRequestURI(); + String method = httpRequest.getMethod(); + + String registrationSource = null; + if (requestURI.startsWith(REQUEST_URI)) { + registrationSource = getRegistrationId(requestURI); + } + + if (registrationSource != null && method.equals(HttpMethod.GET.name())) { + Registration registration = oAuth2ClientProperties.getRegistrations().get(registrationSource); + Provider provider = oAuth2ClientProperties.getProviders().get(registrationSource); + + String code = httpRequest.getParameter("code"); + + String accessToken = oAuth2AccessTokenClient.getAccessToken(code, registration, provider); + + OAuth2UserInfo userInfo = oAuth2UserInfoClient.getUserInfo(accessToken, provider); + + String email = userInfo.getEmail(); + Member member = memberRepository.findByEmail(email) + .orElse(new Member( + email, "", userInfo.getName(), userInfo.getPictureUrl(), Set.of("USER") + )); + + UsernamePasswordAuthenticationToken authentication = + UsernamePasswordAuthenticationToken.authenticated( + member.getEmail(), null, member.getRoles()); + + SecurityContextHolder.getContext().setAuthentication(authentication); + + httpRequest.getSession(true).setAttribute( + HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY, + SecurityContextHolder.getContext() + ); + + httpResponse.sendRedirect("/"); + return; + } + + filterChain.doFilter(request, response); + } + + private String getRegistrationId(String requestURI) { + for (String registrationId : oAuth2ClientProperties.getRegistrations().keySet()) { + if (requestURI.contains(registrationId)) { + return registrationId; + } + } + return null; + } +}
Java
> ์žฅ์ ์œผ๋กœ๋Š” ๊ฒฐ๊ตญ ๊ตฌํ˜„์ฒด์— ์˜์กดํ•˜์ง€ ์•Š๋Š” ๊ตฌ์กฐ๋กœ ๋ณ€๊ฒฝ๋˜๊ธฐ ๋•Œ๋ฌธ์—, ๊ฒฐํ•ฉ๋„๋ฅผ ๋‚ฎ์ถ”๊ณ  ์œ ์—ฐํ•˜๊ฒŒ ํ™•์žฅํ•ด ๋‚˜๊ฐˆ ์ˆ˜ ์žˆ์„ ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค! ๋˜ํ•œ TestDouble ๊ตฌํ˜„ํ•˜๊ธฐ๋„ ํ›จ ์ˆ˜์›”ํ•  ๊ฒƒ ๊ฐ™์•„์š”! ์žฌ์—ฐ๋‹˜์ด ์ƒ๊ฐํ•˜์‹œ๋Š” ์ด๊ฑฐ ์™ธ์—๋„ ์–ป์„ ์ˆ˜ ์žˆ๋Š” ์ค‘์š” ์ด์ ์ด ์žˆ์œผ์‹ค๊นŒ์š”? ( ๋ฐ˜์˜์€ [c887083](https://github.com/next-step/spring-security-oauth2/pull/7/commits/c8870831fea1cb685a7614a49c33229242b8e442) ๋กœ ์ง„ํ–‰ํ–ˆ์Šต๋‹ˆ๋‹ค.) ๋งž์Šต๋‹ˆ๋‹ค. ๊ฒฐํ•ฉ๋„๋ฅผ ๋‚ฎ์ถœ ์ˆ˜ ์žˆ๋‹ค๋Š” ์ ์ด ๊ฐ€์žฅ ํฐ ์žฅ์ ์ผ ๊ฒƒ ๊ฐ™์•„์š”. ์ถ”๊ฐ€๋กœ, Spring์˜ DI ์ปจํ…Œ์ด๋„ˆ๋ฅผ ํ™œ์šฉํ•˜๋ฉด ๊ฐ์ฒด์˜ ์ƒ๋ช…์ฃผ๊ธฐ๋ฅผ ํ”„๋ ˆ์ž„์›Œํฌ๊ฐ€ ๊ด€๋ฆฌํ•ด ์ฃผ๊ธฐ ๋•Œ๋ฌธ์— ๊ฐ์ฒด ์ƒ์„ฑ ๋ฐ ๊ด€๋ฆฌ ๋ถ€๋‹ด๋„ ์ค„์–ด๋“ค ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค ใ…Žใ…Ž
@@ -0,0 +1,95 @@ +package nextstep.security.authentication; + +import jakarta.servlet.FilterChain; +import jakarta.servlet.ServletException; +import jakarta.servlet.ServletRequest; +import jakarta.servlet.ServletResponse; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; +import java.io.IOException; +import java.util.Set; +import nextstep.app.domain.Member; +import nextstep.app.domain.MemberRepository; +import nextstep.security.authentication.OAuth2ClientProperties.Provider; +import nextstep.security.authentication.OAuth2ClientProperties.Registration; +import nextstep.security.context.HttpSessionSecurityContextRepository; +import nextstep.security.context.SecurityContextHolder; +import org.springframework.http.HttpMethod; +import org.springframework.web.filter.GenericFilterBean; + +public class OAuth2AuthenticationFilter extends GenericFilterBean { + + private static final String REQUEST_URI = "/login/oauth2/code"; + + private final OAuth2ClientProperties oAuth2ClientProperties; + private final OAuth2AccessTokenClient oAuth2AccessTokenClient; + private final MemberRepository memberRepository; + private final OAuth2UserInfoClient oAuth2UserInfoClient; + + public OAuth2AuthenticationFilter(OAuth2ClientProperties oAuth2ClientProperties, + MemberRepository memberRepository, + OAuth2AccessTokenClient oAuth2AccessTokenClient, + OAuth2UserInfoClient oAuth2UserInfoClient) { + this.oAuth2AccessTokenClient = oAuth2AccessTokenClient; + this.oAuth2UserInfoClient = oAuth2UserInfoClient; + this.oAuth2ClientProperties = oAuth2ClientProperties; + this.memberRepository = memberRepository; + } + + @Override + public void doFilter(ServletRequest request, ServletResponse response, + FilterChain filterChain) throws IOException, ServletException { + HttpServletRequest httpRequest = (HttpServletRequest) request; + HttpServletResponse httpResponse = (HttpServletResponse) response; + + String requestURI = httpRequest.getRequestURI(); + String method = httpRequest.getMethod(); + + String registrationSource = null; + if (requestURI.startsWith(REQUEST_URI)) { + registrationSource = getRegistrationId(requestURI); + } + + if (registrationSource != null && method.equals(HttpMethod.GET.name())) { + Registration registration = oAuth2ClientProperties.getRegistrations().get(registrationSource); + Provider provider = oAuth2ClientProperties.getProviders().get(registrationSource); + + String code = httpRequest.getParameter("code"); + + String accessToken = oAuth2AccessTokenClient.getAccessToken(code, registration, provider); + + OAuth2UserInfo userInfo = oAuth2UserInfoClient.getUserInfo(accessToken, provider); + + String email = userInfo.getEmail(); + Member member = memberRepository.findByEmail(email) + .orElse(new Member( + email, "", userInfo.getName(), userInfo.getPictureUrl(), Set.of("USER") + )); + + UsernamePasswordAuthenticationToken authentication = + UsernamePasswordAuthenticationToken.authenticated( + member.getEmail(), null, member.getRoles()); + + SecurityContextHolder.getContext().setAuthentication(authentication); + + httpRequest.getSession(true).setAttribute( + HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY, + SecurityContextHolder.getContext() + ); + + httpResponse.sendRedirect("/"); + return; + } + + filterChain.doFilter(request, response); + } + + private String getRegistrationId(String requestURI) { + for (String registrationId : oAuth2ClientProperties.getRegistrations().keySet()) { + if (requestURI.contains(registrationId)) { + return registrationId; + } + } + return null; + } +}
Java
์ œ๊ณต์ž๊ฐ€ ์—†์„ ๊ฒฝ์šฐ ๋ฌด์‹œํ•œ๋‹ค. vs ์˜ˆ์™ธ๋ฅผ ๋ฐœ์ƒํ•œ๋‹ค. ์–ด๋–ค ๋ฐฉํ–ฅ์„ฑ์ด ์ข‹์„์ง€ ๊ณ ๋ฏผํ•ด ๋ณด์•„์š”.
@@ -78,6 +78,7 @@ public List<ReviewPhoto> createReviewPhoto(Long reviewId, List<MultipartFile> re List<ReviewPhoto> reviewPhotoList = new ArrayList<>(); List<String> photoUrls = new ArrayList<>(); + if(reviewPhotos == null) return reviewPhotoList; reviewPhotos.forEach(multipartFile -> { try { photoUrls.add(s3Util.upload(multipartFile)); @@ -87,7 +88,6 @@ public List<ReviewPhoto> createReviewPhoto(Long reviewId, List<MultipartFile> re }); photoUrls.forEach(photoUrl -> reviewPhotoList.add(reviewPhotoPort.save(new ReviewPhoto(reviewId, photoUrl)))); - return reviewPhotoList; }
Java
์ด ๋ถ€๋ถ„์€ ์–ด๋–ค ์˜๋ฏธ์ธ๊ฐ€์š”?
@@ -78,6 +78,7 @@ public List<ReviewPhoto> createReviewPhoto(Long reviewId, List<MultipartFile> re List<ReviewPhoto> reviewPhotoList = new ArrayList<>(); List<String> photoUrls = new ArrayList<>(); + if(reviewPhotos == null) return reviewPhotoList; reviewPhotos.forEach(multipartFile -> { try { photoUrls.add(s3Util.upload(multipartFile)); @@ -87,7 +88,6 @@ public List<ReviewPhoto> createReviewPhoto(Long reviewId, List<MultipartFile> re }); photoUrls.forEach(photoUrl -> reviewPhotoList.add(reviewPhotoPort.save(new ReviewPhoto(reviewId, photoUrl)))); - return reviewPhotoList; }
Java
์ด ๋ถ€๋ถ„์€ ์–ด๋–ค ์˜๋ฏธ์ธ๊ฐ€์š”?
@@ -0,0 +1,34 @@ +package com.luckytree.shop.utils; + +import com.fasterxml.jackson.databind.ObjectMapper; +import org.springframework.http.MediaType; +import org.springframework.http.converter.json.AbstractJackson2HttpMessageConverter; +import org.springframework.stereotype.Component; + +import java.lang.reflect.Type; + +@Component +public class MultipartJackson2HttpMessageConverter extends AbstractJackson2HttpMessageConverter { + + /** + * Converter for support http request with header Content-Type: multipart/form-data + */ + public MultipartJackson2HttpMessageConverter(ObjectMapper objectMapper) { + super(objectMapper, MediaType.APPLICATION_OCTET_STREAM); + } + + @Override + public boolean canWrite(Class<?> clazz, MediaType mediaType) { + return false; + } + + @Override + public boolean canWrite(Type type, Class<?> clazz, MediaType mediaType) { + return false; + } + + @Override + protected boolean canWrite(MediaType mediaType) { + return false; + } +}
Java
์ด ํด๋ž˜์Šค๋ฅผ ์‚ฌ์šฉํ•˜๋Š” ๊ณณ์ด ์–ด๋”˜๊ฐ€์š”?
@@ -32,12 +32,11 @@ public class ReviewController { private final ReviewUseCase reviewUseCase; @Operation(summary = "๋ฆฌ๋ทฐ ๋“ฑ๋ก") - @PostMapping(consumes = MediaType.MULTIPART_FORM_DATA_VALUE) + @PostMapping(consumes = {MediaType.APPLICATION_JSON_VALUE, MediaType.MULTIPART_FORM_DATA_VALUE}) public ResponseEntity<CreateReviewResponse> createReview( - @RequestBody @Valid CreateReviewRequest createReviewRequest, - @RequestPart("reviewPhotos") @Valid List<MultipartFile> reviewPhotos) { + @RequestPart("createReviewRequest") @Valid CreateReviewRequest createReviewRequest, + @RequestPart(value = "reviewPhotos", required = false) @Valid List<MultipartFile> reviewPhotos) { Review review = reviewUseCase.create(createReviewRequest.toDomain(Long.valueOf(SecurityContextHolder.getContext().getAuthentication().getPrincipal().toString()))); - List<ReviewPhoto> reviewPhotoList = reviewUseCase.createReviewPhoto(review.getId(), reviewPhotos); return ResponseEntity.ok(new CreateReviewResponse(review, reviewPhotoList));
Java
๋ฆฌํ€˜์ŠคํŠธ๋ฐ”๋””๊ฐ€ ์‚ฌ๋ผ์กŒ๋Š”๋ฐ, ์ด ๊ฒฝ์šฐ์—๋„ ํด๋ผ์ด์–ธํŠธ์—์„œ JSON ํ˜•์‹์˜ Body ํƒœ๊ทธ ๋ฐ์ดํ„ฐ๋ฅผ ๋ฐ›์•„์˜ค๋Š” ๋ฐ์— ๋ฌธ์ œ๊ฐ€ ์—†๋‚˜์š”?
@@ -78,6 +78,7 @@ public List<ReviewPhoto> createReviewPhoto(Long reviewId, List<MultipartFile> re List<ReviewPhoto> reviewPhotoList = new ArrayList<>(); List<String> photoUrls = new ArrayList<>(); + if(reviewPhotos == null) return reviewPhotoList; reviewPhotos.forEach(multipartFile -> { try { photoUrls.add(s3Util.upload(multipartFile)); @@ -87,7 +88,6 @@ public List<ReviewPhoto> createReviewPhoto(Long reviewId, List<MultipartFile> re }); photoUrls.forEach(photoUrl -> reviewPhotoList.add(reviewPhotoPort.save(new ReviewPhoto(reviewId, photoUrl)))); - return reviewPhotoList; }
Java
๋ฆฌ๋ทฐ ์ƒ์„ฑ ์‹œ ํฌํ† ๋ฅผ ์„ ํƒํ•˜์ง€ ์•Š์•„๋„ ์ด ์„œ๋น„์Šค๊ฐ€ ์‹คํ–‰๋˜์–ด์„œ ์„ ํƒ๋˜์ง€ ์•Š์•˜์„ ๋•Œ ๋ฐ”๋กœ ๋น ์ ธ๋‚˜๊ฐ€๊ฒŒ ํ•œ๊ฒ๋‹ˆ๋‹ค
@@ -0,0 +1,34 @@ +package com.luckytree.shop.utils; + +import com.fasterxml.jackson.databind.ObjectMapper; +import org.springframework.http.MediaType; +import org.springframework.http.converter.json.AbstractJackson2HttpMessageConverter; +import org.springframework.stereotype.Component; + +import java.lang.reflect.Type; + +@Component +public class MultipartJackson2HttpMessageConverter extends AbstractJackson2HttpMessageConverter { + + /** + * Converter for support http request with header Content-Type: multipart/form-data + */ + public MultipartJackson2HttpMessageConverter(ObjectMapper objectMapper) { + super(objectMapper, MediaType.APPLICATION_OCTET_STREAM); + } + + @Override + public boolean canWrite(Class<?> clazz, MediaType mediaType) { + return false; + } + + @Override + public boolean canWrite(Type type, Class<?> clazz, MediaType mediaType) { + return false; + } + + @Override + protected boolean canWrite(MediaType mediaType) { + return false; + } +}
Java
swagger์—์„œ ๋ฆฌ๋ทฐ ์ƒ์„ฑ API์— multipartfile์„ ์‚ฌ์šฉํ•ด์„œ ๊ทธ๊ฑฐ ์‚ฌ์šฉํ•˜๊ฒŒ ๋งŒ๋“ค์–ด์ฃผ๋Š” ํด๋ž˜์Šค์ž…๋‹ˆ๋‹ค
@@ -32,12 +32,11 @@ public class ReviewController { private final ReviewUseCase reviewUseCase; @Operation(summary = "๋ฆฌ๋ทฐ ๋“ฑ๋ก") - @PostMapping(consumes = MediaType.MULTIPART_FORM_DATA_VALUE) + @PostMapping(consumes = {MediaType.APPLICATION_JSON_VALUE, MediaType.MULTIPART_FORM_DATA_VALUE}) public ResponseEntity<CreateReviewResponse> createReview( - @RequestBody @Valid CreateReviewRequest createReviewRequest, - @RequestPart("reviewPhotos") @Valid List<MultipartFile> reviewPhotos) { + @RequestPart("createReviewRequest") @Valid CreateReviewRequest createReviewRequest, + @RequestPart(value = "reviewPhotos", required = false) @Valid List<MultipartFile> reviewPhotos) { Review review = reviewUseCase.create(createReviewRequest.toDomain(Long.valueOf(SecurityContextHolder.getContext().getAuthentication().getPrincipal().toString()))); - List<ReviewPhoto> reviewPhotoList = reviewUseCase.createReviewPhoto(review.getId(), reviewPhotos); return ResponseEntity.ok(new CreateReviewResponse(review, reviewPhotoList));
Java
swagger๋ž‘ postman์—์„œ ํ™•์ธํ–ˆ๊ณ  ์˜คํžˆ๋ ค ๋ฆฌํ€˜์ŠคํŠธ๋ฐ”๋””๋ฅผ ์ผ์„ ๋•Œ ์•ˆ๋ผ์„œ ๋ฐ”๊ฟจ์Šต๋‹ˆ๋‹ค. ์ด์œ ๋Š” ์ฐพ์•„๋ณด๊ฒ ์Šต๋‹ˆ๋‹ค
@@ -0,0 +1,95 @@ +'use client'; + +import { useState } from 'react'; +import { useGlobalModal } from './useGlobalModal'; +import { useParams } from 'next/navigation'; +import { createReview } from '@/api/reivews'; + +export interface IReviewState { + valid: boolean; + comment: string; + score: number; +} + +export function useCreateReview(initialState: IReviewState) { + const [state, setState] = useState(initialState); + const { openModal, closeAllModal } = useGlobalModal(); // ์ „์—ญ ๋ชจ๋‹ฌ ์ œ์–ด + const params = useParams<{ id: string }>(); + + /** ์œ ํšจ์„ฑ ๊ฒ€์‚ฌ */ + const validate = ( + name: string, + value: string | number, + prev: IReviewState, + ) => { + let valid = false; + + // ํ‰์  0์  ์ด์ƒ + if (name === 'score') { + valid = + typeof value === 'number' && value > 0 && prev.comment?.length > 0; + } + + // ๋นˆ ๋ฌธ์ž์—ด ์œ ํšจ์„ฑ ๊ฒ€์‚ฌ + if (name === 'comment' && typeof value === 'string') { + valid = value.trim().length > 0 && prev.score > 0; + } + + return valid; + }; + + // ๊ณตํ†ต ํ•ธ๋“ค๋Ÿฌ ํ•จ์ˆ˜ + const handleChange = ( + e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>, + ) => { + const { name, value } = e.currentTarget; + const nextValue = name === 'score' ? Number(value) : value; + + setState((prevState) => { + const valid = validate(name, nextValue, prevState); + return { + ...prevState, + valid, + [name]: nextValue, + }; + }); + }; + + // form submit ํ•ธ๋“ค๋Ÿฌ ํ•จ์ˆ˜ + const handleSubmit = async (e: React.FormEvent<HTMLFormElement>) => { + e.preventDefault(); + const res = await createReview(params?.id, state); + if (res) { + closeAllModal(); + } + + // const formData = new FormData(e.currentTarget); + + // for (const [name, value] of formData) { + // console.log(`${name} = ${value}`); // key1 = value1, then key2 = value2 + // } + }; + + // ์ž‘์„ฑ ์ค‘๊ฐ„์— ์ดํƒˆ ์‹œ ์‹คํ–‰ ํ•จ์ˆ˜ + const handleClose = (e: React.MouseEvent<HTMLButtonElement, MouseEvent>) => { + // ์ž‘์„ฑ๋œ ๋‚ด์šฉ์ด ์žˆ์„ ๋•Œ๋งŒ ํ‘œ์‹œ + if (state.score !== 0 || state.comment?.trim()?.length !== 0) { + openModal({ + content: ( + <> + ์ •๋ง ๋‚˜๊ฐ€์‹œ๊ฒ ์–ด์š”? + <br /> + ์ž‘์„ฑ๋œ ๋‚ด์šฉ์ด ๋ชจ๋‘ ์‚ญ์ œ๋ฉ๋‹ˆ๋‹ค. + </> + ), + confirmType: 'Alert', + onConfirm: closeAllModal, + buttonPosition: 'right', + }); + } else { + closeAllModal(); + } + }; + + return { state, handleChange, handleSubmit, handleClose }; +}
Unknown
P4: ๋‚˜์ค‘์— ์—๋Ÿฌ์ฒ˜๋ฆฌ๋งŒ ์ž˜ ๋„ฃ์–ด์ฃผ์‹œ๋ฉด ์ข‹์„ ๊ฒƒ ๊ฐ™์•„์š”! ๊ณ ์ƒํ•˜์…จ์Šต๋‹ˆ๋‹ค~
@@ -13,15 +13,13 @@ import nextstep.security.context.SecurityContextHolderFilter; import nextstep.security.matcher.AnyRequestMatcher; import nextstep.security.matcher.MvcRequestMatcher; -import nextstep.security.matcher.RequestMatcherEntry; import nextstep.security.userdetails.UserDetails; import nextstep.security.userdetails.UserDetailsService; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.EnableAspectJAutoProxy; import org.springframework.http.HttpMethod; -import java.util.ArrayList; import java.util.List; import java.util.Set; @@ -50,20 +48,31 @@ public SecuredMethodInterceptor securedMethodInterceptor() { return new SecuredMethodInterceptor(); } +// @Bean +// public SecuredAspect securedAspect() { +// return new SecuredAspect(); +// } + + @Bean - public SecuredAspect securedAspect() { - return new SecuredAspect(); + public RoleHierarchy roleHierarchy() { + return RoleHierarchyImpl.with() + .role("ADMIN") + .implies("USER","GUEST") + .build(); } + @Bean public RequestMatcherDelegatingAuthorizationManager requestAuthorizationManager() { - List<RequestMatcherEntry<AuthorizationManager>> mappings = new ArrayList<>(); - mappings.add(new RequestMatcherEntry<>(new MvcRequestMatcher(HttpMethod.GET, "/members/me"), new AuthenticatedAuthorizationManager())); - mappings.add(new RequestMatcherEntry<>(new MvcRequestMatcher(HttpMethod.GET, "/members"), new HasAuthorityAuthorizationManager("ADMIN"))); - mappings.add(new RequestMatcherEntry<>(new MvcRequestMatcher(HttpMethod.GET, "/search"), new PermitAllAuthorizationManager())); - mappings.add(new RequestMatcherEntry<>(new MvcRequestMatcher(HttpMethod.POST, "/private"), new DenyAllAuthorizationManager())); - mappings.add(new RequestMatcherEntry<>(new AnyRequestMatcher(), new PermitAllAuthorizationManager())); - return new RequestMatcherDelegatingAuthorizationManager(mappings); + return RequestMatcherAuthorizationManagerBuilder.withRoleHierarchy(roleHierarchy()) + .authenticated(new MvcRequestMatcher(HttpMethod.GET, "/members/me")) + .permitAll(new MvcRequestMatcher(HttpMethod.GET, "/search")) + .hasAuthority("ADMIN", new MvcRequestMatcher(HttpMethod.GET, "/members")) + .hasAuthority("USER", new MvcRequestMatcher(HttpMethod.POST, "/hierarchy")) + .denyAll(new MvcRequestMatcher(HttpMethod.POST, "/private")) + .permitAll(new AnyRequestMatcher()) + .build(); } @Bean
Java
์š”๊ตฌ์‚ฌํ•ญ ์„ค์ • ๐Ÿ‘
@@ -13,15 +13,13 @@ import nextstep.security.context.SecurityContextHolderFilter; import nextstep.security.matcher.AnyRequestMatcher; import nextstep.security.matcher.MvcRequestMatcher; -import nextstep.security.matcher.RequestMatcherEntry; import nextstep.security.userdetails.UserDetails; import nextstep.security.userdetails.UserDetailsService; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.EnableAspectJAutoProxy; import org.springframework.http.HttpMethod; -import java.util.ArrayList; import java.util.List; import java.util.Set; @@ -50,20 +48,31 @@ public SecuredMethodInterceptor securedMethodInterceptor() { return new SecuredMethodInterceptor(); } +// @Bean +// public SecuredAspect securedAspect() { +// return new SecuredAspect(); +// } + + @Bean - public SecuredAspect securedAspect() { - return new SecuredAspect(); + public RoleHierarchy roleHierarchy() { + return RoleHierarchyImpl.with() + .role("ADMIN") + .implies("USER","GUEST") + .build(); } + @Bean public RequestMatcherDelegatingAuthorizationManager requestAuthorizationManager() { - List<RequestMatcherEntry<AuthorizationManager>> mappings = new ArrayList<>(); - mappings.add(new RequestMatcherEntry<>(new MvcRequestMatcher(HttpMethod.GET, "/members/me"), new AuthenticatedAuthorizationManager())); - mappings.add(new RequestMatcherEntry<>(new MvcRequestMatcher(HttpMethod.GET, "/members"), new HasAuthorityAuthorizationManager("ADMIN"))); - mappings.add(new RequestMatcherEntry<>(new MvcRequestMatcher(HttpMethod.GET, "/search"), new PermitAllAuthorizationManager())); - mappings.add(new RequestMatcherEntry<>(new MvcRequestMatcher(HttpMethod.POST, "/private"), new DenyAllAuthorizationManager())); - mappings.add(new RequestMatcherEntry<>(new AnyRequestMatcher(), new PermitAllAuthorizationManager())); - return new RequestMatcherDelegatingAuthorizationManager(mappings); + return RequestMatcherAuthorizationManagerBuilder.withRoleHierarchy(roleHierarchy()) + .authenticated(new MvcRequestMatcher(HttpMethod.GET, "/members/me")) + .permitAll(new MvcRequestMatcher(HttpMethod.GET, "/search")) + .hasAuthority("ADMIN", new MvcRequestMatcher(HttpMethod.GET, "/members")) + .hasAuthority("USER", new MvcRequestMatcher(HttpMethod.POST, "/hierarchy")) + .denyAll(new MvcRequestMatcher(HttpMethod.POST, "/private")) + .permitAll(new AnyRequestMatcher()) + .build(); } @Bean
Java
๊ถŒํ•œ ๊ณ„์ธต์„ ์กฐํšŒํ•˜๋„๋ก ํ•˜์…จ๊ตฐ์š”! ์„ค์ •์ด ์ž˜ ๋˜์—ˆ๋Š”์ง€ ํ™•์ธํ•˜๊ธฐ ์œ„ํ•ด ์ข‹์€ ์‹œ๋„์ž…๋‹ˆ๋‹ค :) ๋‹จ, roleHierarchy()์„ ๋งค๋ฒˆ ์„ค์ •ํ•  ๋•Œ ๋งˆ๋‹ค ์ฃผ์ž…ํ•ด์ฃผ๋Š” ํ˜•ํƒœ๋กœ ๊ตฌํ˜„ํ•ด์ฃผ์…จ๋Š”๋ฐ ํ•œ๋ฒˆ๋งŒ ์„ค์ •ํ•˜๋Š” ๋ฐฉ๋ฒ•์€ ์—†์„ ์ง€ ๊ณ ๋ฏผํ•ด๋ณด์…”๋„ ์ข‹์„ ๊ฒƒ ๊ฐ™์•„์š”!
@@ -2,33 +2,43 @@ import jakarta.servlet.FilterChain; import jakarta.servlet.ServletException; +import jakarta.servlet.ServletRequest; +import jakarta.servlet.ServletResponse; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; import nextstep.security.authentication.Authentication; import nextstep.security.context.SecurityContextHolder; -import org.springframework.web.filter.OncePerRequestFilter; +import org.springframework.web.filter.GenericFilterBean; import java.io.IOException; -public class CheckAuthenticationFilter extends OncePerRequestFilter { +public class CheckAuthenticationFilter extends GenericFilterBean { - private final RequestMatcherDelegatingAuthorizationManager requestMatcherDelegatingAuthorizationManager; + private final AuthorizationManager<HttpServletRequest> authorizationManager; + private final AuthorizationDeniedHandler authorizationDeniedHandler; - public CheckAuthenticationFilter(RequestMatcherDelegatingAuthorizationManager requestMatcherDelegatingAuthorizationManager) { - this.requestMatcherDelegatingAuthorizationManager = requestMatcherDelegatingAuthorizationManager; + public CheckAuthenticationFilter(AuthorizationManager<HttpServletRequest> authorizationManager) { + this(authorizationManager, response -> response.setStatus(HttpServletResponse.SC_FORBIDDEN)); + } + + public CheckAuthenticationFilter(AuthorizationManager<HttpServletRequest> authorizationManager + , AuthorizationDeniedHandler authorizationDeniedHandler + ) { + this.authorizationManager = authorizationManager; + this.authorizationDeniedHandler = authorizationDeniedHandler; } @Override - protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException { + public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); - AuthorizationDecision authorizationDecision = requestMatcherDelegatingAuthorizationManager.check(authentication, request); + AuthorizationDecision authorizationDecision = authorizationManager.check(authentication, (HttpServletRequest) request); if (authorizationDecision.isDeny()) { - response.setStatus(HttpServletResponse.SC_FORBIDDEN); + authorizationDeniedHandler.handle((HttpServletResponse) response); return; } - filterChain.doFilter(request, response); + chain.doFilter(request, response); } }
Java
๋งŒ์•ฝ ์ธ์ฆ์ด ๋˜์ง€์•Š์€ ๊ฒฝ์šฐ 401์‘๋‹ต์ด ํ•„์š”ํ•  ์ˆ˜ ์žˆ๋Š”๋ฐ ํ˜„์žฌ๋Š” ๋ชจ๋“  ์—๋กœ ์ƒํ™ฉ์—์„œ 403์ด ์‘๋‹ต์ด ๋˜๋Š” ๊ฒƒ ๊ฐ™๋„ค์š”!
@@ -0,0 +1,11 @@ +package nextstep.security.authorization; + +import java.util.Collection; + +public class NullRoleHierarchy implements RoleHierarchy { + + @Override + public Collection<String> getReachableGrantedAuthorities(Collection<String> authorities) { + return authorities; + } +}
Java
๋„ ๊ฐ์ฒด ํŒจํ„ด ๐Ÿ‘
@@ -0,0 +1,57 @@ +package nextstep.security.authorization; + +import java.util.*; + +public class RoleHierarchyImpl implements RoleHierarchy { + private final Map<String, Set<String>> hierarchyPath; + + private RoleHierarchyImpl(Map<String, Set<String>> hierarchyPath) { + this.hierarchyPath = hierarchyPath; + } + + @Override + public Collection<String> getReachableGrantedAuthorities(Collection<String> authorities) { + Set<String> grantedAuthorities = new HashSet<>(); + + for (String authority : authorities) { + if (hierarchyPath.get(authority) != null) { + grantedAuthorities.addAll(hierarchyPath.get(authority)); + } + } + + return grantedAuthorities; + } + + public static RoleBuilder with() { + return new RoleBuilder(); + } + + public static class RoleBuilder { + private static final Map<String, Set<String>> hierarchy = new HashMap<>(); + private String role; + + public RoleBuilder role(String role) { + this.role = role; + hierarchy.put(role, new HashSet<>(Set.of(role))); + return this; + } + + public ImpliesBuilder implies(String... implies) { + hierarchy.get(role).addAll(Set.of(implies)); + + for (int i = 0; i < implies.length; i++) { + Set<String> paths = hierarchy.getOrDefault(implies[i], new HashSet<>()); + paths.addAll(List.of(implies).subList(i, implies.length)); + hierarchy.put(implies[i], paths); + } + + return new ImpliesBuilder(); + } + + public static class ImpliesBuilder { + public RoleHierarchyImpl build() { + return new RoleHierarchyImpl(hierarchy); + } + } + } +}
Java
RoleHierarchy ๊ตฌํ˜„ ์ž˜ ํ•ด์ฃผ์…จ์Šต๋‹ˆ๋‹ค ๐Ÿ‘
@@ -1,24 +0,0 @@ -package nextstep.security.authorization; - -import nextstep.security.authentication.Authentication; - -public class HasAuthorityAuthorizationManager implements AuthorizationManager { - private final String allowRole; - - public HasAuthorityAuthorizationManager(String allowRole) { - this.allowRole = allowRole; - } - - @Override - public AuthorizationDecision check(Authentication authentication, Object object) { - if (authentication == null || !authentication.isAuthenticated()) { - return AuthorizationDecision.deny(); - } - - if (authentication.getAuthorities().contains(allowRole)) { - return AuthorizationDecision.granted(); - } - - return AuthorizationDecision.deny(); - } -}
Java
์‹œํ๋ฆฌํ‹ฐ ์ฝ”๋“œ๋ฅผ ๋ณด๋ฉด AuthorityAuthorizationManager ์™€ AuthoritiesAuthorizationManager๊ฐ€ ์žˆ๋Š”๋ฐ์š” ์ด ๊ตฌ์กฐ๋ฅผ ๋ถ„์„ํ•ด๋ณด์‹œ๊ณ  HasAuthorityAuthorizationManager ์— ๋Œ€์ž…ํ•ด๋ณด์…”๋„ ์ข‹์„ ๊ฒƒ ๊ฐ™์•„์š”.
@@ -0,0 +1,38 @@ +package nextstep.security.authorization; + +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; + +import java.util.Collection; +import java.util.List; +import java.util.Set; +import java.util.stream.Stream; + +import static org.assertj.core.api.Assertions.assertThat; + +class RoleHierarchyImplTest { + + @DisplayName("๊ณ„์ธต๋ณ„๋กœ ํ—ˆ์šฉ๋˜๋Š” ๊ถŒํ•œ์„ ๋ฐ˜ํ™˜ํ•œ๋‹ค") + @ParameterizedTest + @MethodSource("๊ณ„์ธต๋ณ„๋กœ_ํ—ˆ์šฉ๋˜๋Š”_๊ถŒํ•œ") + void reachableGrantedAuthorities(String role, Set<String> grantedAuthorities) { + RoleHierarchyImpl roleHierarchy = RoleHierarchyImpl.with() + .role("ADMIN") + .implies("USER","GUEST") + .build(); + + Collection<String> reachableGrantedAuthorities = roleHierarchy.getReachableGrantedAuthorities(List.of(role)); + + assertThat(reachableGrantedAuthorities).isEqualTo(grantedAuthorities); + } + + private static Stream<Arguments> ๊ณ„์ธต๋ณ„๋กœ_ํ—ˆ์šฉ๋˜๋Š”_๊ถŒํ•œ() { + return Stream.of( + Arguments.of("ADMIN", Set.of("ADMIN", "USER","GUEST")), + Arguments.of("USER", Set.of("USER", "GUEST")), + Arguments.of("GUEST", Set.of("GUEST")) + ); + } +}
Java
Role Hierarchy ํ…Œ์ŠคํŠธ ๐Ÿ‘
@@ -13,15 +13,13 @@ import nextstep.security.context.SecurityContextHolderFilter; import nextstep.security.matcher.AnyRequestMatcher; import nextstep.security.matcher.MvcRequestMatcher; -import nextstep.security.matcher.RequestMatcherEntry; import nextstep.security.userdetails.UserDetails; import nextstep.security.userdetails.UserDetailsService; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.EnableAspectJAutoProxy; import org.springframework.http.HttpMethod; -import java.util.ArrayList; import java.util.List; import java.util.Set; @@ -50,20 +48,31 @@ public SecuredMethodInterceptor securedMethodInterceptor() { return new SecuredMethodInterceptor(); } +// @Bean +// public SecuredAspect securedAspect() { +// return new SecuredAspect(); +// } + + @Bean - public SecuredAspect securedAspect() { - return new SecuredAspect(); + public RoleHierarchy roleHierarchy() { + return RoleHierarchyImpl.with() + .role("ADMIN") + .implies("USER","GUEST") + .build(); } + @Bean public RequestMatcherDelegatingAuthorizationManager requestAuthorizationManager() { - List<RequestMatcherEntry<AuthorizationManager>> mappings = new ArrayList<>(); - mappings.add(new RequestMatcherEntry<>(new MvcRequestMatcher(HttpMethod.GET, "/members/me"), new AuthenticatedAuthorizationManager())); - mappings.add(new RequestMatcherEntry<>(new MvcRequestMatcher(HttpMethod.GET, "/members"), new HasAuthorityAuthorizationManager("ADMIN"))); - mappings.add(new RequestMatcherEntry<>(new MvcRequestMatcher(HttpMethod.GET, "/search"), new PermitAllAuthorizationManager())); - mappings.add(new RequestMatcherEntry<>(new MvcRequestMatcher(HttpMethod.POST, "/private"), new DenyAllAuthorizationManager())); - mappings.add(new RequestMatcherEntry<>(new AnyRequestMatcher(), new PermitAllAuthorizationManager())); - return new RequestMatcherDelegatingAuthorizationManager(mappings); + return RequestMatcherAuthorizationManagerBuilder.withRoleHierarchy(roleHierarchy()) + .authenticated(new MvcRequestMatcher(HttpMethod.GET, "/members/me")) + .permitAll(new MvcRequestMatcher(HttpMethod.GET, "/search")) + .hasAuthority("ADMIN", new MvcRequestMatcher(HttpMethod.GET, "/members")) + .hasAuthority("USER", new MvcRequestMatcher(HttpMethod.POST, "/hierarchy")) + .denyAll(new MvcRequestMatcher(HttpMethod.POST, "/private")) + .permitAll(new AnyRequestMatcher()) + .build(); } @Bean
Java
๊ณ ๋ฏผ ๋์— ๋นŒ๋” ํด๋ž˜์Šค๋ฅผ ์ถ”์ถœํ•˜์—ฌ ๊ฐœ์„ ํ•ด๋ณด์•˜์Šต๋‹ˆ๋‹ค! [72fe548](https://github.com/next-step/spring-security-authorization/pull/23/commits/72fe5487d07f732b75950f6ce55af19c9dabd72b) ํ•ด๋‹น ์ปค๋ฐ‹์— ๋ฐ˜์˜ํ•˜์˜€์Šต๋‹ˆ๋‹ค.
@@ -2,33 +2,43 @@ import jakarta.servlet.FilterChain; import jakarta.servlet.ServletException; +import jakarta.servlet.ServletRequest; +import jakarta.servlet.ServletResponse; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; import nextstep.security.authentication.Authentication; import nextstep.security.context.SecurityContextHolder; -import org.springframework.web.filter.OncePerRequestFilter; +import org.springframework.web.filter.GenericFilterBean; import java.io.IOException; -public class CheckAuthenticationFilter extends OncePerRequestFilter { +public class CheckAuthenticationFilter extends GenericFilterBean { - private final RequestMatcherDelegatingAuthorizationManager requestMatcherDelegatingAuthorizationManager; + private final AuthorizationManager<HttpServletRequest> authorizationManager; + private final AuthorizationDeniedHandler authorizationDeniedHandler; - public CheckAuthenticationFilter(RequestMatcherDelegatingAuthorizationManager requestMatcherDelegatingAuthorizationManager) { - this.requestMatcherDelegatingAuthorizationManager = requestMatcherDelegatingAuthorizationManager; + public CheckAuthenticationFilter(AuthorizationManager<HttpServletRequest> authorizationManager) { + this(authorizationManager, response -> response.setStatus(HttpServletResponse.SC_FORBIDDEN)); + } + + public CheckAuthenticationFilter(AuthorizationManager<HttpServletRequest> authorizationManager + , AuthorizationDeniedHandler authorizationDeniedHandler + ) { + this.authorizationManager = authorizationManager; + this.authorizationDeniedHandler = authorizationDeniedHandler; } @Override - protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException { + public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); - AuthorizationDecision authorizationDecision = requestMatcherDelegatingAuthorizationManager.check(authentication, request); + AuthorizationDecision authorizationDecision = authorizationManager.check(authentication, (HttpServletRequest) request); if (authorizationDecision.isDeny()) { - response.setStatus(HttpServletResponse.SC_FORBIDDEN); + authorizationDeniedHandler.handle((HttpServletResponse) response); return; } - filterChain.doFilter(request, response); + chain.doFilter(request, response); } }
Java
์•—.. ๊ทธ๋Ÿด์ˆ˜๋„ ์žˆ๊ฒ ๋„ค์š”! ์ธ๊ฐ€์‹คํŒจ์ธ ๊ฒฝ์šฐ ์œ ๋™์ ์œผ๋กœ ์ฒ˜๋ฆฌํ•  ์ˆ˜ ์žˆ๋„๋ก ์ธ๊ฐ€ ์‹คํŒจ ํ•ธ๋“ค๋Ÿฌ ์ธํ„ฐํŽ˜์ด์Šค๋ฅผ ์ •์˜ํ•˜์—ฌ ์ฒ˜๋ฆฌํ•ด๋ณด์•˜์Šต๋‹ˆ๋‹ค! [fc99a7a](https://github.com/next-step/spring-security-authorization/pull/23/commits/fc99a7a726f73bf39d3a30e7f02f4d2ecab0ec4e) ํ•ด๋‹น ์ปค๋ฐ‹์— ๋ฐ˜์˜ํ•ด๋‘์—ˆ์Šต๋‹ˆ๋‹ค
@@ -1,24 +0,0 @@ -package nextstep.security.authorization; - -import nextstep.security.authentication.Authentication; - -public class HasAuthorityAuthorizationManager implements AuthorizationManager { - private final String allowRole; - - public HasAuthorityAuthorizationManager(String allowRole) { - this.allowRole = allowRole; - } - - @Override - public AuthorizationDecision check(Authentication authentication, Object object) { - if (authentication == null || !authentication.isAuthenticated()) { - return AuthorizationDecision.deny(); - } - - if (authentication.getAuthorities().contains(allowRole)) { - return AuthorizationDecision.granted(); - } - - return AuthorizationDecision.deny(); - } -}
Java
์ฝ”๋“œ ๊ตฌ์กฐ๋ฅผ ๋ถ„์„ํ•ด๋ณด๋‹ˆ AuthoritiesAuthorizationManager๋Š” ์—ฌ๋Ÿฌ๊ฑด์˜ ์ธ๊ฐ€๋ฅผ ์ฒดํฌํ•  ์ˆ˜ ์žˆ๋Š” ์—ญํ• , AuthorityAuthorizationManager ๋Š” ์ธ๊ฐ€์ •๋ณด๋ฅผ ์„ค์ •ํ•˜๋Š” ์—ญํ• ๋กœ ๋ถ„๋ฆฌํ•œ๊ฒƒ ๊ฐ™์•„์š”. ํ•ด๋‹น ๋ถ€๋ถ„์„ ๊ด€์ ์œผ๋กœ ๋ฆฌํŒฉํ† ๋ง ํ•ด๋ณด์•˜์Šต๋‹ˆ๋‹ค [8ab4798](https://github.com/next-step/spring-security-authorization/pull/23/commits/8ab47981b3de163a355d9c4c50ef54f1cacf497c)ํ•ด๋‹น ์ปค๋ฐ‹์— ๋ฐ˜์˜ํ•ด๋ณด์•˜์Šต๋‹ˆ๋‹ค
@@ -13,15 +13,13 @@ import nextstep.security.context.SecurityContextHolderFilter; import nextstep.security.matcher.AnyRequestMatcher; import nextstep.security.matcher.MvcRequestMatcher; -import nextstep.security.matcher.RequestMatcherEntry; import nextstep.security.userdetails.UserDetails; import nextstep.security.userdetails.UserDetailsService; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.EnableAspectJAutoProxy; import org.springframework.http.HttpMethod; -import java.util.ArrayList; import java.util.List; import java.util.Set; @@ -50,20 +48,31 @@ public SecuredMethodInterceptor securedMethodInterceptor() { return new SecuredMethodInterceptor(); } +// @Bean +// public SecuredAspect securedAspect() { +// return new SecuredAspect(); +// } + + @Bean - public SecuredAspect securedAspect() { - return new SecuredAspect(); + public RoleHierarchy roleHierarchy() { + return RoleHierarchyImpl.with() + .role("ADMIN") + .implies("USER","GUEST") + .build(); } + @Bean public RequestMatcherDelegatingAuthorizationManager requestAuthorizationManager() { - List<RequestMatcherEntry<AuthorizationManager>> mappings = new ArrayList<>(); - mappings.add(new RequestMatcherEntry<>(new MvcRequestMatcher(HttpMethod.GET, "/members/me"), new AuthenticatedAuthorizationManager())); - mappings.add(new RequestMatcherEntry<>(new MvcRequestMatcher(HttpMethod.GET, "/members"), new HasAuthorityAuthorizationManager("ADMIN"))); - mappings.add(new RequestMatcherEntry<>(new MvcRequestMatcher(HttpMethod.GET, "/search"), new PermitAllAuthorizationManager())); - mappings.add(new RequestMatcherEntry<>(new MvcRequestMatcher(HttpMethod.POST, "/private"), new DenyAllAuthorizationManager())); - mappings.add(new RequestMatcherEntry<>(new AnyRequestMatcher(), new PermitAllAuthorizationManager())); - return new RequestMatcherDelegatingAuthorizationManager(mappings); + return RequestMatcherAuthorizationManagerBuilder.withRoleHierarchy(roleHierarchy()) + .authenticated(new MvcRequestMatcher(HttpMethod.GET, "/members/me")) + .permitAll(new MvcRequestMatcher(HttpMethod.GET, "/search")) + .hasAuthority("ADMIN", new MvcRequestMatcher(HttpMethod.GET, "/members")) + .hasAuthority("USER", new MvcRequestMatcher(HttpMethod.POST, "/hierarchy")) + .denyAll(new MvcRequestMatcher(HttpMethod.POST, "/private")) + .permitAll(new AnyRequestMatcher()) + .build(); } @Bean
Java
๋นŒ๋” ํŒจํ„ด์„ ์ ์šฉํ•˜์…จ๊ตฐ์š”! ์žฌ๋ฏธ์žˆ๋Š” ์‹œ๋„์ž…๋‹ˆ๋‹ค ๐Ÿ‘
@@ -0,0 +1,44 @@ +package nextstep.security.authorization; + +import nextstep.security.authentication.Authentication; +import org.springframework.util.CollectionUtils; + +import java.util.Collection; +import java.util.Set; + +public class AuthoritiesAuthorizationManager implements AuthorizationManager<Collection<String>> { + private final RoleHierarchy roleHierarchy; + + public AuthoritiesAuthorizationManager(RoleHierarchy roleHierarchy) { + this.roleHierarchy = roleHierarchy; + } + + @Override + public AuthorizationDecision check(Authentication authentication, Collection<String> authorities) { + if (authentication == null || !authentication.isAuthenticated()) { + return AuthorizationDecision.deny(); + } + + if (isHasAccess(authentication, authorities)) { + return AuthorizationDecision.granted(); + } + + return AuthorizationDecision.deny(); + } + + private boolean isHasAccess(Authentication authentication, Collection<String> authorities) { + Set<String> authenticationAuthorities = authentication.getAuthorities(); + + if (isMatchAuthority(authorities, authenticationAuthorities)) { + return true; + } + + Collection<String> reachableGrantedAuthorities = roleHierarchy.getReachableGrantedAuthorities(authentication.getAuthorities()); + + return isMatchAuthority(reachableGrantedAuthorities, authenticationAuthorities); + } + + private static boolean isMatchAuthority(Collection<String> authorities, Set<String> authenticationAuthorities) { + return CollectionUtils.containsAny(authorities, authenticationAuthorities); + } +}
Java
AuthoritiesAuthorizationManager ๋ถ„๋ฆฌ๋ฅผ ํ†ตํ•œ ์ฑ…์ž„๊ณผ ์—ญํ•  ๋ถ„๋ฆฌ ๐Ÿ‘
@@ -2,33 +2,43 @@ import jakarta.servlet.FilterChain; import jakarta.servlet.ServletException; +import jakarta.servlet.ServletRequest; +import jakarta.servlet.ServletResponse; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; import nextstep.security.authentication.Authentication; import nextstep.security.context.SecurityContextHolder; -import org.springframework.web.filter.OncePerRequestFilter; +import org.springframework.web.filter.GenericFilterBean; import java.io.IOException; -public class CheckAuthenticationFilter extends OncePerRequestFilter { +public class CheckAuthenticationFilter extends GenericFilterBean { - private final RequestMatcherDelegatingAuthorizationManager requestMatcherDelegatingAuthorizationManager; + private final AuthorizationManager<HttpServletRequest> authorizationManager; + private final AuthorizationDeniedHandler authorizationDeniedHandler; - public CheckAuthenticationFilter(RequestMatcherDelegatingAuthorizationManager requestMatcherDelegatingAuthorizationManager) { - this.requestMatcherDelegatingAuthorizationManager = requestMatcherDelegatingAuthorizationManager; + public CheckAuthenticationFilter(AuthorizationManager<HttpServletRequest> authorizationManager) { + this(authorizationManager, response -> response.setStatus(HttpServletResponse.SC_FORBIDDEN)); + } + + public CheckAuthenticationFilter(AuthorizationManager<HttpServletRequest> authorizationManager + , AuthorizationDeniedHandler authorizationDeniedHandler + ) { + this.authorizationManager = authorizationManager; + this.authorizationDeniedHandler = authorizationDeniedHandler; } @Override - protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException { + public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); - AuthorizationDecision authorizationDecision = requestMatcherDelegatingAuthorizationManager.check(authentication, request); + AuthorizationDecision authorizationDecision = authorizationManager.check(authentication, (HttpServletRequest) request); if (authorizationDecision.isDeny()) { - response.setStatus(HttpServletResponse.SC_FORBIDDEN); + authorizationDeniedHandler.handle((HttpServletResponse) response); return; } - filterChain.doFilter(request, response); + chain.doFilter(request, response); } }
Java
๊ตฌํ˜„ํ•ด์ฃผ์‹  ์ฝ”๋“œ๋ฅผ ๋ณด๋‹ˆ ExceptionTranslationFilter์—์„œ ์ฒ˜๋ฆฌํ•˜๋Š” ๊ฒƒ ์ฒ˜๋Ÿผ AuthorizationDeniedHandler๋ฅผ ํ†ตํ•ด ์—๋Ÿฌ๋ฅผ ์ฒ˜๋ฆฌํ•˜๋„๋ก ์ž‘์—…ํ•ด์ฃผ์…จ๊ตฐ์š” ๐Ÿ‘ ์‚ฌ์‹ค ์ฝ”๋ฉ˜ํŠธ ๋“œ๋ฆฌ๋ ค ํ–ˆ๋˜ ๋ถ€๋ถ„์€ 401์ด ๋ฐœ์ƒํ•  ์ˆ˜๋„ ์žˆ์–ด์„œ 403 ์™ธ ๋‹ค๋ฅธ ์‘๋‹ต ์ฝ”๋“œ๊ฐ€ ์‘๋‹ต๋  ์ˆ˜ ์žˆ๋„๋ก ์ฒ˜๋ฆฌํ•ด๋ณด๋Š” ๊ฒƒ์„ ์ƒ๊ฐํ•ด๋ณด์‹œ๊ธธ ์˜๋ฏธํ•˜๋Š” ์ฝ”๋ฉ˜ํŠธ์—ฟ์Šต๋‹ˆ๋‹ค :) ์ด๋ ‡๊ฒŒ ํ•  ๊ฒฝ์šฐ AuthorizationDeniedHandler ์™ธ ๋‹ค๋ฅธ handler๊ฐ€ ํ•„์š”ํ•  ์ˆ˜ ์žˆ๊ณ , ํŠนํžˆ Authentication ๊ด€๋ จ ์˜ˆ์™ธ๋ฅผ ์ฒ˜๋ฆฌํ•˜๋Š” handler๋Š” ๋‹ค๋ฅธ ์ธ์ฆ ํ•„ํ„ฐ์—์„œ๋„ ์‚ฌ์šฉ๋  ์ˆ˜ ์žˆ๊ฒ ๋„ค์š”! ์š”๊ตฌ์‚ฌํ•ญ์—๋Š” ์—†๋˜ ๋‚ด์šฉ์ด์ง€๋งŒ ์ฐธ๊ณ ํ•ด๋ณด์‹œ๊ธธ ๋ฐ”๋ผ๋Š” ๋งˆ์Œ์—์„œ ๋‚จ๊ธด ์ฝ”๋ฉ˜ํŠธ์˜€์–ด์š” :)
@@ -0,0 +1,104 @@ +import React from "react"; +import { useState } from "react"; + +const dummies = [ + { reviewId: 1, isAwarded: true, applicationYear: 2023, semester: "1ํ•™๊ธฐ", content: "์žฅํ•™๊ธˆ ์‹ ์ฒญ ๊ณผ์ •์ด ๊ฐ„๋‹จํ–ˆ์–ด์š”!" }, + { reviewId: 2, isAwarded: false, applicationYear: 2024, semester: "2ํ•™๊ธฐ", content: "์„ ๋ฐœ ๊ธฐ์ค€์ด ๋ช…ํ™•ํ•˜์ง€ ์•Š์•„์„œ ์•„์‰ฌ์› ์–ด์š”." }, + { reviewId: 3, isAwarded: true, applicationYear: 2022, semester: "1ํ•™๊ธฐ", content: "๋ฐ›์•„์„œ ํ•™๋น„ ๋ถ€๋‹ด์ด ์ค„์—ˆ์–ด์š”!" }, + { reviewId: 4, isAwarded: false, applicationYear: 2021, semester: "2ํ•™๊ธฐ", content: "์ง€์›ํ–ˆ์ง€๋งŒ ํƒˆ๋ฝํ•ด์„œ ์•„์‰ฌ์› ์–ด์š”." }, + { reviewId: 5, isAwarded: true, applicationYear: 2020, semester: "1ํ•™๊ธฐ", content: "๊ธˆ์•ก์ด ์ƒ๊ฐ๋ณด๋‹ค ๋งŽ์•„์„œ ๋งŒ์กฑํ–ˆ์–ด์š”!" }, + { reviewId: 6, isAwarded: true, applicationYear: 2022, semester: "1ํ•™๊ธฐ", content: "์„ฑ์ ์ด ์กฐ๊ธˆ ๋ถ€์กฑํ•œ๊ฐ€ ์‹ถ์—ˆ๋Š”๋ฐ ๊ดœ์ฐฎ์•˜์–ด์š”." }, + { reviewId: 7, isAwarded: false, applicationYear: 2024, semester: "1ํ•™๊ธฐ", content: "๋‹ค์Œ์— ๋‹ค์‹œ ์‹ ์ฒญํ•˜๋ ค๊ณ ์š”.." }, + { reviewId: 8, isAwarded: true, applicationYear: 2020, semester: "2ํ•™๊ธฐ", content: "ํ•™์ ๋ณด๋‹จ ๋ฉด์ ‘์ด ๋” ์ค‘์š”ํ•œ ๊ฒƒ ๊ฐ™์•„์š”!" }, + { reviewId: 9, isAwarded: false, applicationYear: 2021, semester: "1ํ•™๊ธฐ", content: "์™œ ๋–จ์–ด์กŒ๋Š”์ง€ ์ž˜ ๋ชจ๋ฅด๊ฒ ์–ด์š”ใ… ใ… " }, + { reviewId: 10, isAwarded: true, applicationYear: 2018, semester: "2ํ•™๊ธฐ", content: "์ง€์› ๋‹น์‹œ ํ•™์ ์€ X.XX์˜€์–ด์š”." }, +]; + +function ReviewList() { + + const reviewsInOnePage = 5; + const [currentPage, setCurrentPage] = useState(1); + + const [filterIsAwarded, setFilterIsAwarded] = useState(""); + const [filterApplicationYear, setFilterApplicationYear] = useState(""); + const [filterSemester, setFilterSemester] = useState(""); + + const filteredReviews = dummies.filter((review) => { + const findIsAwarded = filterIsAwarded === "" || (filterIsAwarded === "์ˆ˜ํ˜œํ•จ" && review.isAwarded) || (filterIsAwarded === "์ˆ˜ํ˜œ ์•ˆํ•จ" && !review.isAwarded); + const findApplicationYear = filterApplicationYear === "" || review.applicationYear.toString() === filterApplicationYear; + const findSemester = filterSemester === "" || `${review.applicationYear}-${review.semester}` === filterSemester; + + return findIsAwarded && findApplicationYear && findSemester; + }); + + const indexOfLastReview = currentPage * reviewsInOnePage; + const indexOfFirstReview = indexOfLastReview - reviewsInOnePage; + const currentReviews = filteredReviews.slice(indexOfFirstReview, indexOfLastReview); + + function previousPage() { + if (currentPage > 1) { + setCurrentPage(currentPage - 1); + } + } + + function nextPage() { + if (indexOfLastReview < filteredReviews.length) { + setCurrentPage(currentPage + 1); + } + } + + return ( + <div> + <h2>ํ•™์ƒ๋“ค์˜ ๋ฆฌ๋ทฐ</h2> + + <div> + <label> + ์ˆ˜ํ˜œ ์—ฌ๋ถ€ + <select value={filterIsAwarded} onChange={(e) => setFilterIsAwarded(e.target.value)}> + <option value="">์ „์ฒด</option> + <option value="์ˆ˜ํ˜œํ•จ">์ˆ˜ํ˜œํ•จ</option> + <option value="์ˆ˜ํ˜œ ์•ˆํ•จ">์ˆ˜ํ˜œ ์•ˆํ•จ</option> + </select> + </label> + + <label> + ์‹ ์ฒญ ์—ฐ๋„ + <input + type="number" + placeholder="์‹ ์ฒญ ์—ฐ๋„๋ฅผ ์ž…๋ ฅํ•˜์„ธ์š”" + value={filterApplicationYear} + onChange={(e) => setFilterApplicationYear(e.target.value)} + /> + </label> + + <label> + ํ•™๊ธฐ + <select value={filterSemester} onChange={(e) => setFilterSemester(e.target.value)}> + <option value="">์ „์ฒด</option> + <option value="1ํ•™๊ธฐ">1ํ•™๊ธฐ</option> + <option value="2ํ•™๊ธฐ">2ํ•™๊ธฐ</option> + </select> + </label> + </div> + + <div> + {currentReviews.length > 0 && currentReviews.map((review) => ( + <div key={review.reviewId}> + <p><strong>์ต๋ช…</strong></p> + <p>{review.isAwarded ? "์ˆ˜ํ˜œํ•จ" : "์ˆ˜ํ˜œ ์•ˆํ•จ"}</p> + <p>{review.applicationYear}-{review.semester}</p> + <p>{review.content}</p> + </div> + ))} + </div> + + <div> + <button onClick={previousPage} disabled={currentPage === 1}>์ด์ „</button> + <span> {currentPage} </span> + <button onClick={nextPage} disabled={indexOfLastReview >= filteredReviews.length}>๋‹ค์Œ</button> + </div> + </div> + ); +} + +export default ReviewList; \ No newline at end of file
Unknown
์‚ฌ์šฉํ•˜์ง€ ์•Š๋Š” ๋ถˆํ•„์š”ํ•œ import React๋Š” ์ œ๊ฑฐํ•ด์ฃผ์„ธ์š”~
@@ -0,0 +1,104 @@ +import React from "react"; +import { useState } from "react"; + +const dummies = [ + { reviewId: 1, isAwarded: true, applicationYear: 2023, semester: "1ํ•™๊ธฐ", content: "์žฅํ•™๊ธˆ ์‹ ์ฒญ ๊ณผ์ •์ด ๊ฐ„๋‹จํ–ˆ์–ด์š”!" }, + { reviewId: 2, isAwarded: false, applicationYear: 2024, semester: "2ํ•™๊ธฐ", content: "์„ ๋ฐœ ๊ธฐ์ค€์ด ๋ช…ํ™•ํ•˜์ง€ ์•Š์•„์„œ ์•„์‰ฌ์› ์–ด์š”." }, + { reviewId: 3, isAwarded: true, applicationYear: 2022, semester: "1ํ•™๊ธฐ", content: "๋ฐ›์•„์„œ ํ•™๋น„ ๋ถ€๋‹ด์ด ์ค„์—ˆ์–ด์š”!" }, + { reviewId: 4, isAwarded: false, applicationYear: 2021, semester: "2ํ•™๊ธฐ", content: "์ง€์›ํ–ˆ์ง€๋งŒ ํƒˆ๋ฝํ•ด์„œ ์•„์‰ฌ์› ์–ด์š”." }, + { reviewId: 5, isAwarded: true, applicationYear: 2020, semester: "1ํ•™๊ธฐ", content: "๊ธˆ์•ก์ด ์ƒ๊ฐ๋ณด๋‹ค ๋งŽ์•„์„œ ๋งŒ์กฑํ–ˆ์–ด์š”!" }, + { reviewId: 6, isAwarded: true, applicationYear: 2022, semester: "1ํ•™๊ธฐ", content: "์„ฑ์ ์ด ์กฐ๊ธˆ ๋ถ€์กฑํ•œ๊ฐ€ ์‹ถ์—ˆ๋Š”๋ฐ ๊ดœ์ฐฎ์•˜์–ด์š”." }, + { reviewId: 7, isAwarded: false, applicationYear: 2024, semester: "1ํ•™๊ธฐ", content: "๋‹ค์Œ์— ๋‹ค์‹œ ์‹ ์ฒญํ•˜๋ ค๊ณ ์š”.." }, + { reviewId: 8, isAwarded: true, applicationYear: 2020, semester: "2ํ•™๊ธฐ", content: "ํ•™์ ๋ณด๋‹จ ๋ฉด์ ‘์ด ๋” ์ค‘์š”ํ•œ ๊ฒƒ ๊ฐ™์•„์š”!" }, + { reviewId: 9, isAwarded: false, applicationYear: 2021, semester: "1ํ•™๊ธฐ", content: "์™œ ๋–จ์–ด์กŒ๋Š”์ง€ ์ž˜ ๋ชจ๋ฅด๊ฒ ์–ด์š”ใ… ใ… " }, + { reviewId: 10, isAwarded: true, applicationYear: 2018, semester: "2ํ•™๊ธฐ", content: "์ง€์› ๋‹น์‹œ ํ•™์ ์€ X.XX์˜€์–ด์š”." }, +]; + +function ReviewList() { + + const reviewsInOnePage = 5; + const [currentPage, setCurrentPage] = useState(1); + + const [filterIsAwarded, setFilterIsAwarded] = useState(""); + const [filterApplicationYear, setFilterApplicationYear] = useState(""); + const [filterSemester, setFilterSemester] = useState(""); + + const filteredReviews = dummies.filter((review) => { + const findIsAwarded = filterIsAwarded === "" || (filterIsAwarded === "์ˆ˜ํ˜œํ•จ" && review.isAwarded) || (filterIsAwarded === "์ˆ˜ํ˜œ ์•ˆํ•จ" && !review.isAwarded); + const findApplicationYear = filterApplicationYear === "" || review.applicationYear.toString() === filterApplicationYear; + const findSemester = filterSemester === "" || `${review.applicationYear}-${review.semester}` === filterSemester; + + return findIsAwarded && findApplicationYear && findSemester; + }); + + const indexOfLastReview = currentPage * reviewsInOnePage; + const indexOfFirstReview = indexOfLastReview - reviewsInOnePage; + const currentReviews = filteredReviews.slice(indexOfFirstReview, indexOfLastReview); + + function previousPage() { + if (currentPage > 1) { + setCurrentPage(currentPage - 1); + } + } + + function nextPage() { + if (indexOfLastReview < filteredReviews.length) { + setCurrentPage(currentPage + 1); + } + } + + return ( + <div> + <h2>ํ•™์ƒ๋“ค์˜ ๋ฆฌ๋ทฐ</h2> + + <div> + <label> + ์ˆ˜ํ˜œ ์—ฌ๋ถ€ + <select value={filterIsAwarded} onChange={(e) => setFilterIsAwarded(e.target.value)}> + <option value="">์ „์ฒด</option> + <option value="์ˆ˜ํ˜œํ•จ">์ˆ˜ํ˜œํ•จ</option> + <option value="์ˆ˜ํ˜œ ์•ˆํ•จ">์ˆ˜ํ˜œ ์•ˆํ•จ</option> + </select> + </label> + + <label> + ์‹ ์ฒญ ์—ฐ๋„ + <input + type="number" + placeholder="์‹ ์ฒญ ์—ฐ๋„๋ฅผ ์ž…๋ ฅํ•˜์„ธ์š”" + value={filterApplicationYear} + onChange={(e) => setFilterApplicationYear(e.target.value)} + /> + </label> + + <label> + ํ•™๊ธฐ + <select value={filterSemester} onChange={(e) => setFilterSemester(e.target.value)}> + <option value="">์ „์ฒด</option> + <option value="1ํ•™๊ธฐ">1ํ•™๊ธฐ</option> + <option value="2ํ•™๊ธฐ">2ํ•™๊ธฐ</option> + </select> + </label> + </div> + + <div> + {currentReviews.length > 0 && currentReviews.map((review) => ( + <div key={review.reviewId}> + <p><strong>์ต๋ช…</strong></p> + <p>{review.isAwarded ? "์ˆ˜ํ˜œํ•จ" : "์ˆ˜ํ˜œ ์•ˆํ•จ"}</p> + <p>{review.applicationYear}-{review.semester}</p> + <p>{review.content}</p> + </div> + ))} + </div> + + <div> + <button onClick={previousPage} disabled={currentPage === 1}>์ด์ „</button> + <span> {currentPage} </span> + <button onClick={nextPage} disabled={indexOfLastReview >= filteredReviews.length}>๋‹ค์Œ</button> + </div> + </div> + ); +} + +export default ReviewList; \ No newline at end of file
Unknown
์˜คํ˜ธ~ dummies๋กœ ๋งŒ๋“ค์–ด ์ž„์‹œ ๊ตฌํ˜„ ๊ตฟ๐Ÿ‘๐Ÿ‘๐Ÿ‘
@@ -0,0 +1,104 @@ +import React from "react"; +import { useState } from "react"; + +const dummies = [ + { reviewId: 1, isAwarded: true, applicationYear: 2023, semester: "1ํ•™๊ธฐ", content: "์žฅํ•™๊ธˆ ์‹ ์ฒญ ๊ณผ์ •์ด ๊ฐ„๋‹จํ–ˆ์–ด์š”!" }, + { reviewId: 2, isAwarded: false, applicationYear: 2024, semester: "2ํ•™๊ธฐ", content: "์„ ๋ฐœ ๊ธฐ์ค€์ด ๋ช…ํ™•ํ•˜์ง€ ์•Š์•„์„œ ์•„์‰ฌ์› ์–ด์š”." }, + { reviewId: 3, isAwarded: true, applicationYear: 2022, semester: "1ํ•™๊ธฐ", content: "๋ฐ›์•„์„œ ํ•™๋น„ ๋ถ€๋‹ด์ด ์ค„์—ˆ์–ด์š”!" }, + { reviewId: 4, isAwarded: false, applicationYear: 2021, semester: "2ํ•™๊ธฐ", content: "์ง€์›ํ–ˆ์ง€๋งŒ ํƒˆ๋ฝํ•ด์„œ ์•„์‰ฌ์› ์–ด์š”." }, + { reviewId: 5, isAwarded: true, applicationYear: 2020, semester: "1ํ•™๊ธฐ", content: "๊ธˆ์•ก์ด ์ƒ๊ฐ๋ณด๋‹ค ๋งŽ์•„์„œ ๋งŒ์กฑํ–ˆ์–ด์š”!" }, + { reviewId: 6, isAwarded: true, applicationYear: 2022, semester: "1ํ•™๊ธฐ", content: "์„ฑ์ ์ด ์กฐ๊ธˆ ๋ถ€์กฑํ•œ๊ฐ€ ์‹ถ์—ˆ๋Š”๋ฐ ๊ดœ์ฐฎ์•˜์–ด์š”." }, + { reviewId: 7, isAwarded: false, applicationYear: 2024, semester: "1ํ•™๊ธฐ", content: "๋‹ค์Œ์— ๋‹ค์‹œ ์‹ ์ฒญํ•˜๋ ค๊ณ ์š”.." }, + { reviewId: 8, isAwarded: true, applicationYear: 2020, semester: "2ํ•™๊ธฐ", content: "ํ•™์ ๋ณด๋‹จ ๋ฉด์ ‘์ด ๋” ์ค‘์š”ํ•œ ๊ฒƒ ๊ฐ™์•„์š”!" }, + { reviewId: 9, isAwarded: false, applicationYear: 2021, semester: "1ํ•™๊ธฐ", content: "์™œ ๋–จ์–ด์กŒ๋Š”์ง€ ์ž˜ ๋ชจ๋ฅด๊ฒ ์–ด์š”ใ… ใ… " }, + { reviewId: 10, isAwarded: true, applicationYear: 2018, semester: "2ํ•™๊ธฐ", content: "์ง€์› ๋‹น์‹œ ํ•™์ ์€ X.XX์˜€์–ด์š”." }, +]; + +function ReviewList() { + + const reviewsInOnePage = 5; + const [currentPage, setCurrentPage] = useState(1); + + const [filterIsAwarded, setFilterIsAwarded] = useState(""); + const [filterApplicationYear, setFilterApplicationYear] = useState(""); + const [filterSemester, setFilterSemester] = useState(""); + + const filteredReviews = dummies.filter((review) => { + const findIsAwarded = filterIsAwarded === "" || (filterIsAwarded === "์ˆ˜ํ˜œํ•จ" && review.isAwarded) || (filterIsAwarded === "์ˆ˜ํ˜œ ์•ˆํ•จ" && !review.isAwarded); + const findApplicationYear = filterApplicationYear === "" || review.applicationYear.toString() === filterApplicationYear; + const findSemester = filterSemester === "" || `${review.applicationYear}-${review.semester}` === filterSemester; + + return findIsAwarded && findApplicationYear && findSemester; + }); + + const indexOfLastReview = currentPage * reviewsInOnePage; + const indexOfFirstReview = indexOfLastReview - reviewsInOnePage; + const currentReviews = filteredReviews.slice(indexOfFirstReview, indexOfLastReview); + + function previousPage() { + if (currentPage > 1) { + setCurrentPage(currentPage - 1); + } + } + + function nextPage() { + if (indexOfLastReview < filteredReviews.length) { + setCurrentPage(currentPage + 1); + } + } + + return ( + <div> + <h2>ํ•™์ƒ๋“ค์˜ ๋ฆฌ๋ทฐ</h2> + + <div> + <label> + ์ˆ˜ํ˜œ ์—ฌ๋ถ€ + <select value={filterIsAwarded} onChange={(e) => setFilterIsAwarded(e.target.value)}> + <option value="">์ „์ฒด</option> + <option value="์ˆ˜ํ˜œํ•จ">์ˆ˜ํ˜œํ•จ</option> + <option value="์ˆ˜ํ˜œ ์•ˆํ•จ">์ˆ˜ํ˜œ ์•ˆํ•จ</option> + </select> + </label> + + <label> + ์‹ ์ฒญ ์—ฐ๋„ + <input + type="number" + placeholder="์‹ ์ฒญ ์—ฐ๋„๋ฅผ ์ž…๋ ฅํ•˜์„ธ์š”" + value={filterApplicationYear} + onChange={(e) => setFilterApplicationYear(e.target.value)} + /> + </label> + + <label> + ํ•™๊ธฐ + <select value={filterSemester} onChange={(e) => setFilterSemester(e.target.value)}> + <option value="">์ „์ฒด</option> + <option value="1ํ•™๊ธฐ">1ํ•™๊ธฐ</option> + <option value="2ํ•™๊ธฐ">2ํ•™๊ธฐ</option> + </select> + </label> + </div> + + <div> + {currentReviews.length > 0 && currentReviews.map((review) => ( + <div key={review.reviewId}> + <p><strong>์ต๋ช…</strong></p> + <p>{review.isAwarded ? "์ˆ˜ํ˜œํ•จ" : "์ˆ˜ํ˜œ ์•ˆํ•จ"}</p> + <p>{review.applicationYear}-{review.semester}</p> + <p>{review.content}</p> + </div> + ))} + </div> + + <div> + <button onClick={previousPage} disabled={currentPage === 1}>์ด์ „</button> + <span> {currentPage} </span> + <button onClick={nextPage} disabled={indexOfLastReview >= filteredReviews.length}>๋‹ค์Œ</button> + </div> + </div> + ); +} + +export default ReviewList; \ No newline at end of file
Unknown
๋ณดํ†ต ๋ณ€ํ•˜์ง€ ์•Š๋Š” ์ƒ์ˆ˜๋Š” `REVIEWS_IN_ONE_PAGE`์™€ ๊ฐ™์ด ๋Œ€๋ฌธ์ž๋กœ ๋„ค์ด๋ฐํ•˜๋Š” ๊ฒƒ์ด ๋ณดํŽธ์ ์ž…๋‹ˆ๋‹ค~ ์ฐธ๊ณ ํ•ด์„œ ์ ์šฉํ•ด๋ณผ๊นŒ์š”~? - cf. https://ko.javascript.info/variables#ref-337 <img width="777" alt="image" src="https://github.com/user-attachments/assets/038d8339-e35a-4608-a4a3-5e847fe7ad1e" />
@@ -0,0 +1,104 @@ +import React from "react"; +import { useState } from "react"; + +const dummies = [ + { reviewId: 1, isAwarded: true, applicationYear: 2023, semester: "1ํ•™๊ธฐ", content: "์žฅํ•™๊ธˆ ์‹ ์ฒญ ๊ณผ์ •์ด ๊ฐ„๋‹จํ–ˆ์–ด์š”!" }, + { reviewId: 2, isAwarded: false, applicationYear: 2024, semester: "2ํ•™๊ธฐ", content: "์„ ๋ฐœ ๊ธฐ์ค€์ด ๋ช…ํ™•ํ•˜์ง€ ์•Š์•„์„œ ์•„์‰ฌ์› ์–ด์š”." }, + { reviewId: 3, isAwarded: true, applicationYear: 2022, semester: "1ํ•™๊ธฐ", content: "๋ฐ›์•„์„œ ํ•™๋น„ ๋ถ€๋‹ด์ด ์ค„์—ˆ์–ด์š”!" }, + { reviewId: 4, isAwarded: false, applicationYear: 2021, semester: "2ํ•™๊ธฐ", content: "์ง€์›ํ–ˆ์ง€๋งŒ ํƒˆ๋ฝํ•ด์„œ ์•„์‰ฌ์› ์–ด์š”." }, + { reviewId: 5, isAwarded: true, applicationYear: 2020, semester: "1ํ•™๊ธฐ", content: "๊ธˆ์•ก์ด ์ƒ๊ฐ๋ณด๋‹ค ๋งŽ์•„์„œ ๋งŒ์กฑํ–ˆ์–ด์š”!" }, + { reviewId: 6, isAwarded: true, applicationYear: 2022, semester: "1ํ•™๊ธฐ", content: "์„ฑ์ ์ด ์กฐ๊ธˆ ๋ถ€์กฑํ•œ๊ฐ€ ์‹ถ์—ˆ๋Š”๋ฐ ๊ดœ์ฐฎ์•˜์–ด์š”." }, + { reviewId: 7, isAwarded: false, applicationYear: 2024, semester: "1ํ•™๊ธฐ", content: "๋‹ค์Œ์— ๋‹ค์‹œ ์‹ ์ฒญํ•˜๋ ค๊ณ ์š”.." }, + { reviewId: 8, isAwarded: true, applicationYear: 2020, semester: "2ํ•™๊ธฐ", content: "ํ•™์ ๋ณด๋‹จ ๋ฉด์ ‘์ด ๋” ์ค‘์š”ํ•œ ๊ฒƒ ๊ฐ™์•„์š”!" }, + { reviewId: 9, isAwarded: false, applicationYear: 2021, semester: "1ํ•™๊ธฐ", content: "์™œ ๋–จ์–ด์กŒ๋Š”์ง€ ์ž˜ ๋ชจ๋ฅด๊ฒ ์–ด์š”ใ… ใ… " }, + { reviewId: 10, isAwarded: true, applicationYear: 2018, semester: "2ํ•™๊ธฐ", content: "์ง€์› ๋‹น์‹œ ํ•™์ ์€ X.XX์˜€์–ด์š”." }, +]; + +function ReviewList() { + + const reviewsInOnePage = 5; + const [currentPage, setCurrentPage] = useState(1); + + const [filterIsAwarded, setFilterIsAwarded] = useState(""); + const [filterApplicationYear, setFilterApplicationYear] = useState(""); + const [filterSemester, setFilterSemester] = useState(""); + + const filteredReviews = dummies.filter((review) => { + const findIsAwarded = filterIsAwarded === "" || (filterIsAwarded === "์ˆ˜ํ˜œํ•จ" && review.isAwarded) || (filterIsAwarded === "์ˆ˜ํ˜œ ์•ˆํ•จ" && !review.isAwarded); + const findApplicationYear = filterApplicationYear === "" || review.applicationYear.toString() === filterApplicationYear; + const findSemester = filterSemester === "" || `${review.applicationYear}-${review.semester}` === filterSemester; + + return findIsAwarded && findApplicationYear && findSemester; + }); + + const indexOfLastReview = currentPage * reviewsInOnePage; + const indexOfFirstReview = indexOfLastReview - reviewsInOnePage; + const currentReviews = filteredReviews.slice(indexOfFirstReview, indexOfLastReview); + + function previousPage() { + if (currentPage > 1) { + setCurrentPage(currentPage - 1); + } + } + + function nextPage() { + if (indexOfLastReview < filteredReviews.length) { + setCurrentPage(currentPage + 1); + } + } + + return ( + <div> + <h2>ํ•™์ƒ๋“ค์˜ ๋ฆฌ๋ทฐ</h2> + + <div> + <label> + ์ˆ˜ํ˜œ ์—ฌ๋ถ€ + <select value={filterIsAwarded} onChange={(e) => setFilterIsAwarded(e.target.value)}> + <option value="">์ „์ฒด</option> + <option value="์ˆ˜ํ˜œํ•จ">์ˆ˜ํ˜œํ•จ</option> + <option value="์ˆ˜ํ˜œ ์•ˆํ•จ">์ˆ˜ํ˜œ ์•ˆํ•จ</option> + </select> + </label> + + <label> + ์‹ ์ฒญ ์—ฐ๋„ + <input + type="number" + placeholder="์‹ ์ฒญ ์—ฐ๋„๋ฅผ ์ž…๋ ฅํ•˜์„ธ์š”" + value={filterApplicationYear} + onChange={(e) => setFilterApplicationYear(e.target.value)} + /> + </label> + + <label> + ํ•™๊ธฐ + <select value={filterSemester} onChange={(e) => setFilterSemester(e.target.value)}> + <option value="">์ „์ฒด</option> + <option value="1ํ•™๊ธฐ">1ํ•™๊ธฐ</option> + <option value="2ํ•™๊ธฐ">2ํ•™๊ธฐ</option> + </select> + </label> + </div> + + <div> + {currentReviews.length > 0 && currentReviews.map((review) => ( + <div key={review.reviewId}> + <p><strong>์ต๋ช…</strong></p> + <p>{review.isAwarded ? "์ˆ˜ํ˜œํ•จ" : "์ˆ˜ํ˜œ ์•ˆํ•จ"}</p> + <p>{review.applicationYear}-{review.semester}</p> + <p>{review.content}</p> + </div> + ))} + </div> + + <div> + <button onClick={previousPage} disabled={currentPage === 1}>์ด์ „</button> + <span> {currentPage} </span> + <button onClick={nextPage} disabled={indexOfLastReview >= filteredReviews.length}>๋‹ค์Œ</button> + </div> + </div> + ); +} + +export default ReviewList; \ No newline at end of file
Unknown
๋ฐ˜๋ณต๋ฌธ์œผ๋กœ ์‚ฌ์šฉํ• ๋•Œ ๋””์ŠคํŠธ๋Ÿญ์ณ๋ง์„ ์‚ฌ์šฉํ•˜๋ฉด ๋” ๊น”๋”ํ•˜๊ฒŒ ํ‘œํ˜„์ด ๊ฐ€๋Šฅํ•ฉ๋‹ˆ๋‹ค~ ์ง€๊ธˆ๋„ map ๋‚ด๋ถ€์—์„œ `review.reviewId`, `reveiw.isAwarded` ์ฒ˜๋Ÿผ `review.`์ด ๊ณ„์† ์ค‘๋ณตํ•ด์„œ ์‚ฌ์šฉํ•˜๊ณ  ์žˆ์ฃ ~ ๋””์ŠคํŠธ๋Ÿญ์ณ๋ง์œผ๋กœ ์ข€ ๋” ๊น”๋”ํ•˜๊ฒŒ ํ‘œํ˜„ํ•ด ๋ณผ๊นŒ์š”~? - cf. https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment
@@ -0,0 +1,104 @@ +import React from "react"; +import { useState } from "react"; + +const dummies = [ + { reviewId: 1, isAwarded: true, applicationYear: 2023, semester: "1ํ•™๊ธฐ", content: "์žฅํ•™๊ธˆ ์‹ ์ฒญ ๊ณผ์ •์ด ๊ฐ„๋‹จํ–ˆ์–ด์š”!" }, + { reviewId: 2, isAwarded: false, applicationYear: 2024, semester: "2ํ•™๊ธฐ", content: "์„ ๋ฐœ ๊ธฐ์ค€์ด ๋ช…ํ™•ํ•˜์ง€ ์•Š์•„์„œ ์•„์‰ฌ์› ์–ด์š”." }, + { reviewId: 3, isAwarded: true, applicationYear: 2022, semester: "1ํ•™๊ธฐ", content: "๋ฐ›์•„์„œ ํ•™๋น„ ๋ถ€๋‹ด์ด ์ค„์—ˆ์–ด์š”!" }, + { reviewId: 4, isAwarded: false, applicationYear: 2021, semester: "2ํ•™๊ธฐ", content: "์ง€์›ํ–ˆ์ง€๋งŒ ํƒˆ๋ฝํ•ด์„œ ์•„์‰ฌ์› ์–ด์š”." }, + { reviewId: 5, isAwarded: true, applicationYear: 2020, semester: "1ํ•™๊ธฐ", content: "๊ธˆ์•ก์ด ์ƒ๊ฐ๋ณด๋‹ค ๋งŽ์•„์„œ ๋งŒ์กฑํ–ˆ์–ด์š”!" }, + { reviewId: 6, isAwarded: true, applicationYear: 2022, semester: "1ํ•™๊ธฐ", content: "์„ฑ์ ์ด ์กฐ๊ธˆ ๋ถ€์กฑํ•œ๊ฐ€ ์‹ถ์—ˆ๋Š”๋ฐ ๊ดœ์ฐฎ์•˜์–ด์š”." }, + { reviewId: 7, isAwarded: false, applicationYear: 2024, semester: "1ํ•™๊ธฐ", content: "๋‹ค์Œ์— ๋‹ค์‹œ ์‹ ์ฒญํ•˜๋ ค๊ณ ์š”.." }, + { reviewId: 8, isAwarded: true, applicationYear: 2020, semester: "2ํ•™๊ธฐ", content: "ํ•™์ ๋ณด๋‹จ ๋ฉด์ ‘์ด ๋” ์ค‘์š”ํ•œ ๊ฒƒ ๊ฐ™์•„์š”!" }, + { reviewId: 9, isAwarded: false, applicationYear: 2021, semester: "1ํ•™๊ธฐ", content: "์™œ ๋–จ์–ด์กŒ๋Š”์ง€ ์ž˜ ๋ชจ๋ฅด๊ฒ ์–ด์š”ใ… ใ… " }, + { reviewId: 10, isAwarded: true, applicationYear: 2018, semester: "2ํ•™๊ธฐ", content: "์ง€์› ๋‹น์‹œ ํ•™์ ์€ X.XX์˜€์–ด์š”." }, +]; + +function ReviewList() { + + const reviewsInOnePage = 5; + const [currentPage, setCurrentPage] = useState(1); + + const [filterIsAwarded, setFilterIsAwarded] = useState(""); + const [filterApplicationYear, setFilterApplicationYear] = useState(""); + const [filterSemester, setFilterSemester] = useState(""); + + const filteredReviews = dummies.filter((review) => { + const findIsAwarded = filterIsAwarded === "" || (filterIsAwarded === "์ˆ˜ํ˜œํ•จ" && review.isAwarded) || (filterIsAwarded === "์ˆ˜ํ˜œ ์•ˆํ•จ" && !review.isAwarded); + const findApplicationYear = filterApplicationYear === "" || review.applicationYear.toString() === filterApplicationYear; + const findSemester = filterSemester === "" || `${review.applicationYear}-${review.semester}` === filterSemester; + + return findIsAwarded && findApplicationYear && findSemester; + }); + + const indexOfLastReview = currentPage * reviewsInOnePage; + const indexOfFirstReview = indexOfLastReview - reviewsInOnePage; + const currentReviews = filteredReviews.slice(indexOfFirstReview, indexOfLastReview); + + function previousPage() { + if (currentPage > 1) { + setCurrentPage(currentPage - 1); + } + } + + function nextPage() { + if (indexOfLastReview < filteredReviews.length) { + setCurrentPage(currentPage + 1); + } + } + + return ( + <div> + <h2>ํ•™์ƒ๋“ค์˜ ๋ฆฌ๋ทฐ</h2> + + <div> + <label> + ์ˆ˜ํ˜œ ์—ฌ๋ถ€ + <select value={filterIsAwarded} onChange={(e) => setFilterIsAwarded(e.target.value)}> + <option value="">์ „์ฒด</option> + <option value="์ˆ˜ํ˜œํ•จ">์ˆ˜ํ˜œํ•จ</option> + <option value="์ˆ˜ํ˜œ ์•ˆํ•จ">์ˆ˜ํ˜œ ์•ˆํ•จ</option> + </select> + </label> + + <label> + ์‹ ์ฒญ ์—ฐ๋„ + <input + type="number" + placeholder="์‹ ์ฒญ ์—ฐ๋„๋ฅผ ์ž…๋ ฅํ•˜์„ธ์š”" + value={filterApplicationYear} + onChange={(e) => setFilterApplicationYear(e.target.value)} + /> + </label> + + <label> + ํ•™๊ธฐ + <select value={filterSemester} onChange={(e) => setFilterSemester(e.target.value)}> + <option value="">์ „์ฒด</option> + <option value="1ํ•™๊ธฐ">1ํ•™๊ธฐ</option> + <option value="2ํ•™๊ธฐ">2ํ•™๊ธฐ</option> + </select> + </label> + </div> + + <div> + {currentReviews.length > 0 && currentReviews.map((review) => ( + <div key={review.reviewId}> + <p><strong>์ต๋ช…</strong></p> + <p>{review.isAwarded ? "์ˆ˜ํ˜œํ•จ" : "์ˆ˜ํ˜œ ์•ˆํ•จ"}</p> + <p>{review.applicationYear}-{review.semester}</p> + <p>{review.content}</p> + </div> + ))} + </div> + + <div> + <button onClick={previousPage} disabled={currentPage === 1}>์ด์ „</button> + <span> {currentPage} </span> + <button onClick={nextPage} disabled={indexOfLastReview >= filteredReviews.length}>๋‹ค์Œ</button> + </div> + </div> + ); +} + +export default ReviewList; \ No newline at end of file
Unknown
์˜คํ˜ธ~ ์„ธ์‹ฌํ•˜๊ฒŒ disabled๊นŒ์ง€ ์ฑ™๊ธฐ๋‹ค๋‹ˆ~๐Ÿ‘
@@ -0,0 +1,73 @@ +package com.eureka.spartaonetoone.review.application; + +import com.eureka.spartaonetoone.review.application.dtos.request.ReviewRequestDto; +import com.eureka.spartaonetoone.review.application.dtos.response.ReviewResponseDto; +import com.eureka.spartaonetoone.review.application.exception.ReviewException; +import com.eureka.spartaonetoone.review.domain.Review; +import com.eureka.spartaonetoone.review.domain.repository.ReviewRepository; + +import org.springframework.data.domain.Page; +import org.springframework.data.domain.PageImpl; +import org.springframework.data.domain.Pageable; +import org.springframework.stereotype.Service; +import org.springframework.validation.annotation.Validated; + +import java.util.List; +import java.util.UUID; +import java.util.stream.Collectors; + +import jakarta.validation.Valid; + +@Service +@Validated +public class ReviewService { + + private final ReviewRepository reviewRepository; + + public ReviewService(ReviewRepository reviewRepository) { + this.reviewRepository = reviewRepository; + } + + // ๋ฆฌ๋ทฐ ๋“ฑ๋ก - DTO๋ฅผ ์—”ํ‹ฐํ‹ฐ๋กœ ๋ณ€ํ™˜ํ•œ ํ›„ ์ €์žฅํ•˜๊ณ , ์ €์žฅ๋œ ์—”ํ‹ฐํ‹ฐ๋ฅผ DTO๋กœ ๋ณ€ํ™˜ํ•˜์—ฌ ๋ฐ˜ํ™˜ + public ReviewResponseDto createReview(@Valid ReviewRequestDto dto) { + Review review = dto.createReview(); + Review savedReview = reviewRepository.save(review); + return ReviewResponseDto.from(savedReview); + } + + // ํŠน์ • ๋ฆฌ๋ทฐ ์กฐํšŒ - ์ฃผ์–ด์ง„ reviewId๋กœ Review ์—”ํ‹ฐํ‹ฐ๋ฅผ ์กฐํšŒํ•˜๋ฉฐ, ์กด์žฌํ•˜์ง€ ์•Š์œผ๋ฉด CustomException์„ ๋ฐœ์ƒ + public ReviewResponseDto getReviewById(UUID reviewId) { + Review review = reviewRepository.findById(reviewId) + .orElseThrow(ReviewException.ReviewNotFoundException::new); + return ReviewResponseDto.from(review); + } + + // ํŠน์ • ์ฃผ๋ฌธ(orderId)์— ์†ํ•œ ๋ฆฌ๋ทฐ ๋ชฉ๋ก ์กฐํšŒ + // ReviewRepository์˜ findByOrderId()๋ฅผ ์‚ฌ์šฉํ•˜์—ฌ ํ•ด๋‹น ์ฃผ๋ฌธ์˜ ๋ชจ๋“  ๋ฆฌ๋ทฐ๋ฅผ ์กฐํšŒ + // ๋ฆฌ์ŠคํŠธ๋ฅผ Pageable๋กœ ๊ฐ์‹ธ์„œ ๋ฐ˜ํ™˜ + public Page<ReviewResponseDto> getReviewsByOrderId(UUID orderId, Pageable pageable) { + List<Review> reviews = reviewRepository.findByOrderId(orderId); + List<ReviewResponseDto> dtoList = reviews.stream() + .map(ReviewResponseDto::from) + .collect(Collectors.toList()); + return new PageImpl<>(dtoList, pageable, dtoList.size()); + } + + // ๋ฆฌ๋ทฐ ์ˆ˜์ • - ํŠน์ • reviewId์— ํ•ด๋‹นํ•˜๋Š” Review ์—”ํ‹ฐํ‹ฐ๋ฅผ ์กฐํšŒํ•œ ํ›„, DTO์˜ ๊ฐ’์œผ๋กœ ์—…๋ฐ์ดํŠธํ•˜๊ณ  ์ €์žฅ + public ReviewResponseDto updateReview(UUID reviewId, @Valid ReviewRequestDto dto) { + Review review = reviewRepository.findById(reviewId) + .orElseThrow(ReviewException.ReviewNotFoundException::new); + review.update(dto.getContent(), dto.getRating(), dto.getImage()); + Review updatedReview = reviewRepository.save(review); + return ReviewResponseDto.from(updatedReview); + } + + + // ๋ฆฌ๋ทฐ ์‚ญ์ œ - ํŠน์ • reviewId๋กœ Review ์—”ํ‹ฐํ‹ฐ๋ฅผ ์กฐํšŒํ•œ ํ›„, markDeleted()๋ฅผ ํ˜ธ์ถœ + public void deleteReview(UUID reviewId) { + Review review = reviewRepository.findById(reviewId) + .orElseThrow(ReviewException.ReviewNotFoundException::new); + review.markDeleted(); + reviewRepository.save(review); + } +} \ No newline at end of file
Java
์•„๋ž˜ ์ฝ”๋“œ๋กœ ๋ณ€๊ฒฝ ๋ถ€ํƒ๋“œ๋ฆด๊ฒŒ์š” ~~ :) return ReviewResponseDto.from(review);
@@ -0,0 +1,73 @@ +package com.eureka.spartaonetoone.review.application; + +import com.eureka.spartaonetoone.review.application.dtos.request.ReviewRequestDto; +import com.eureka.spartaonetoone.review.application.dtos.response.ReviewResponseDto; +import com.eureka.spartaonetoone.review.application.exception.ReviewException; +import com.eureka.spartaonetoone.review.domain.Review; +import com.eureka.spartaonetoone.review.domain.repository.ReviewRepository; + +import org.springframework.data.domain.Page; +import org.springframework.data.domain.PageImpl; +import org.springframework.data.domain.Pageable; +import org.springframework.stereotype.Service; +import org.springframework.validation.annotation.Validated; + +import java.util.List; +import java.util.UUID; +import java.util.stream.Collectors; + +import jakarta.validation.Valid; + +@Service +@Validated +public class ReviewService { + + private final ReviewRepository reviewRepository; + + public ReviewService(ReviewRepository reviewRepository) { + this.reviewRepository = reviewRepository; + } + + // ๋ฆฌ๋ทฐ ๋“ฑ๋ก - DTO๋ฅผ ์—”ํ‹ฐํ‹ฐ๋กœ ๋ณ€ํ™˜ํ•œ ํ›„ ์ €์žฅํ•˜๊ณ , ์ €์žฅ๋œ ์—”ํ‹ฐํ‹ฐ๋ฅผ DTO๋กœ ๋ณ€ํ™˜ํ•˜์—ฌ ๋ฐ˜ํ™˜ + public ReviewResponseDto createReview(@Valid ReviewRequestDto dto) { + Review review = dto.createReview(); + Review savedReview = reviewRepository.save(review); + return ReviewResponseDto.from(savedReview); + } + + // ํŠน์ • ๋ฆฌ๋ทฐ ์กฐํšŒ - ์ฃผ์–ด์ง„ reviewId๋กœ Review ์—”ํ‹ฐํ‹ฐ๋ฅผ ์กฐํšŒํ•˜๋ฉฐ, ์กด์žฌํ•˜์ง€ ์•Š์œผ๋ฉด CustomException์„ ๋ฐœ์ƒ + public ReviewResponseDto getReviewById(UUID reviewId) { + Review review = reviewRepository.findById(reviewId) + .orElseThrow(ReviewException.ReviewNotFoundException::new); + return ReviewResponseDto.from(review); + } + + // ํŠน์ • ์ฃผ๋ฌธ(orderId)์— ์†ํ•œ ๋ฆฌ๋ทฐ ๋ชฉ๋ก ์กฐํšŒ + // ReviewRepository์˜ findByOrderId()๋ฅผ ์‚ฌ์šฉํ•˜์—ฌ ํ•ด๋‹น ์ฃผ๋ฌธ์˜ ๋ชจ๋“  ๋ฆฌ๋ทฐ๋ฅผ ์กฐํšŒ + // ๋ฆฌ์ŠคํŠธ๋ฅผ Pageable๋กœ ๊ฐ์‹ธ์„œ ๋ฐ˜ํ™˜ + public Page<ReviewResponseDto> getReviewsByOrderId(UUID orderId, Pageable pageable) { + List<Review> reviews = reviewRepository.findByOrderId(orderId); + List<ReviewResponseDto> dtoList = reviews.stream() + .map(ReviewResponseDto::from) + .collect(Collectors.toList()); + return new PageImpl<>(dtoList, pageable, dtoList.size()); + } + + // ๋ฆฌ๋ทฐ ์ˆ˜์ • - ํŠน์ • reviewId์— ํ•ด๋‹นํ•˜๋Š” Review ์—”ํ‹ฐํ‹ฐ๋ฅผ ์กฐํšŒํ•œ ํ›„, DTO์˜ ๊ฐ’์œผ๋กœ ์—…๋ฐ์ดํŠธํ•˜๊ณ  ์ €์žฅ + public ReviewResponseDto updateReview(UUID reviewId, @Valid ReviewRequestDto dto) { + Review review = reviewRepository.findById(reviewId) + .orElseThrow(ReviewException.ReviewNotFoundException::new); + review.update(dto.getContent(), dto.getRating(), dto.getImage()); + Review updatedReview = reviewRepository.save(review); + return ReviewResponseDto.from(updatedReview); + } + + + // ๋ฆฌ๋ทฐ ์‚ญ์ œ - ํŠน์ • reviewId๋กœ Review ์—”ํ‹ฐํ‹ฐ๋ฅผ ์กฐํšŒํ•œ ํ›„, markDeleted()๋ฅผ ํ˜ธ์ถœ + public void deleteReview(UUID reviewId) { + Review review = reviewRepository.findById(reviewId) + .orElseThrow(ReviewException.ReviewNotFoundException::new); + review.markDeleted(); + reviewRepository.save(review); + } +} \ No newline at end of file
Java
์š” ๋ฉ”์„œ๋“œ๋Š” ์ œ๊ฑฐํ•ด์ฃผ์…”๋„ ๋  ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค ๋ฏผ์ˆ˜๋‹˜ ~~!
@@ -0,0 +1,152 @@ +package com.eureka.spartaonetoone.store.application; + +import com.eureka.spartaonetoone.common.client.OrderClient; +import com.eureka.spartaonetoone.common.client.ReviewClient; +import com.eureka.spartaonetoone.common.dtos.response.ReviewResponse; +import com.eureka.spartaonetoone.common.dtos.response.OrderResponse; +import com.eureka.spartaonetoone.store.application.exception.StoreException; +import com.eureka.spartaonetoone.store.domain.Store; +import com.eureka.spartaonetoone.store.domain.StoreState; +import com.eureka.spartaonetoone.store.domain.repository.StoreRepository; +import com.eureka.spartaonetoone.store.application.dtos.StoreRequestDto; +import com.eureka.spartaonetoone.store.application.dtos.StoreResponseDto; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.Pageable; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.validation.annotation.Validated; + +import java.util.List; +import java.util.UUID; +import java.util.stream.Collectors; + +@Service +@Validated +public class StoreService { + + private final StoreRepository storeRepository; + private final OrderClient orderClient; + private final ReviewClient reviewClient; + + // ์ƒ์„ฑ์ž ์ฃผ์ž… + public StoreService(StoreRepository storeRepository, OrderClient orderClient, ReviewClient reviewClient) { + this.storeRepository = storeRepository; + this.orderClient = orderClient; + this.reviewClient = reviewClient; + } + + // DTO -> ์—”ํ‹ฐํ‹ฐ ๋ณ€ํ™˜ ๋ฉ”์„œ๋“œ (Service ๋‚ด๋ถ€ ๋ณ€ํ™˜ ๋กœ์ง) - StoreRequestDto์˜ ๊ฐ’์„ ์ถ”์ถœํ•˜์—ฌ, Store ์—”ํ‹ฐํ‹ฐ๋ฅผ ์ƒ์„ฑํ•˜๋Š” ๋ฐ ์‚ฌ์šฉ + private Store convertDtoToEntity(StoreRequestDto dto) { + StoreState stateEnum; + try { + // DTO์˜ state ๋ฌธ์ž์—ด์„ ๋Œ€๋ฌธ์ž๋กœ ๋ณ€ํ™˜ ํ›„ ENUM์œผ๋กœ ๋ณ€ํ™˜. ์ž˜๋ชป๋œ ๊ฐ’์ด๋ฉด ๊ธฐ๋ณธ๊ฐ’ OPEN ์‚ฌ์šฉ. + stateEnum = dto.getState() != null ? StoreState.valueOf(dto.getState().toUpperCase()) : StoreState.OPEN; + } catch (IllegalArgumentException e) { + stateEnum = StoreState.OPEN; + } + // Service ๊ณ„์ธต์—์„œ ํ•„์š”ํ•œ ํ•„๋“œ๋งŒ ์ถ”์ถœํ•˜์—ฌ ์—”ํ‹ฐํ‹ฐ ์ƒ์„ฑ (์ˆœํ™˜์ฐธ์กฐ๋ฅผ ํ”ผํ•˜๊ธฐ ์œ„ํ•ด DTO์— ์ง์ ‘ ์˜์กดํ•˜์ง€ ์•Š์Œ) + return Store.createStore( + dto.getUserId(), + dto.getName(), + stateEnum, + dto.getTellNumber(), + dto.getDescription(), + dto.getMinOrderPrice() != null ? dto.getMinOrderPrice() : 0, + dto.getDeliveryFee() != null ? dto.getDeliveryFee() : 0, + dto.getRating() != null ? dto.getRating() : 0.0f, + dto.getReviewCount() != null ? dto.getReviewCount() : 0, + dto.getCategoryId() + ); + } + + // ๊ฐ€๊ฒŒ ๋“ฑ๋ก - ํด๋ผ์ด์–ธํŠธ๋กœ๋ถ€ํ„ฐ ์ „๋‹ฌ๋ฐ›์€ StoreRequestDto๋ฅผ ๋ณ€ํ™˜ํ•˜์—ฌ Store ์—”ํ‹ฐํ‹ฐ๋กœ ์ƒ์„ฑํ•˜๊ณ , ์ €์žฅํ•œ ํ›„ DTO๋กœ ๋ฐ˜ํ™˜ + public StoreResponseDto createStore(StoreRequestDto dto) { + Store store = convertDtoToEntity(dto); + Store savedStore = storeRepository.save(store); + return StoreResponseDto.of(savedStore); + } + + // ํŠน์ • ๊ฐ€๊ฒŒ ์กฐํšŒ + public StoreResponseDto getStoreById(UUID storeId) { + Store store = storeRepository.findById(storeId) + .orElseThrow(StoreException.StoreNotFoundException::new); + return StoreResponseDto.of(store); + } + + // ์ „์ฒด ๊ฐ€๊ฒŒ ์กฐํšŒ(ํŽ˜์ด์ง€๋„ค์ด์…˜ ์ง€์›) - Pageable์„ ์‚ฌ์šฉํ•ด Store ์—”ํ‹ฐํ‹ฐ๋ฅผ ํŽ˜์ด์ง€ ๋‹จ์œ„๋กœ ์กฐํšŒํ•˜๊ณ , ๊ฐ Entity๋ฅผ DTO๋กœ ๋ณ€ํ™˜ํ•˜์—ฌ Page ๊ฐ์ฒด๋กœ ๋ฐ˜ํ™˜ + public Page<StoreResponseDto> getAllStores(Pageable pageable) { + return storeRepository.findAll(pageable) + .map(StoreResponseDto::of); + } + + // ๊ฐ€๊ฒŒ ์ˆ˜์ • - ํŠน์ • storeId์— ํ•ด๋‹นํ•˜๋Š” Entity๋ฅผ ์กฐํšŒํ•œ ํ›„, DTO์˜ ๊ฐ’์œผ๋กœ ์—…๋ฐ์ดํŠธํ•˜๊ณ  ์ €์žฅ + public StoreResponseDto updateStore(UUID storeId, StoreRequestDto dto) { + // storeId์— ํ•ด๋‹นํ•˜๋Š” ๊ฐ€๊ฒŒ๋ฅผ ์กฐํšŒ (์—†์œผ๋ฉด ์˜ˆ์™ธ ๋ฐœ์ƒ) + Store store = storeRepository.findById(storeId) + .orElseThrow(StoreException.StoreNotFoundException::new); + + // DTO์˜ state ๊ฐ’์„ ๋Œ€๋ฌธ์ž๋กœ ๋ณ€ํ™˜ํ•˜์—ฌ ENUM์œผ๋กœ ๋งคํ•‘, ์˜ค๋ฅ˜ ๋ฐœ์ƒ ์‹œ ๊ธฐ์กด ๊ฐ’์„ ์‚ฌ์šฉ + StoreState stateEnum; + try { + stateEnum = (dto.getState() != null) ? StoreState.valueOf(dto.getState().toUpperCase()) : store.getState(); + } catch(Exception e) { + stateEnum = store.getState(); + } + store.update( + dto.getName(), + stateEnum, + dto.getTellNumber(), + dto.getDescription(), + dto.getMinOrderPrice(), + dto.getDeliveryFee(), + store.getRating(), + store.getReviewCount(), + dto.getCategoryId() + ); + Store updatedStore = storeRepository.save(store); + return StoreResponseDto.of(updatedStore); + } + + // ์ฃผ์–ด์ง„ storeId๋กœ Entity๋ฅผ ์กฐํšŒํ•œ ํ›„, markDeleted()๋ฅผ ํ˜ธ์ถœํ•˜์—ฌ ์‚ญ์ œ๋œ ๊ฒƒ์ฒ˜๋Ÿผ ํ‘œ์‹œํ•˜๊ณ  ์ €์žฅ + @Transactional + public void deleteStore(UUID storeId) { + Store store = storeRepository.findById(storeId) + .orElseThrow(StoreException.StoreNotFoundException::new); + store.markDeleted(); + } + + // ๋ฆฌ๋ทฐ ์ง‘๊ณ„ ์—…๋ฐ์ดํŠธ ๋ฉ”์„œ๋“œ + @Transactional + public void updateStoreReview(UUID storeId) { + // 1. OrderClient๋ฅผ ์‚ฌ์šฉํ•˜์—ฌ ํ•ด๋‹น ๊ฐ€๊ฒŒ์˜ ์ฃผ๋ฌธ ๋ชฉ๋ก ์กฐํšŒ + List<OrderResponse> orders = orderClient.getOrders(storeId); + + // 2. ์ฃผ๋ฌธ ๋ชฉ๋ก์—์„œ ๊ฐ ์ฃผ๋ฌธ์˜ orderId ์ถ”์ถœ + List<UUID> orderIds = orders.stream() + .map(OrderResponse::getOrderId) + .collect(Collectors.toList()); + // 3. ReviewClient๋ฅผ ํ†ตํ•ด ํ•ด๋‹น orderId ๋ชฉ๋ก์— ํ•ด๋‹นํ•˜๋Š” ๋ฆฌ๋ทฐ ๋ฐ์ดํ„ฐ ์กฐํšŒ + List<ReviewResponse> reviews = reviewClient.getReviews(orderIds); + // 4. ์ด ๋ฆฌ๋ทฐ ๊ฐœ์ˆ˜์™€ ์ด ํ‰์  ํ•ฉ๊ณ„ ๊ณ„์‚ฐ + int reviewCount = reviews.size(); + float totalRating = (float) reviews.stream() + .mapToDouble(ReviewResponse::getTotalRating) + .sum(); + float avgRating = reviewCount > 0 ? totalRating / reviewCount : 0.0f; + // 5. ํ•ด๋‹น ๊ฐ€๊ฒŒ ์—”ํ‹ฐํ‹ฐ ์กฐํšŒ ๋ฐ ์—…๋ฐ์ดํŠธ + Store store = storeRepository.findById(storeId) + .orElseThrow(StoreException.StoreNotFoundException::new); + // ๊ธฐ์กด ํ•„๋“œ ์ค‘ ์ด๋ฆ„, state, ์ „ํ™”๋ฒˆํ˜ธ ๋“ฑ์€ ๊ทธ๋Œ€๋กœ ์œ ์ง€ํ•˜๊ณ , ํ‰์ ๊ณผ ๋ฆฌ๋ทฐ ์ˆ˜๋งŒ ์—…๋ฐ์ดํŠธ + store.update( + store.getName(), + store.getState(), + store.getTellNumber(), + store.getDescription(), + store.getMinOrderPrice(), + store.getDeliveryFee(), + avgRating, // ์™ธ๋ถ€์—์„œ ๋ฐ›์•„์˜จ ํ‰๊ท  ํ‰์  + reviewCount, // ์™ธ๋ถ€์—์„œ ๋ฐ›์•„์˜จ ์ด ๋ฆฌ๋ทฐ ์ˆ˜ + store.getCategoryId() + ); + } +}
Java
๋ฏผ์ˆ˜๋‹˜ ์—ฌ๊ธฐ .from ์ด ๋˜์–ด์•ผ ํ•  ๊ฒƒ ๊ฐ™๋„ค์š” ~!! ์ฝ”๋“œ ๋ณต๋ถ™ํ•˜๋А๋ผ ์ œ๊ฐ€ of๋ฅผ ๋ณต๋ถ™ํ–ˆ๋„ค์š” ใ…Žใ…Ž :) from์œผ๋กœ ๋ถ€ํƒ๋“œ๋ฆด๊ฒŒ์š”
@@ -0,0 +1,152 @@ +package com.eureka.spartaonetoone.store.application; + +import com.eureka.spartaonetoone.common.client.OrderClient; +import com.eureka.spartaonetoone.common.client.ReviewClient; +import com.eureka.spartaonetoone.common.dtos.response.ReviewResponse; +import com.eureka.spartaonetoone.common.dtos.response.OrderResponse; +import com.eureka.spartaonetoone.store.application.exception.StoreException; +import com.eureka.spartaonetoone.store.domain.Store; +import com.eureka.spartaonetoone.store.domain.StoreState; +import com.eureka.spartaonetoone.store.domain.repository.StoreRepository; +import com.eureka.spartaonetoone.store.application.dtos.StoreRequestDto; +import com.eureka.spartaonetoone.store.application.dtos.StoreResponseDto; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.Pageable; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.validation.annotation.Validated; + +import java.util.List; +import java.util.UUID; +import java.util.stream.Collectors; + +@Service +@Validated +public class StoreService { + + private final StoreRepository storeRepository; + private final OrderClient orderClient; + private final ReviewClient reviewClient; + + // ์ƒ์„ฑ์ž ์ฃผ์ž… + public StoreService(StoreRepository storeRepository, OrderClient orderClient, ReviewClient reviewClient) { + this.storeRepository = storeRepository; + this.orderClient = orderClient; + this.reviewClient = reviewClient; + } + + // DTO -> ์—”ํ‹ฐํ‹ฐ ๋ณ€ํ™˜ ๋ฉ”์„œ๋“œ (Service ๋‚ด๋ถ€ ๋ณ€ํ™˜ ๋กœ์ง) - StoreRequestDto์˜ ๊ฐ’์„ ์ถ”์ถœํ•˜์—ฌ, Store ์—”ํ‹ฐํ‹ฐ๋ฅผ ์ƒ์„ฑํ•˜๋Š” ๋ฐ ์‚ฌ์šฉ + private Store convertDtoToEntity(StoreRequestDto dto) { + StoreState stateEnum; + try { + // DTO์˜ state ๋ฌธ์ž์—ด์„ ๋Œ€๋ฌธ์ž๋กœ ๋ณ€ํ™˜ ํ›„ ENUM์œผ๋กœ ๋ณ€ํ™˜. ์ž˜๋ชป๋œ ๊ฐ’์ด๋ฉด ๊ธฐ๋ณธ๊ฐ’ OPEN ์‚ฌ์šฉ. + stateEnum = dto.getState() != null ? StoreState.valueOf(dto.getState().toUpperCase()) : StoreState.OPEN; + } catch (IllegalArgumentException e) { + stateEnum = StoreState.OPEN; + } + // Service ๊ณ„์ธต์—์„œ ํ•„์š”ํ•œ ํ•„๋“œ๋งŒ ์ถ”์ถœํ•˜์—ฌ ์—”ํ‹ฐํ‹ฐ ์ƒ์„ฑ (์ˆœํ™˜์ฐธ์กฐ๋ฅผ ํ”ผํ•˜๊ธฐ ์œ„ํ•ด DTO์— ์ง์ ‘ ์˜์กดํ•˜์ง€ ์•Š์Œ) + return Store.createStore( + dto.getUserId(), + dto.getName(), + stateEnum, + dto.getTellNumber(), + dto.getDescription(), + dto.getMinOrderPrice() != null ? dto.getMinOrderPrice() : 0, + dto.getDeliveryFee() != null ? dto.getDeliveryFee() : 0, + dto.getRating() != null ? dto.getRating() : 0.0f, + dto.getReviewCount() != null ? dto.getReviewCount() : 0, + dto.getCategoryId() + ); + } + + // ๊ฐ€๊ฒŒ ๋“ฑ๋ก - ํด๋ผ์ด์–ธํŠธ๋กœ๋ถ€ํ„ฐ ์ „๋‹ฌ๋ฐ›์€ StoreRequestDto๋ฅผ ๋ณ€ํ™˜ํ•˜์—ฌ Store ์—”ํ‹ฐํ‹ฐ๋กœ ์ƒ์„ฑํ•˜๊ณ , ์ €์žฅํ•œ ํ›„ DTO๋กœ ๋ฐ˜ํ™˜ + public StoreResponseDto createStore(StoreRequestDto dto) { + Store store = convertDtoToEntity(dto); + Store savedStore = storeRepository.save(store); + return StoreResponseDto.of(savedStore); + } + + // ํŠน์ • ๊ฐ€๊ฒŒ ์กฐํšŒ + public StoreResponseDto getStoreById(UUID storeId) { + Store store = storeRepository.findById(storeId) + .orElseThrow(StoreException.StoreNotFoundException::new); + return StoreResponseDto.of(store); + } + + // ์ „์ฒด ๊ฐ€๊ฒŒ ์กฐํšŒ(ํŽ˜์ด์ง€๋„ค์ด์…˜ ์ง€์›) - Pageable์„ ์‚ฌ์šฉํ•ด Store ์—”ํ‹ฐํ‹ฐ๋ฅผ ํŽ˜์ด์ง€ ๋‹จ์œ„๋กœ ์กฐํšŒํ•˜๊ณ , ๊ฐ Entity๋ฅผ DTO๋กœ ๋ณ€ํ™˜ํ•˜์—ฌ Page ๊ฐ์ฒด๋กœ ๋ฐ˜ํ™˜ + public Page<StoreResponseDto> getAllStores(Pageable pageable) { + return storeRepository.findAll(pageable) + .map(StoreResponseDto::of); + } + + // ๊ฐ€๊ฒŒ ์ˆ˜์ • - ํŠน์ • storeId์— ํ•ด๋‹นํ•˜๋Š” Entity๋ฅผ ์กฐํšŒํ•œ ํ›„, DTO์˜ ๊ฐ’์œผ๋กœ ์—…๋ฐ์ดํŠธํ•˜๊ณ  ์ €์žฅ + public StoreResponseDto updateStore(UUID storeId, StoreRequestDto dto) { + // storeId์— ํ•ด๋‹นํ•˜๋Š” ๊ฐ€๊ฒŒ๋ฅผ ์กฐํšŒ (์—†์œผ๋ฉด ์˜ˆ์™ธ ๋ฐœ์ƒ) + Store store = storeRepository.findById(storeId) + .orElseThrow(StoreException.StoreNotFoundException::new); + + // DTO์˜ state ๊ฐ’์„ ๋Œ€๋ฌธ์ž๋กœ ๋ณ€ํ™˜ํ•˜์—ฌ ENUM์œผ๋กœ ๋งคํ•‘, ์˜ค๋ฅ˜ ๋ฐœ์ƒ ์‹œ ๊ธฐ์กด ๊ฐ’์„ ์‚ฌ์šฉ + StoreState stateEnum; + try { + stateEnum = (dto.getState() != null) ? StoreState.valueOf(dto.getState().toUpperCase()) : store.getState(); + } catch(Exception e) { + stateEnum = store.getState(); + } + store.update( + dto.getName(), + stateEnum, + dto.getTellNumber(), + dto.getDescription(), + dto.getMinOrderPrice(), + dto.getDeliveryFee(), + store.getRating(), + store.getReviewCount(), + dto.getCategoryId() + ); + Store updatedStore = storeRepository.save(store); + return StoreResponseDto.of(updatedStore); + } + + // ์ฃผ์–ด์ง„ storeId๋กœ Entity๋ฅผ ์กฐํšŒํ•œ ํ›„, markDeleted()๋ฅผ ํ˜ธ์ถœํ•˜์—ฌ ์‚ญ์ œ๋œ ๊ฒƒ์ฒ˜๋Ÿผ ํ‘œ์‹œํ•˜๊ณ  ์ €์žฅ + @Transactional + public void deleteStore(UUID storeId) { + Store store = storeRepository.findById(storeId) + .orElseThrow(StoreException.StoreNotFoundException::new); + store.markDeleted(); + } + + // ๋ฆฌ๋ทฐ ์ง‘๊ณ„ ์—…๋ฐ์ดํŠธ ๋ฉ”์„œ๋“œ + @Transactional + public void updateStoreReview(UUID storeId) { + // 1. OrderClient๋ฅผ ์‚ฌ์šฉํ•˜์—ฌ ํ•ด๋‹น ๊ฐ€๊ฒŒ์˜ ์ฃผ๋ฌธ ๋ชฉ๋ก ์กฐํšŒ + List<OrderResponse> orders = orderClient.getOrders(storeId); + + // 2. ์ฃผ๋ฌธ ๋ชฉ๋ก์—์„œ ๊ฐ ์ฃผ๋ฌธ์˜ orderId ์ถ”์ถœ + List<UUID> orderIds = orders.stream() + .map(OrderResponse::getOrderId) + .collect(Collectors.toList()); + // 3. ReviewClient๋ฅผ ํ†ตํ•ด ํ•ด๋‹น orderId ๋ชฉ๋ก์— ํ•ด๋‹นํ•˜๋Š” ๋ฆฌ๋ทฐ ๋ฐ์ดํ„ฐ ์กฐํšŒ + List<ReviewResponse> reviews = reviewClient.getReviews(orderIds); + // 4. ์ด ๋ฆฌ๋ทฐ ๊ฐœ์ˆ˜์™€ ์ด ํ‰์  ํ•ฉ๊ณ„ ๊ณ„์‚ฐ + int reviewCount = reviews.size(); + float totalRating = (float) reviews.stream() + .mapToDouble(ReviewResponse::getTotalRating) + .sum(); + float avgRating = reviewCount > 0 ? totalRating / reviewCount : 0.0f; + // 5. ํ•ด๋‹น ๊ฐ€๊ฒŒ ์—”ํ‹ฐํ‹ฐ ์กฐํšŒ ๋ฐ ์—…๋ฐ์ดํŠธ + Store store = storeRepository.findById(storeId) + .orElseThrow(StoreException.StoreNotFoundException::new); + // ๊ธฐ์กด ํ•„๋“œ ์ค‘ ์ด๋ฆ„, state, ์ „ํ™”๋ฒˆํ˜ธ ๋“ฑ์€ ๊ทธ๋Œ€๋กœ ์œ ์ง€ํ•˜๊ณ , ํ‰์ ๊ณผ ๋ฆฌ๋ทฐ ์ˆ˜๋งŒ ์—…๋ฐ์ดํŠธ + store.update( + store.getName(), + store.getState(), + store.getTellNumber(), + store.getDescription(), + store.getMinOrderPrice(), + store.getDeliveryFee(), + avgRating, // ์™ธ๋ถ€์—์„œ ๋ฐ›์•„์˜จ ํ‰๊ท  ํ‰์  + reviewCount, // ์™ธ๋ถ€์—์„œ ๋ฐ›์•„์˜จ ์ด ๋ฆฌ๋ทฐ ์ˆ˜ + store.getCategoryId() + ); + } +}
Java
from์œผ๋กœ ๋ถ€ํƒ๋“œ๋ฆด๊ฒŒ์š”
@@ -0,0 +1,152 @@ +package com.eureka.spartaonetoone.store.application; + +import com.eureka.spartaonetoone.common.client.OrderClient; +import com.eureka.spartaonetoone.common.client.ReviewClient; +import com.eureka.spartaonetoone.common.dtos.response.ReviewResponse; +import com.eureka.spartaonetoone.common.dtos.response.OrderResponse; +import com.eureka.spartaonetoone.store.application.exception.StoreException; +import com.eureka.spartaonetoone.store.domain.Store; +import com.eureka.spartaonetoone.store.domain.StoreState; +import com.eureka.spartaonetoone.store.domain.repository.StoreRepository; +import com.eureka.spartaonetoone.store.application.dtos.StoreRequestDto; +import com.eureka.spartaonetoone.store.application.dtos.StoreResponseDto; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.Pageable; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.validation.annotation.Validated; + +import java.util.List; +import java.util.UUID; +import java.util.stream.Collectors; + +@Service +@Validated +public class StoreService { + + private final StoreRepository storeRepository; + private final OrderClient orderClient; + private final ReviewClient reviewClient; + + // ์ƒ์„ฑ์ž ์ฃผ์ž… + public StoreService(StoreRepository storeRepository, OrderClient orderClient, ReviewClient reviewClient) { + this.storeRepository = storeRepository; + this.orderClient = orderClient; + this.reviewClient = reviewClient; + } + + // DTO -> ์—”ํ‹ฐํ‹ฐ ๋ณ€ํ™˜ ๋ฉ”์„œ๋“œ (Service ๋‚ด๋ถ€ ๋ณ€ํ™˜ ๋กœ์ง) - StoreRequestDto์˜ ๊ฐ’์„ ์ถ”์ถœํ•˜์—ฌ, Store ์—”ํ‹ฐํ‹ฐ๋ฅผ ์ƒ์„ฑํ•˜๋Š” ๋ฐ ์‚ฌ์šฉ + private Store convertDtoToEntity(StoreRequestDto dto) { + StoreState stateEnum; + try { + // DTO์˜ state ๋ฌธ์ž์—ด์„ ๋Œ€๋ฌธ์ž๋กœ ๋ณ€ํ™˜ ํ›„ ENUM์œผ๋กœ ๋ณ€ํ™˜. ์ž˜๋ชป๋œ ๊ฐ’์ด๋ฉด ๊ธฐ๋ณธ๊ฐ’ OPEN ์‚ฌ์šฉ. + stateEnum = dto.getState() != null ? StoreState.valueOf(dto.getState().toUpperCase()) : StoreState.OPEN; + } catch (IllegalArgumentException e) { + stateEnum = StoreState.OPEN; + } + // Service ๊ณ„์ธต์—์„œ ํ•„์š”ํ•œ ํ•„๋“œ๋งŒ ์ถ”์ถœํ•˜์—ฌ ์—”ํ‹ฐํ‹ฐ ์ƒ์„ฑ (์ˆœํ™˜์ฐธ์กฐ๋ฅผ ํ”ผํ•˜๊ธฐ ์œ„ํ•ด DTO์— ์ง์ ‘ ์˜์กดํ•˜์ง€ ์•Š์Œ) + return Store.createStore( + dto.getUserId(), + dto.getName(), + stateEnum, + dto.getTellNumber(), + dto.getDescription(), + dto.getMinOrderPrice() != null ? dto.getMinOrderPrice() : 0, + dto.getDeliveryFee() != null ? dto.getDeliveryFee() : 0, + dto.getRating() != null ? dto.getRating() : 0.0f, + dto.getReviewCount() != null ? dto.getReviewCount() : 0, + dto.getCategoryId() + ); + } + + // ๊ฐ€๊ฒŒ ๋“ฑ๋ก - ํด๋ผ์ด์–ธํŠธ๋กœ๋ถ€ํ„ฐ ์ „๋‹ฌ๋ฐ›์€ StoreRequestDto๋ฅผ ๋ณ€ํ™˜ํ•˜์—ฌ Store ์—”ํ‹ฐํ‹ฐ๋กœ ์ƒ์„ฑํ•˜๊ณ , ์ €์žฅํ•œ ํ›„ DTO๋กœ ๋ฐ˜ํ™˜ + public StoreResponseDto createStore(StoreRequestDto dto) { + Store store = convertDtoToEntity(dto); + Store savedStore = storeRepository.save(store); + return StoreResponseDto.of(savedStore); + } + + // ํŠน์ • ๊ฐ€๊ฒŒ ์กฐํšŒ + public StoreResponseDto getStoreById(UUID storeId) { + Store store = storeRepository.findById(storeId) + .orElseThrow(StoreException.StoreNotFoundException::new); + return StoreResponseDto.of(store); + } + + // ์ „์ฒด ๊ฐ€๊ฒŒ ์กฐํšŒ(ํŽ˜์ด์ง€๋„ค์ด์…˜ ์ง€์›) - Pageable์„ ์‚ฌ์šฉํ•ด Store ์—”ํ‹ฐํ‹ฐ๋ฅผ ํŽ˜์ด์ง€ ๋‹จ์œ„๋กœ ์กฐํšŒํ•˜๊ณ , ๊ฐ Entity๋ฅผ DTO๋กœ ๋ณ€ํ™˜ํ•˜์—ฌ Page ๊ฐ์ฒด๋กœ ๋ฐ˜ํ™˜ + public Page<StoreResponseDto> getAllStores(Pageable pageable) { + return storeRepository.findAll(pageable) + .map(StoreResponseDto::of); + } + + // ๊ฐ€๊ฒŒ ์ˆ˜์ • - ํŠน์ • storeId์— ํ•ด๋‹นํ•˜๋Š” Entity๋ฅผ ์กฐํšŒํ•œ ํ›„, DTO์˜ ๊ฐ’์œผ๋กœ ์—…๋ฐ์ดํŠธํ•˜๊ณ  ์ €์žฅ + public StoreResponseDto updateStore(UUID storeId, StoreRequestDto dto) { + // storeId์— ํ•ด๋‹นํ•˜๋Š” ๊ฐ€๊ฒŒ๋ฅผ ์กฐํšŒ (์—†์œผ๋ฉด ์˜ˆ์™ธ ๋ฐœ์ƒ) + Store store = storeRepository.findById(storeId) + .orElseThrow(StoreException.StoreNotFoundException::new); + + // DTO์˜ state ๊ฐ’์„ ๋Œ€๋ฌธ์ž๋กœ ๋ณ€ํ™˜ํ•˜์—ฌ ENUM์œผ๋กœ ๋งคํ•‘, ์˜ค๋ฅ˜ ๋ฐœ์ƒ ์‹œ ๊ธฐ์กด ๊ฐ’์„ ์‚ฌ์šฉ + StoreState stateEnum; + try { + stateEnum = (dto.getState() != null) ? StoreState.valueOf(dto.getState().toUpperCase()) : store.getState(); + } catch(Exception e) { + stateEnum = store.getState(); + } + store.update( + dto.getName(), + stateEnum, + dto.getTellNumber(), + dto.getDescription(), + dto.getMinOrderPrice(), + dto.getDeliveryFee(), + store.getRating(), + store.getReviewCount(), + dto.getCategoryId() + ); + Store updatedStore = storeRepository.save(store); + return StoreResponseDto.of(updatedStore); + } + + // ์ฃผ์–ด์ง„ storeId๋กœ Entity๋ฅผ ์กฐํšŒํ•œ ํ›„, markDeleted()๋ฅผ ํ˜ธ์ถœํ•˜์—ฌ ์‚ญ์ œ๋œ ๊ฒƒ์ฒ˜๋Ÿผ ํ‘œ์‹œํ•˜๊ณ  ์ €์žฅ + @Transactional + public void deleteStore(UUID storeId) { + Store store = storeRepository.findById(storeId) + .orElseThrow(StoreException.StoreNotFoundException::new); + store.markDeleted(); + } + + // ๋ฆฌ๋ทฐ ์ง‘๊ณ„ ์—…๋ฐ์ดํŠธ ๋ฉ”์„œ๋“œ + @Transactional + public void updateStoreReview(UUID storeId) { + // 1. OrderClient๋ฅผ ์‚ฌ์šฉํ•˜์—ฌ ํ•ด๋‹น ๊ฐ€๊ฒŒ์˜ ์ฃผ๋ฌธ ๋ชฉ๋ก ์กฐํšŒ + List<OrderResponse> orders = orderClient.getOrders(storeId); + + // 2. ์ฃผ๋ฌธ ๋ชฉ๋ก์—์„œ ๊ฐ ์ฃผ๋ฌธ์˜ orderId ์ถ”์ถœ + List<UUID> orderIds = orders.stream() + .map(OrderResponse::getOrderId) + .collect(Collectors.toList()); + // 3. ReviewClient๋ฅผ ํ†ตํ•ด ํ•ด๋‹น orderId ๋ชฉ๋ก์— ํ•ด๋‹นํ•˜๋Š” ๋ฆฌ๋ทฐ ๋ฐ์ดํ„ฐ ์กฐํšŒ + List<ReviewResponse> reviews = reviewClient.getReviews(orderIds); + // 4. ์ด ๋ฆฌ๋ทฐ ๊ฐœ์ˆ˜์™€ ์ด ํ‰์  ํ•ฉ๊ณ„ ๊ณ„์‚ฐ + int reviewCount = reviews.size(); + float totalRating = (float) reviews.stream() + .mapToDouble(ReviewResponse::getTotalRating) + .sum(); + float avgRating = reviewCount > 0 ? totalRating / reviewCount : 0.0f; + // 5. ํ•ด๋‹น ๊ฐ€๊ฒŒ ์—”ํ‹ฐํ‹ฐ ์กฐํšŒ ๋ฐ ์—…๋ฐ์ดํŠธ + Store store = storeRepository.findById(storeId) + .orElseThrow(StoreException.StoreNotFoundException::new); + // ๊ธฐ์กด ํ•„๋“œ ์ค‘ ์ด๋ฆ„, state, ์ „ํ™”๋ฒˆํ˜ธ ๋“ฑ์€ ๊ทธ๋Œ€๋กœ ์œ ์ง€ํ•˜๊ณ , ํ‰์ ๊ณผ ๋ฆฌ๋ทฐ ์ˆ˜๋งŒ ์—…๋ฐ์ดํŠธ + store.update( + store.getName(), + store.getState(), + store.getTellNumber(), + store.getDescription(), + store.getMinOrderPrice(), + store.getDeliveryFee(), + avgRating, // ์™ธ๋ถ€์—์„œ ๋ฐ›์•„์˜จ ํ‰๊ท  ํ‰์  + reviewCount, // ์™ธ๋ถ€์—์„œ ๋ฐ›์•„์˜จ ์ด ๋ฆฌ๋ทฐ ์ˆ˜ + store.getCategoryId() + ); + } +}
Java
๋ฏผ์ˆ˜๋‹˜ ์—ฌ๊ธฐ๋„ .from ์ด ๋˜์–ด์•ผ ํ•  ๊ฒƒ ๊ฐ™๋„ค์š” ~!!
@@ -0,0 +1,152 @@ +package com.eureka.spartaonetoone.store.application; + +import com.eureka.spartaonetoone.common.client.OrderClient; +import com.eureka.spartaonetoone.common.client.ReviewClient; +import com.eureka.spartaonetoone.common.dtos.response.ReviewResponse; +import com.eureka.spartaonetoone.common.dtos.response.OrderResponse; +import com.eureka.spartaonetoone.store.application.exception.StoreException; +import com.eureka.spartaonetoone.store.domain.Store; +import com.eureka.spartaonetoone.store.domain.StoreState; +import com.eureka.spartaonetoone.store.domain.repository.StoreRepository; +import com.eureka.spartaonetoone.store.application.dtos.StoreRequestDto; +import com.eureka.spartaonetoone.store.application.dtos.StoreResponseDto; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.Pageable; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.validation.annotation.Validated; + +import java.util.List; +import java.util.UUID; +import java.util.stream.Collectors; + +@Service +@Validated +public class StoreService { + + private final StoreRepository storeRepository; + private final OrderClient orderClient; + private final ReviewClient reviewClient; + + // ์ƒ์„ฑ์ž ์ฃผ์ž… + public StoreService(StoreRepository storeRepository, OrderClient orderClient, ReviewClient reviewClient) { + this.storeRepository = storeRepository; + this.orderClient = orderClient; + this.reviewClient = reviewClient; + } + + // DTO -> ์—”ํ‹ฐํ‹ฐ ๋ณ€ํ™˜ ๋ฉ”์„œ๋“œ (Service ๋‚ด๋ถ€ ๋ณ€ํ™˜ ๋กœ์ง) - StoreRequestDto์˜ ๊ฐ’์„ ์ถ”์ถœํ•˜์—ฌ, Store ์—”ํ‹ฐํ‹ฐ๋ฅผ ์ƒ์„ฑํ•˜๋Š” ๋ฐ ์‚ฌ์šฉ + private Store convertDtoToEntity(StoreRequestDto dto) { + StoreState stateEnum; + try { + // DTO์˜ state ๋ฌธ์ž์—ด์„ ๋Œ€๋ฌธ์ž๋กœ ๋ณ€ํ™˜ ํ›„ ENUM์œผ๋กœ ๋ณ€ํ™˜. ์ž˜๋ชป๋œ ๊ฐ’์ด๋ฉด ๊ธฐ๋ณธ๊ฐ’ OPEN ์‚ฌ์šฉ. + stateEnum = dto.getState() != null ? StoreState.valueOf(dto.getState().toUpperCase()) : StoreState.OPEN; + } catch (IllegalArgumentException e) { + stateEnum = StoreState.OPEN; + } + // Service ๊ณ„์ธต์—์„œ ํ•„์š”ํ•œ ํ•„๋“œ๋งŒ ์ถ”์ถœํ•˜์—ฌ ์—”ํ‹ฐํ‹ฐ ์ƒ์„ฑ (์ˆœํ™˜์ฐธ์กฐ๋ฅผ ํ”ผํ•˜๊ธฐ ์œ„ํ•ด DTO์— ์ง์ ‘ ์˜์กดํ•˜์ง€ ์•Š์Œ) + return Store.createStore( + dto.getUserId(), + dto.getName(), + stateEnum, + dto.getTellNumber(), + dto.getDescription(), + dto.getMinOrderPrice() != null ? dto.getMinOrderPrice() : 0, + dto.getDeliveryFee() != null ? dto.getDeliveryFee() : 0, + dto.getRating() != null ? dto.getRating() : 0.0f, + dto.getReviewCount() != null ? dto.getReviewCount() : 0, + dto.getCategoryId() + ); + } + + // ๊ฐ€๊ฒŒ ๋“ฑ๋ก - ํด๋ผ์ด์–ธํŠธ๋กœ๋ถ€ํ„ฐ ์ „๋‹ฌ๋ฐ›์€ StoreRequestDto๋ฅผ ๋ณ€ํ™˜ํ•˜์—ฌ Store ์—”ํ‹ฐํ‹ฐ๋กœ ์ƒ์„ฑํ•˜๊ณ , ์ €์žฅํ•œ ํ›„ DTO๋กœ ๋ฐ˜ํ™˜ + public StoreResponseDto createStore(StoreRequestDto dto) { + Store store = convertDtoToEntity(dto); + Store savedStore = storeRepository.save(store); + return StoreResponseDto.of(savedStore); + } + + // ํŠน์ • ๊ฐ€๊ฒŒ ์กฐํšŒ + public StoreResponseDto getStoreById(UUID storeId) { + Store store = storeRepository.findById(storeId) + .orElseThrow(StoreException.StoreNotFoundException::new); + return StoreResponseDto.of(store); + } + + // ์ „์ฒด ๊ฐ€๊ฒŒ ์กฐํšŒ(ํŽ˜์ด์ง€๋„ค์ด์…˜ ์ง€์›) - Pageable์„ ์‚ฌ์šฉํ•ด Store ์—”ํ‹ฐํ‹ฐ๋ฅผ ํŽ˜์ด์ง€ ๋‹จ์œ„๋กœ ์กฐํšŒํ•˜๊ณ , ๊ฐ Entity๋ฅผ DTO๋กœ ๋ณ€ํ™˜ํ•˜์—ฌ Page ๊ฐ์ฒด๋กœ ๋ฐ˜ํ™˜ + public Page<StoreResponseDto> getAllStores(Pageable pageable) { + return storeRepository.findAll(pageable) + .map(StoreResponseDto::of); + } + + // ๊ฐ€๊ฒŒ ์ˆ˜์ • - ํŠน์ • storeId์— ํ•ด๋‹นํ•˜๋Š” Entity๋ฅผ ์กฐํšŒํ•œ ํ›„, DTO์˜ ๊ฐ’์œผ๋กœ ์—…๋ฐ์ดํŠธํ•˜๊ณ  ์ €์žฅ + public StoreResponseDto updateStore(UUID storeId, StoreRequestDto dto) { + // storeId์— ํ•ด๋‹นํ•˜๋Š” ๊ฐ€๊ฒŒ๋ฅผ ์กฐํšŒ (์—†์œผ๋ฉด ์˜ˆ์™ธ ๋ฐœ์ƒ) + Store store = storeRepository.findById(storeId) + .orElseThrow(StoreException.StoreNotFoundException::new); + + // DTO์˜ state ๊ฐ’์„ ๋Œ€๋ฌธ์ž๋กœ ๋ณ€ํ™˜ํ•˜์—ฌ ENUM์œผ๋กœ ๋งคํ•‘, ์˜ค๋ฅ˜ ๋ฐœ์ƒ ์‹œ ๊ธฐ์กด ๊ฐ’์„ ์‚ฌ์šฉ + StoreState stateEnum; + try { + stateEnum = (dto.getState() != null) ? StoreState.valueOf(dto.getState().toUpperCase()) : store.getState(); + } catch(Exception e) { + stateEnum = store.getState(); + } + store.update( + dto.getName(), + stateEnum, + dto.getTellNumber(), + dto.getDescription(), + dto.getMinOrderPrice(), + dto.getDeliveryFee(), + store.getRating(), + store.getReviewCount(), + dto.getCategoryId() + ); + Store updatedStore = storeRepository.save(store); + return StoreResponseDto.of(updatedStore); + } + + // ์ฃผ์–ด์ง„ storeId๋กœ Entity๋ฅผ ์กฐํšŒํ•œ ํ›„, markDeleted()๋ฅผ ํ˜ธ์ถœํ•˜์—ฌ ์‚ญ์ œ๋œ ๊ฒƒ์ฒ˜๋Ÿผ ํ‘œ์‹œํ•˜๊ณ  ์ €์žฅ + @Transactional + public void deleteStore(UUID storeId) { + Store store = storeRepository.findById(storeId) + .orElseThrow(StoreException.StoreNotFoundException::new); + store.markDeleted(); + } + + // ๋ฆฌ๋ทฐ ์ง‘๊ณ„ ์—…๋ฐ์ดํŠธ ๋ฉ”์„œ๋“œ + @Transactional + public void updateStoreReview(UUID storeId) { + // 1. OrderClient๋ฅผ ์‚ฌ์šฉํ•˜์—ฌ ํ•ด๋‹น ๊ฐ€๊ฒŒ์˜ ์ฃผ๋ฌธ ๋ชฉ๋ก ์กฐํšŒ + List<OrderResponse> orders = orderClient.getOrders(storeId); + + // 2. ์ฃผ๋ฌธ ๋ชฉ๋ก์—์„œ ๊ฐ ์ฃผ๋ฌธ์˜ orderId ์ถ”์ถœ + List<UUID> orderIds = orders.stream() + .map(OrderResponse::getOrderId) + .collect(Collectors.toList()); + // 3. ReviewClient๋ฅผ ํ†ตํ•ด ํ•ด๋‹น orderId ๋ชฉ๋ก์— ํ•ด๋‹นํ•˜๋Š” ๋ฆฌ๋ทฐ ๋ฐ์ดํ„ฐ ์กฐํšŒ + List<ReviewResponse> reviews = reviewClient.getReviews(orderIds); + // 4. ์ด ๋ฆฌ๋ทฐ ๊ฐœ์ˆ˜์™€ ์ด ํ‰์  ํ•ฉ๊ณ„ ๊ณ„์‚ฐ + int reviewCount = reviews.size(); + float totalRating = (float) reviews.stream() + .mapToDouble(ReviewResponse::getTotalRating) + .sum(); + float avgRating = reviewCount > 0 ? totalRating / reviewCount : 0.0f; + // 5. ํ•ด๋‹น ๊ฐ€๊ฒŒ ์—”ํ‹ฐํ‹ฐ ์กฐํšŒ ๋ฐ ์—…๋ฐ์ดํŠธ + Store store = storeRepository.findById(storeId) + .orElseThrow(StoreException.StoreNotFoundException::new); + // ๊ธฐ์กด ํ•„๋“œ ์ค‘ ์ด๋ฆ„, state, ์ „ํ™”๋ฒˆํ˜ธ ๋“ฑ์€ ๊ทธ๋Œ€๋กœ ์œ ์ง€ํ•˜๊ณ , ํ‰์ ๊ณผ ๋ฆฌ๋ทฐ ์ˆ˜๋งŒ ์—…๋ฐ์ดํŠธ + store.update( + store.getName(), + store.getState(), + store.getTellNumber(), + store.getDescription(), + store.getMinOrderPrice(), + store.getDeliveryFee(), + avgRating, // ์™ธ๋ถ€์—์„œ ๋ฐ›์•„์˜จ ํ‰๊ท  ํ‰์  + reviewCount, // ์™ธ๋ถ€์—์„œ ๋ฐ›์•„์˜จ ์ด ๋ฆฌ๋ทฐ ์ˆ˜ + store.getCategoryId() + ); + } +}
Java
๋ฏผ์ˆ˜๋‹˜ ์—ฌ๊ธฐ๋„ .from ์ด ๋˜์–ด์•ผ ํ•  ๊ฒƒ ๊ฐ™๋„ค์š” ~!!
@@ -0,0 +1,152 @@ +package com.eureka.spartaonetoone.store.application; + +import com.eureka.spartaonetoone.common.client.OrderClient; +import com.eureka.spartaonetoone.common.client.ReviewClient; +import com.eureka.spartaonetoone.common.dtos.response.ReviewResponse; +import com.eureka.spartaonetoone.common.dtos.response.OrderResponse; +import com.eureka.spartaonetoone.store.application.exception.StoreException; +import com.eureka.spartaonetoone.store.domain.Store; +import com.eureka.spartaonetoone.store.domain.StoreState; +import com.eureka.spartaonetoone.store.domain.repository.StoreRepository; +import com.eureka.spartaonetoone.store.application.dtos.StoreRequestDto; +import com.eureka.spartaonetoone.store.application.dtos.StoreResponseDto; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.Pageable; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.validation.annotation.Validated; + +import java.util.List; +import java.util.UUID; +import java.util.stream.Collectors; + +@Service +@Validated +public class StoreService { + + private final StoreRepository storeRepository; + private final OrderClient orderClient; + private final ReviewClient reviewClient; + + // ์ƒ์„ฑ์ž ์ฃผ์ž… + public StoreService(StoreRepository storeRepository, OrderClient orderClient, ReviewClient reviewClient) { + this.storeRepository = storeRepository; + this.orderClient = orderClient; + this.reviewClient = reviewClient; + } + + // DTO -> ์—”ํ‹ฐํ‹ฐ ๋ณ€ํ™˜ ๋ฉ”์„œ๋“œ (Service ๋‚ด๋ถ€ ๋ณ€ํ™˜ ๋กœ์ง) - StoreRequestDto์˜ ๊ฐ’์„ ์ถ”์ถœํ•˜์—ฌ, Store ์—”ํ‹ฐํ‹ฐ๋ฅผ ์ƒ์„ฑํ•˜๋Š” ๋ฐ ์‚ฌ์šฉ + private Store convertDtoToEntity(StoreRequestDto dto) { + StoreState stateEnum; + try { + // DTO์˜ state ๋ฌธ์ž์—ด์„ ๋Œ€๋ฌธ์ž๋กœ ๋ณ€ํ™˜ ํ›„ ENUM์œผ๋กœ ๋ณ€ํ™˜. ์ž˜๋ชป๋œ ๊ฐ’์ด๋ฉด ๊ธฐ๋ณธ๊ฐ’ OPEN ์‚ฌ์šฉ. + stateEnum = dto.getState() != null ? StoreState.valueOf(dto.getState().toUpperCase()) : StoreState.OPEN; + } catch (IllegalArgumentException e) { + stateEnum = StoreState.OPEN; + } + // Service ๊ณ„์ธต์—์„œ ํ•„์š”ํ•œ ํ•„๋“œ๋งŒ ์ถ”์ถœํ•˜์—ฌ ์—”ํ‹ฐํ‹ฐ ์ƒ์„ฑ (์ˆœํ™˜์ฐธ์กฐ๋ฅผ ํ”ผํ•˜๊ธฐ ์œ„ํ•ด DTO์— ์ง์ ‘ ์˜์กดํ•˜์ง€ ์•Š์Œ) + return Store.createStore( + dto.getUserId(), + dto.getName(), + stateEnum, + dto.getTellNumber(), + dto.getDescription(), + dto.getMinOrderPrice() != null ? dto.getMinOrderPrice() : 0, + dto.getDeliveryFee() != null ? dto.getDeliveryFee() : 0, + dto.getRating() != null ? dto.getRating() : 0.0f, + dto.getReviewCount() != null ? dto.getReviewCount() : 0, + dto.getCategoryId() + ); + } + + // ๊ฐ€๊ฒŒ ๋“ฑ๋ก - ํด๋ผ์ด์–ธํŠธ๋กœ๋ถ€ํ„ฐ ์ „๋‹ฌ๋ฐ›์€ StoreRequestDto๋ฅผ ๋ณ€ํ™˜ํ•˜์—ฌ Store ์—”ํ‹ฐํ‹ฐ๋กœ ์ƒ์„ฑํ•˜๊ณ , ์ €์žฅํ•œ ํ›„ DTO๋กœ ๋ฐ˜ํ™˜ + public StoreResponseDto createStore(StoreRequestDto dto) { + Store store = convertDtoToEntity(dto); + Store savedStore = storeRepository.save(store); + return StoreResponseDto.of(savedStore); + } + + // ํŠน์ • ๊ฐ€๊ฒŒ ์กฐํšŒ + public StoreResponseDto getStoreById(UUID storeId) { + Store store = storeRepository.findById(storeId) + .orElseThrow(StoreException.StoreNotFoundException::new); + return StoreResponseDto.of(store); + } + + // ์ „์ฒด ๊ฐ€๊ฒŒ ์กฐํšŒ(ํŽ˜์ด์ง€๋„ค์ด์…˜ ์ง€์›) - Pageable์„ ์‚ฌ์šฉํ•ด Store ์—”ํ‹ฐํ‹ฐ๋ฅผ ํŽ˜์ด์ง€ ๋‹จ์œ„๋กœ ์กฐํšŒํ•˜๊ณ , ๊ฐ Entity๋ฅผ DTO๋กœ ๋ณ€ํ™˜ํ•˜์—ฌ Page ๊ฐ์ฒด๋กœ ๋ฐ˜ํ™˜ + public Page<StoreResponseDto> getAllStores(Pageable pageable) { + return storeRepository.findAll(pageable) + .map(StoreResponseDto::of); + } + + // ๊ฐ€๊ฒŒ ์ˆ˜์ • - ํŠน์ • storeId์— ํ•ด๋‹นํ•˜๋Š” Entity๋ฅผ ์กฐํšŒํ•œ ํ›„, DTO์˜ ๊ฐ’์œผ๋กœ ์—…๋ฐ์ดํŠธํ•˜๊ณ  ์ €์žฅ + public StoreResponseDto updateStore(UUID storeId, StoreRequestDto dto) { + // storeId์— ํ•ด๋‹นํ•˜๋Š” ๊ฐ€๊ฒŒ๋ฅผ ์กฐํšŒ (์—†์œผ๋ฉด ์˜ˆ์™ธ ๋ฐœ์ƒ) + Store store = storeRepository.findById(storeId) + .orElseThrow(StoreException.StoreNotFoundException::new); + + // DTO์˜ state ๊ฐ’์„ ๋Œ€๋ฌธ์ž๋กœ ๋ณ€ํ™˜ํ•˜์—ฌ ENUM์œผ๋กœ ๋งคํ•‘, ์˜ค๋ฅ˜ ๋ฐœ์ƒ ์‹œ ๊ธฐ์กด ๊ฐ’์„ ์‚ฌ์šฉ + StoreState stateEnum; + try { + stateEnum = (dto.getState() != null) ? StoreState.valueOf(dto.getState().toUpperCase()) : store.getState(); + } catch(Exception e) { + stateEnum = store.getState(); + } + store.update( + dto.getName(), + stateEnum, + dto.getTellNumber(), + dto.getDescription(), + dto.getMinOrderPrice(), + dto.getDeliveryFee(), + store.getRating(), + store.getReviewCount(), + dto.getCategoryId() + ); + Store updatedStore = storeRepository.save(store); + return StoreResponseDto.of(updatedStore); + } + + // ์ฃผ์–ด์ง„ storeId๋กœ Entity๋ฅผ ์กฐํšŒํ•œ ํ›„, markDeleted()๋ฅผ ํ˜ธ์ถœํ•˜์—ฌ ์‚ญ์ œ๋œ ๊ฒƒ์ฒ˜๋Ÿผ ํ‘œ์‹œํ•˜๊ณ  ์ €์žฅ + @Transactional + public void deleteStore(UUID storeId) { + Store store = storeRepository.findById(storeId) + .orElseThrow(StoreException.StoreNotFoundException::new); + store.markDeleted(); + } + + // ๋ฆฌ๋ทฐ ์ง‘๊ณ„ ์—…๋ฐ์ดํŠธ ๋ฉ”์„œ๋“œ + @Transactional + public void updateStoreReview(UUID storeId) { + // 1. OrderClient๋ฅผ ์‚ฌ์šฉํ•˜์—ฌ ํ•ด๋‹น ๊ฐ€๊ฒŒ์˜ ์ฃผ๋ฌธ ๋ชฉ๋ก ์กฐํšŒ + List<OrderResponse> orders = orderClient.getOrders(storeId); + + // 2. ์ฃผ๋ฌธ ๋ชฉ๋ก์—์„œ ๊ฐ ์ฃผ๋ฌธ์˜ orderId ์ถ”์ถœ + List<UUID> orderIds = orders.stream() + .map(OrderResponse::getOrderId) + .collect(Collectors.toList()); + // 3. ReviewClient๋ฅผ ํ†ตํ•ด ํ•ด๋‹น orderId ๋ชฉ๋ก์— ํ•ด๋‹นํ•˜๋Š” ๋ฆฌ๋ทฐ ๋ฐ์ดํ„ฐ ์กฐํšŒ + List<ReviewResponse> reviews = reviewClient.getReviews(orderIds); + // 4. ์ด ๋ฆฌ๋ทฐ ๊ฐœ์ˆ˜์™€ ์ด ํ‰์  ํ•ฉ๊ณ„ ๊ณ„์‚ฐ + int reviewCount = reviews.size(); + float totalRating = (float) reviews.stream() + .mapToDouble(ReviewResponse::getTotalRating) + .sum(); + float avgRating = reviewCount > 0 ? totalRating / reviewCount : 0.0f; + // 5. ํ•ด๋‹น ๊ฐ€๊ฒŒ ์—”ํ‹ฐํ‹ฐ ์กฐํšŒ ๋ฐ ์—…๋ฐ์ดํŠธ + Store store = storeRepository.findById(storeId) + .orElseThrow(StoreException.StoreNotFoundException::new); + // ๊ธฐ์กด ํ•„๋“œ ์ค‘ ์ด๋ฆ„, state, ์ „ํ™”๋ฒˆํ˜ธ ๋“ฑ์€ ๊ทธ๋Œ€๋กœ ์œ ์ง€ํ•˜๊ณ , ํ‰์ ๊ณผ ๋ฆฌ๋ทฐ ์ˆ˜๋งŒ ์—…๋ฐ์ดํŠธ + store.update( + store.getName(), + store.getState(), + store.getTellNumber(), + store.getDescription(), + store.getMinOrderPrice(), + store.getDeliveryFee(), + avgRating, // ์™ธ๋ถ€์—์„œ ๋ฐ›์•„์˜จ ํ‰๊ท  ํ‰์  + reviewCount, // ์™ธ๋ถ€์—์„œ ๋ฐ›์•„์˜จ ์ด ๋ฆฌ๋ทฐ ์ˆ˜ + store.getCategoryId() + ); + } +}
Java
๋ฏผ์ˆ˜๋‹˜ createStore ์•„๋ž˜ ์ฒ˜๋Ÿผ ๋ฐ”๊ฟ”๋ณด์‹œ์ฃ  ใ…Žใ…Ž ``` public StoreResponseDto createStore(StoreRequestDto dto) { StoreState stateEnum = parseStoreState(dto.getState()); Store store = Store.createStore( dto.getUserId(), dto.getName(), stateEnum, dto.getTellNumber(), dto.getDescription(), dto.getMinOrderPrice() != null ? dto.getMinOrderPrice() : 0, dto.getDeliveryFee() != null ? dto.getDeliveryFee() : 0, dto.getRating() != null ? dto.getRating() : 0.0f, dto.getReviewCount() != null ? dto.getReviewCount() : 0, dto.getCategoryId() ); Store savedStore = storeRepository.save(store); return StoreResponseDto.from(savedStore); } private StoreState parseStoreState(String state) { try { return state != null ? StoreState.valueOf(state.toUpperCase()) : StoreState.OPEN; } catch (IllegalArgumentException e) { return StoreState.OPEN; } } ```
@@ -0,0 +1,57 @@ +import java.util.ArrayList; +import java.util.HashSet; +import java.util.List; +import java.util.Set; + +public class Lotto { + private final static int LOTTO_NUM_SIZE = 6; + private final List<LottoNo> lottoNums; + + public Lotto(List<LottoNo> lottoNums) { + checkSizeValid(lottoNums); + checkNumbersValid(lottoNums); + checkDuplicated(lottoNums); + + this.lottoNums = lottoNums; + } + + public List<Integer> getNums() { + List<Integer> lottoNumbers = new ArrayList<>(); + + for (LottoNo lottoNo : lottoNums) { + lottoNumbers.add(lottoNo.getLottoNumber()); + } + + return lottoNumbers; + } + + public List<LottoNo> getLottoNums() { + return lottoNums; + } + + public void checkSizeValid(List<LottoNo> lotto) { + if (!isValidLottoSize(lotto)) { + throw new IllegalArgumentException("6๊ฐœ์˜ ๋กœ๋˜ ๋ฒˆํ˜ธ๋ฅผ ์ž…๋ ฅํ•ด ์ฃผ์„ธ์š”."); + } + } + + public void checkNumbersValid(List<LottoNo> lotto) { + if (lotto.contains(LottoNo.INVALID_LOTTO_NO)) { + throw new IllegalArgumentException("1 ~ 45 ์•ˆ์˜ ์ •์ˆ˜๋ฅผ ์ž…๋ ฅํ•˜์„ธ์š”."); + } + } + + public void checkDuplicated(List<LottoNo> lotto) { + if (!isValidLottoSize(new HashSet<>(lotto))) { + throw new IllegalArgumentException("๋กœ๋˜ ๋ฒˆํ˜ธ๋Š” ์ค‘๋ณต๋  ์ˆ˜ ์—†์Šต๋‹ˆ๋‹ค."); + } + } + + boolean isValidLottoSize(List<LottoNo> lotto) { + return lotto.size() == LOTTO_NUM_SIZE; + } + + boolean isValidLottoSize(Set<LottoNo> lotto) { + return lotto.size() == LOTTO_NUM_SIZE; + } +}
Java
final ๋กœ ์„ ์–ธํ•˜์‹  ์ด์œ ๊ฐ€ ๊ถ๊ธˆํ•ฉ๋‹ˆ๋‹ค~
@@ -0,0 +1,57 @@ +import java.util.ArrayList; +import java.util.HashSet; +import java.util.List; +import java.util.Set; + +public class Lotto { + private final static int LOTTO_NUM_SIZE = 6; + private final List<LottoNo> lottoNums; + + public Lotto(List<LottoNo> lottoNums) { + checkSizeValid(lottoNums); + checkNumbersValid(lottoNums); + checkDuplicated(lottoNums); + + this.lottoNums = lottoNums; + } + + public List<Integer> getNums() { + List<Integer> lottoNumbers = new ArrayList<>(); + + for (LottoNo lottoNo : lottoNums) { + lottoNumbers.add(lottoNo.getLottoNumber()); + } + + return lottoNumbers; + } + + public List<LottoNo> getLottoNums() { + return lottoNums; + } + + public void checkSizeValid(List<LottoNo> lotto) { + if (!isValidLottoSize(lotto)) { + throw new IllegalArgumentException("6๊ฐœ์˜ ๋กœ๋˜ ๋ฒˆํ˜ธ๋ฅผ ์ž…๋ ฅํ•ด ์ฃผ์„ธ์š”."); + } + } + + public void checkNumbersValid(List<LottoNo> lotto) { + if (lotto.contains(LottoNo.INVALID_LOTTO_NO)) { + throw new IllegalArgumentException("1 ~ 45 ์•ˆ์˜ ์ •์ˆ˜๋ฅผ ์ž…๋ ฅํ•˜์„ธ์š”."); + } + } + + public void checkDuplicated(List<LottoNo> lotto) { + if (!isValidLottoSize(new HashSet<>(lotto))) { + throw new IllegalArgumentException("๋กœ๋˜ ๋ฒˆํ˜ธ๋Š” ์ค‘๋ณต๋  ์ˆ˜ ์—†์Šต๋‹ˆ๋‹ค."); + } + } + + boolean isValidLottoSize(List<LottoNo> lotto) { + return lotto.size() == LOTTO_NUM_SIZE; + } + + boolean isValidLottoSize(Set<LottoNo> lotto) { + return lotto.size() == LOTTO_NUM_SIZE; + } +}
Java
check ๋ฉ”์„œ๋“œ๋“ค์ด public ์ธ ์ด์œ ๊ฐ€ ์žˆ๋‚˜์š”~?
@@ -0,0 +1,57 @@ +import java.util.ArrayList; +import java.util.HashSet; +import java.util.List; +import java.util.Set; + +public class Lotto { + private final static int LOTTO_NUM_SIZE = 6; + private final List<LottoNo> lottoNums; + + public Lotto(List<LottoNo> lottoNums) { + checkSizeValid(lottoNums); + checkNumbersValid(lottoNums); + checkDuplicated(lottoNums); + + this.lottoNums = lottoNums; + } + + public List<Integer> getNums() { + List<Integer> lottoNumbers = new ArrayList<>(); + + for (LottoNo lottoNo : lottoNums) { + lottoNumbers.add(lottoNo.getLottoNumber()); + } + + return lottoNumbers; + } + + public List<LottoNo> getLottoNums() { + return lottoNums; + } + + public void checkSizeValid(List<LottoNo> lotto) { + if (!isValidLottoSize(lotto)) { + throw new IllegalArgumentException("6๊ฐœ์˜ ๋กœ๋˜ ๋ฒˆํ˜ธ๋ฅผ ์ž…๋ ฅํ•ด ์ฃผ์„ธ์š”."); + } + } + + public void checkNumbersValid(List<LottoNo> lotto) { + if (lotto.contains(LottoNo.INVALID_LOTTO_NO)) { + throw new IllegalArgumentException("1 ~ 45 ์•ˆ์˜ ์ •์ˆ˜๋ฅผ ์ž…๋ ฅํ•˜์„ธ์š”."); + } + } + + public void checkDuplicated(List<LottoNo> lotto) { + if (!isValidLottoSize(new HashSet<>(lotto))) { + throw new IllegalArgumentException("๋กœ๋˜ ๋ฒˆํ˜ธ๋Š” ์ค‘๋ณต๋  ์ˆ˜ ์—†์Šต๋‹ˆ๋‹ค."); + } + } + + boolean isValidLottoSize(List<LottoNo> lotto) { + return lotto.size() == LOTTO_NUM_SIZE; + } + + boolean isValidLottoSize(Set<LottoNo> lotto) { + return lotto.size() == LOTTO_NUM_SIZE; + } +}
Java
java 8 ์˜ stream map ์„ ์จ๋ณด๋ฉด ์–ด๋–จ๊นŒ์š”?
@@ -0,0 +1,57 @@ +import java.util.ArrayList; +import java.util.HashSet; +import java.util.List; +import java.util.Set; + +public class Lotto { + private final static int LOTTO_NUM_SIZE = 6; + private final List<LottoNo> lottoNums; + + public Lotto(List<LottoNo> lottoNums) { + checkSizeValid(lottoNums); + checkNumbersValid(lottoNums); + checkDuplicated(lottoNums); + + this.lottoNums = lottoNums; + } + + public List<Integer> getNums() { + List<Integer> lottoNumbers = new ArrayList<>(); + + for (LottoNo lottoNo : lottoNums) { + lottoNumbers.add(lottoNo.getLottoNumber()); + } + + return lottoNumbers; + } + + public List<LottoNo> getLottoNums() { + return lottoNums; + } + + public void checkSizeValid(List<LottoNo> lotto) { + if (!isValidLottoSize(lotto)) { + throw new IllegalArgumentException("6๊ฐœ์˜ ๋กœ๋˜ ๋ฒˆํ˜ธ๋ฅผ ์ž…๋ ฅํ•ด ์ฃผ์„ธ์š”."); + } + } + + public void checkNumbersValid(List<LottoNo> lotto) { + if (lotto.contains(LottoNo.INVALID_LOTTO_NO)) { + throw new IllegalArgumentException("1 ~ 45 ์•ˆ์˜ ์ •์ˆ˜๋ฅผ ์ž…๋ ฅํ•˜์„ธ์š”."); + } + } + + public void checkDuplicated(List<LottoNo> lotto) { + if (!isValidLottoSize(new HashSet<>(lotto))) { + throw new IllegalArgumentException("๋กœ๋˜ ๋ฒˆํ˜ธ๋Š” ์ค‘๋ณต๋  ์ˆ˜ ์—†์Šต๋‹ˆ๋‹ค."); + } + } + + boolean isValidLottoSize(List<LottoNo> lotto) { + return lotto.size() == LOTTO_NUM_SIZE; + } + + boolean isValidLottoSize(Set<LottoNo> lotto) { + return lotto.size() == LOTTO_NUM_SIZE; + } +}
Java
์ ‘๊ทผ์ œ์–ด์ž๋ฅผ package-private ์œผ๋กœ ํ•˜์‹  ์ด์œ ๊ฐ€ ์žˆ์„๊นŒ์š”?
@@ -0,0 +1,57 @@ +import java.util.ArrayList; +import java.util.HashSet; +import java.util.List; +import java.util.Set; + +public class Lotto { + private final static int LOTTO_NUM_SIZE = 6; + private final List<LottoNo> lottoNums; + + public Lotto(List<LottoNo> lottoNums) { + checkSizeValid(lottoNums); + checkNumbersValid(lottoNums); + checkDuplicated(lottoNums); + + this.lottoNums = lottoNums; + } + + public List<Integer> getNums() { + List<Integer> lottoNumbers = new ArrayList<>(); + + for (LottoNo lottoNo : lottoNums) { + lottoNumbers.add(lottoNo.getLottoNumber()); + } + + return lottoNumbers; + } + + public List<LottoNo> getLottoNums() { + return lottoNums; + } + + public void checkSizeValid(List<LottoNo> lotto) { + if (!isValidLottoSize(lotto)) { + throw new IllegalArgumentException("6๊ฐœ์˜ ๋กœ๋˜ ๋ฒˆํ˜ธ๋ฅผ ์ž…๋ ฅํ•ด ์ฃผ์„ธ์š”."); + } + } + + public void checkNumbersValid(List<LottoNo> lotto) { + if (lotto.contains(LottoNo.INVALID_LOTTO_NO)) { + throw new IllegalArgumentException("1 ~ 45 ์•ˆ์˜ ์ •์ˆ˜๋ฅผ ์ž…๋ ฅํ•˜์„ธ์š”."); + } + } + + public void checkDuplicated(List<LottoNo> lotto) { + if (!isValidLottoSize(new HashSet<>(lotto))) { + throw new IllegalArgumentException("๋กœ๋˜ ๋ฒˆํ˜ธ๋Š” ์ค‘๋ณต๋  ์ˆ˜ ์—†์Šต๋‹ˆ๋‹ค."); + } + } + + boolean isValidLottoSize(List<LottoNo> lotto) { + return lotto.size() == LOTTO_NUM_SIZE; + } + + boolean isValidLottoSize(Set<LottoNo> lotto) { + return lotto.size() == LOTTO_NUM_SIZE; + } +}
Java
Set<LottoNo> ๋กœ ์„ ์–ธํ•˜๋Š” ๊ฒƒ์€ ์–ด๋–ป๊ฒŒ ์ƒ๊ฐํ•˜์‹œ๋‚˜์š”~
@@ -0,0 +1,46 @@ +import java.util.Objects; + +public class LottoNo implements Comparable<LottoNo> { + private final static int INVALID_NUM = 0; + public final static LottoNo INVALID_LOTTO_NO = new LottoNo(INVALID_NUM); + + private int lottoNumber; + + public LottoNo(int lottoNumber) { + try { + this.lottoNumber = validateLottoNo(lottoNumber); + } catch (IllegalArgumentException e) { + this.lottoNumber = INVALID_NUM; + } + } + + public int getLottoNumber() { + return lottoNumber; + } + + private int validateLottoNo(int lottoNumber) { + if (lottoNumber < 1 || lottoNumber > 45) { + throw new IllegalArgumentException(); + } + + return lottoNumber; + } + + @Override + public int hashCode() { + return Objects.hashCode(lottoNumber); + } + + @Override + public boolean equals(Object obj) { + if (lottoNumber == ((LottoNo)obj).lottoNumber) + return true; + + return false; + } + + @Override + public int compareTo(LottoNo o) { + return lottoNumber - o.lottoNumber; + } +}
Java
LottoNo ๋Š” ๋ณ€๊ฒฝ๋˜์ง€ ์•Š๋Š” lottoNumber ํ•˜๋‚˜๋ฅผ ๊ฐ€์ง€๊ณ  ์žˆ์–ด์•ผํ•˜๋ฏ€๋กœ final ํ‚ค์›Œ๋“œ๋ฅผ ๋„ฃ์–ด๋„ ๋  ๊ฒƒ ๊ฐ™๋„ค์š” ใ…Žใ…Ž
@@ -0,0 +1,46 @@ +import java.util.Objects; + +public class LottoNo implements Comparable<LottoNo> { + private final static int INVALID_NUM = 0; + public final static LottoNo INVALID_LOTTO_NO = new LottoNo(INVALID_NUM); + + private int lottoNumber; + + public LottoNo(int lottoNumber) { + try { + this.lottoNumber = validateLottoNo(lottoNumber); + } catch (IllegalArgumentException e) { + this.lottoNumber = INVALID_NUM; + } + } + + public int getLottoNumber() { + return lottoNumber; + } + + private int validateLottoNo(int lottoNumber) { + if (lottoNumber < 1 || lottoNumber > 45) { + throw new IllegalArgumentException(); + } + + return lottoNumber; + } + + @Override + public int hashCode() { + return Objects.hashCode(lottoNumber); + } + + @Override + public boolean equals(Object obj) { + if (lottoNumber == ((LottoNo)obj).lottoNumber) + return true; + + return false; + } + + @Override + public int compareTo(LottoNo o) { + return lottoNumber - o.lottoNumber; + } +}
Java
์Œ.. RuntimeException ์„ ๋ฐœ์ƒ์‹œํ‚ค๊ณ  catch ๋ฅผ ๊ตณ์ด ํ•˜๋Š” ์ด์œ ๊ฐ€ ์žˆ์„๊นŒ์š”? checkedException ๊ณผ uncheckedException ์— ๋Œ€ํ•ด์„œ ๊ณต๋ถ€ํ•ด๋ณด์‹œ๋ฉด ์ข‹์„ ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค~
@@ -0,0 +1,46 @@ +import java.util.Objects; + +public class LottoNo implements Comparable<LottoNo> { + private final static int INVALID_NUM = 0; + public final static LottoNo INVALID_LOTTO_NO = new LottoNo(INVALID_NUM); + + private int lottoNumber; + + public LottoNo(int lottoNumber) { + try { + this.lottoNumber = validateLottoNo(lottoNumber); + } catch (IllegalArgumentException e) { + this.lottoNumber = INVALID_NUM; + } + } + + public int getLottoNumber() { + return lottoNumber; + } + + private int validateLottoNo(int lottoNumber) { + if (lottoNumber < 1 || lottoNumber > 45) { + throw new IllegalArgumentException(); + } + + return lottoNumber; + } + + @Override + public int hashCode() { + return Objects.hashCode(lottoNumber); + } + + @Override + public boolean equals(Object obj) { + if (lottoNumber == ((LottoNo)obj).lottoNumber) + return true; + + return false; + } + + @Override + public int compareTo(LottoNo o) { + return lottoNumber - o.lottoNumber; + } +}
Java
๊ตณ์ด ๋ฉ”์„œ๋“œ๋กœ ๋นผ์ง€ ์•Š์•„๋„ ๋  ๊ฒƒ ๊ฐ™์•„์š”
@@ -0,0 +1,40 @@ +import java.util.ArrayList; +import java.util.List; + +public class LottoRankResult { + private List<Rank> ranks; + + public LottoRankResult(WinningLotto winningLotto, LottoTicket lottoTicket) { + this.ranks = new ArrayList<>(); + + for (Lotto lotto : lottoTicket.getAllLottoGames()) { + ranks.add( + Rank.valueOf( + winningLotto.getCountOfSameNumber(lotto), + winningLotto.isWinningBonus(lotto) + ) + ); + } + } + + public int getCount(Rank rank) { + return (int) ranks.stream().filter(t -> t.equals(rank)).count(); + } + + public Money getTotalWinningMoney() { + Money earnings = Money.ZERO; + + for (Rank rank : ranks) { + earnings = earnings.add(rank.getWinningMoney()); + } + + return earnings; + } + + public double getEarningsRate(Money invest) { + Money earnings = getTotalWinningMoney(); + + return (double)(earnings.intValue()) / invest.intValue() * 100.0; + } + +} \ No newline at end of file
Java
๋ญ”๊ฐ€ ์ด๋ฆ„์ด ๊ฒฐ๊ณผ๋ฅผ ๋‹ด๋Š” ๋ฐ์ดํ„ฐ ๊ทธ๋ฆ‡ ๊ฐ™์€ ๋А๋‚Œ์ด๋ผ LottoCalculator LottoResultCalculator LottoRankCalculator ๊ฐ™์€ ๋„ค์ด๋ฐ์œผ๋กœ ๋ณ€๊ฒฝํ•ด๋ณด๋ฉด ์–ด๋–จ๊นŒ์š”? ๊ทธ์— ๋งž์ถฐ์„œ ๋ฉ”์„œ๋“œ ๋„ค์ด๋ฐ๋„ ๋ณ€๊ฒฝํ•˜๋ฉด ๋‹จ์ˆœํžˆ set ๋œ ๋ฐ์ดํ„ฐ๋ฅผ get ํ•˜๋Š” ๊ฒƒ๋ณด๋‹ค ์ƒํƒœ์™€ ํ–‰์œ„๋ฅผ ๊ฐ–๋Š” ๊ฐ์ฒด์ง€ํ–ฅ์ ์ธ ๋„ค์ด๋ฐ์ด ๋  ๊ฒƒ ๊ฐ™๋‹ค๋Š” ์ƒ๊ฐ์ด ๋“ญ๋‹ˆ๋‹ค
@@ -0,0 +1,22 @@ +import java.util.ArrayList; +import java.util.List; + +public class Lottos { + private List<Lotto> lottos; + + public Lottos() { + this.lottos = new ArrayList<>(); + } + + public List<Lotto> getLottos() { + return lottos; + } + + public void addLotto(Lotto lotto) { + lottos.add(lotto); + } + + public int getSize() { + return lottos.size(); + } +}
Java
Lottos ๊ฐ€ ๊ฐ€์ง€๋Š” ํ–‰์œ„๊ฐ€ ํ•˜๋‚˜๋„ ์—†๋Š”๋ฐ์š”, ๋‹ค๋ฅธ ๊ฐ์ฒด์—์„œ ์œ„์ž„ํ• ๋งŒํ•œ๊ฒŒ ์—†์„๊นŒ์š”? get์ด ์‚ฌ์šฉ๋˜๊ณ  ์žˆ๋‹ค๋Š” ๊ฒƒ์€ Lottos ์˜ tell dont ask ์›์น™์ด ์•ˆ์ง€์ผœ์ง€๊ณ  ์žˆ๋‹ค๋Š” ๋œป์ด๊ณ , ์—ฌ๊ธฐ๋กœ ์œ„์ž„ํ• ๋งŒํ•œ ์ฑ…์ž„์ด ์‚ฐ์žฌํ•ด ์žˆ๋‹ค๋Š” ๋œป์ด๊ธฐ๋„ ํ•ฉ๋‹ˆ๋‹ค.
@@ -0,0 +1,29 @@ +import java.util.List; + +public class WinningLotto { + private Lotto winningLotto; + private LottoNo bonusNo; + + public WinningLotto(List<LottoNo> winningLottoNumbers, LottoNo lottoNo) { + if (winningLottoNumbers == null) { + throw new IllegalArgumentException("'lotto' must not be null"); + } + if (lottoNo == null) { + throw new IllegalArgumentException("'lottoNo' must not be null"); + } + + this.winningLotto = new Lotto(winningLottoNumbers); + this.bonusNo = lottoNo; + } + + public int getCountOfSameNumber(Lotto purchasedLotto) { + return (int) winningLotto.getLottoNums() + .stream() + .filter(purchasedLotto.getLottoNums()::contains) + .count(); + } + + public boolean isWinningBonus(Lotto purchasedLotto) { + return purchasedLotto.getLottoNums().contains(bonusNo); + } +}
Java
Lotto๋ฅผ ์ƒ์† ๋ฐ›์„ ์ˆ˜๋„ ์žˆ์—ˆ๋Š”๋ฐ ์ด๋ ‡๊ฒŒ ํ•ฉ์„ฑ์„ ์‚ฌ์šฉํ•˜์…จ๋„ค์š”. ๐Ÿ‘ ํ˜น์‹œ๋ผ๋„ ์šฐ์—ฐํžˆ ์ด๋ ‡๊ฒŒ ๊ตฌํ˜„ํ•˜์‹ ๊ฑฐ๋ผ๋ฉด, ์ƒ์†๊ณผ ํ•ฉ์„ฑ์„ ๊ตฌ๊ธ€๋ง ํ•ด๋ณด์‹œ๋ฉด ๊ด€๋ จ ์ž๋ฃŒ๋ฅผ ์ฐพ์œผ์‹ค ์ˆ˜ ์žˆ์„๊ฒ๋‹ˆ๋‹ค ~
@@ -0,0 +1,43 @@ +import java.util.Scanner; + +public class LottoApplication { + private static boolean APP_SUCCESS = false; + + public static void main(String[] args) { + runUntilAppSuccess(); + } + + public static void runUntilAppSuccess() { + while (!APP_SUCCESS) { + run(); + } + } + + public static void run() { + final Scanner scanner = new Scanner(System.in); + int countOfManualLotto; + + try { + LottoService lottoService = new LottoService( + InputView.scanMoney(scanner), + countOfManualLotto = InputView.scanCountOfManualLotto(scanner), + InputView.scanNumbersOfManualLotto(scanner, countOfManualLotto), + new LottoSeller() + ); + + lottoService.purchaseLottoTicket(); + lottoService.printPurchaseResult(); + + lottoService.setWinningLotto( + InputView.scanWinningLotto(scanner), + InputView.scanBonusNo(scanner) + ); + + lottoService.printWinningResult(); + + APP_SUCCESS = true; + } catch (OutOfConditionException | IllegalArgumentException e) { + e.printStackTrace(); + } + } +}
Java
LottoGame ์ด๋ผ๋Š” ๋„ค์ด๋ฐ์€ ์–ด๋–จ๊นŒ์š”
@@ -0,0 +1,43 @@ +import java.util.Scanner; + +public class LottoApplication { + private static boolean APP_SUCCESS = false; + + public static void main(String[] args) { + runUntilAppSuccess(); + } + + public static void runUntilAppSuccess() { + while (!APP_SUCCESS) { + run(); + } + } + + public static void run() { + final Scanner scanner = new Scanner(System.in); + int countOfManualLotto; + + try { + LottoService lottoService = new LottoService( + InputView.scanMoney(scanner), + countOfManualLotto = InputView.scanCountOfManualLotto(scanner), + InputView.scanNumbersOfManualLotto(scanner, countOfManualLotto), + new LottoSeller() + ); + + lottoService.purchaseLottoTicket(); + lottoService.printPurchaseResult(); + + lottoService.setWinningLotto( + InputView.scanWinningLotto(scanner), + InputView.scanBonusNo(scanner) + ); + + lottoService.printWinningResult(); + + APP_SUCCESS = true; + } catch (OutOfConditionException | IllegalArgumentException e) { + e.printStackTrace(); + } + } +}
Java
lottoService ์— set ํ•˜๊ณ  get ํ•˜๊ณ  ์ ˆ์ฐจ์ง€ํ–ฅ์ ์ธ ๋ฐฉ์‹์œผ๋กœ ์ฝ”๋“œ๊ฐ€ ์งœ์—ฌ์ ธ ์žˆ์Šต๋‹ˆ๋‹ค. ๋ชจ๋“  ๋กœ์ง์ด lottoService ๋ฅผ ํ†ตํ•˜๋ฉด์„œ ๊ฒฐ๊ตญ ์ด ํด๋ž˜์Šค๋Š” ์ ์  ๋น„๋Œ€ํ•ด์งˆํ…๋ฐ์š” ์ข‹์€ ๊ฐœ์„  ๋ฐฉ๋ฒ•์ด ์—†์„๊นŒ์š”~?
@@ -0,0 +1,48 @@ +import java.util.Arrays; + +public enum Rank { + FIRST(6, 2000000000), + SECOND(5, 30000000), + THIRD(5, 1500000), + FOURTH(4, 50000), + FIFTH(3, 5000), + MISS(0, 0); + + private int countOfMatch; + private Money winningMoney; + + Rank(int countOfMatch, int winningMoney) { + this.countOfMatch = countOfMatch; + this.winningMoney = Money.valueOf(winningMoney); + } + + public static Rank valueOf(int countOfGame, boolean matchBonus) { + if (countOfGame == SECOND.getCountOfMatch()) { + return getSecondOrThird(matchBonus); + } + + return Arrays.stream(values()) + .filter(r -> countOfGame == r.countOfMatch) + .findFirst() + .orElse(MISS); + } + + public static Rank[] valuesNotMiss() { + return new Rank[]{FIRST, SECOND, THIRD, FOURTH, FIFTH}; + } + + private static Rank getSecondOrThird(boolean matchBonus) { + if (matchBonus) + return SECOND; + return THIRD; + } + + public int getCountOfMatch() { + return countOfMatch; + } + + public Money getWinningMoney() { + return winningMoney; + } + +}
Java
์ค‘๊ด„ํ˜ธ๊ฐ€ ๋น ์กŒ์Šต๋‹ˆ๋‹ค
@@ -0,0 +1,21 @@ +public class RankResult { + private Rank rank; + private int countOfRank; + + RankResult(Rank rank) { + this.rank = rank; + this.countOfRank = 0; + } + + public Rank getRank() { + return rank; + } + + public int getCountOfRank() { + return countOfRank; + } + + public void countUp(int count) { + countOfRank += count; + } +}
Java
๋ฐ์ดํ„ฐ๋“ค์„ ํด๋ž˜์Šค๋กœ ๋ฌถ๋Š” ๊ฒƒ์ด ๊ฐ์ฒด์ง€ํ–ฅ์€ ์•„๋‹™๋‹ˆ๋‹ค~ RankResult ๋„ ๊ฒฐ๊ตญ ๋ฐ์ดํ„ฐ์™€ get ๋งŒ ๊ฐ€์ง€๊ณ  ์žˆ๊ณ , ์œ ์˜๋ฏธํ•œ ํ–‰์œ„๊ฐ€ ์—†์Šต๋‹ˆ๋‹ค ใ… ใ…  ๋ถˆํ•„์š”ํ•œ ๊ฐ์ฒด๊ฐ€ ์•„๋‹Œ์ง€, ์œ ์˜๋ฏธํ•œ ํ–‰์œ„๋ฅผ ๊ฐ€์ง„ ๊ฐ์ฒด๋กœ ๋งŒ๋“ค๋ ค๋ฉด ์–ด๋–ค ํ–‰์œ„๋ฅผ ๋ถ€์—ฌํ•ด์•ผํ•˜๋Š”์ง€ ๊ณ ๋ฏผํ•ด๋ณด์‹œ๋ฉด ์ข‹์„ ๊ฒƒ ๊ฐ™์•„์š”~
@@ -0,0 +1,50 @@ +import java.util.List; + +public class LottoSeller { + private LottoPurchaseService lottoPurchaseService; + private Money change; + + public LottoSeller() { + change = Money.ZERO; + lottoPurchaseService = new LottoPurchaseService(); + } + + public LottoTicket sellTicketTo(LottoUser lottoUser) throws OutOfConditionException { + Money investMoney = LottoPurchaseService + .validatePurchase( + lottoUser.getInvestMoney(), + lottoUser.getCountOfManualLotto() + ); + + this.change = LottoPurchaseService + .calculateChange(investMoney); + + return lottoPurchaseService + .createLottoTicket( + investMoney, + getCountOfAutoGame(investMoney, lottoUser.getCountOfManualLotto()), + changeToLottos(lottoUser.getNumbersOfManualLottos()) + ); + } + + public int getCountOfAutoGame(Money investMoney, int countOfManualLotto) { + return investMoney.divideBy(LottoPurchaseService.LOTTO_PRICE).intValue() + - countOfManualLotto; + } + + private Lottos changeToLottos(List<List<LottoNo>> numbers0fManualLottos) { + Lottos manualLottos = new Lottos(); + + for (List<LottoNo> lottoNums : numbers0fManualLottos) { + manualLottos.addLotto( + lottoPurchaseService.createManualLotto(lottoNums) + ); + } + + return manualLottos; + } + + public Money getChange() { + return change; + } +}
Java
Service ๋ผ๋Š” ๋„ค์ด๋ฐ์„ ์“ฐ์‹œ๋Š”๊ฑธ๋กœ ๋ด์„œ ์›น ์ชฝ ์ž๋ฃŒ๋ฅผ ๋ณด์‹  ๊ฒƒ ๊ฐ™์€๋ฐ, controller, service, repository ์ด๋Ÿฐ layered architecture ๋Š” ์ง€๊ธˆ ์ €ํฌ๊ฐ€ ํ•˜๊ณ  ์žˆ๋Š” ๊ฐ์ฒด์ง€ํ–ฅ๊ณผ ๊ฑฐ๋ฆฌ๊ฐ€ ์ข€ ์žˆ์Šต๋‹ˆ๋‹ค ~ service ๋ผ๋Š” ๋„ค์ด๋ฐ์„ ์‚ฌ์šฉํ•˜๊ธฐ๋ณด๋‹ค๋Š” ์ข€ ๋” ๊ตฌ์ฒด์ ์ด๊ณ  ๋ˆ„๊ตฌ๋‚˜ ๊ธ€ ์ฝ๋“ฏ์ด ๋ณผ ์ˆ˜ ์žˆ๋Š” ๋„ค์ด๋ฐ์„ ํ•˜์‹œ๋ฉด ํ•ด๋‹น ๊ฐ์ฒด์— ๋ถ€์—ฌํ•˜๋Š” ์ฑ…์ž„๊ณผ ํ–‰์œ„๋“ค๋„ ๋‹ฌ๋ผ์ง€๊ฒŒ ๋ฉ๋‹ˆ๋‹ค ~ ๋„ค์ด๋ฐ์€ ๋‹จ์ˆœํžˆ ์‹œ๊ฐ์ ์ธ ํšจ๊ณผ ๊ทธ ์ด์ƒ์˜ ๊ฐ€์น˜๋ฅผ ๊ฐ€์ง€๊ณ  ์žˆ์Šต๋‹ˆ๋‹ค
@@ -0,0 +1,50 @@ +import java.util.List; + +public class LottoSeller { + private LottoPurchaseService lottoPurchaseService; + private Money change; + + public LottoSeller() { + change = Money.ZERO; + lottoPurchaseService = new LottoPurchaseService(); + } + + public LottoTicket sellTicketTo(LottoUser lottoUser) throws OutOfConditionException { + Money investMoney = LottoPurchaseService + .validatePurchase( + lottoUser.getInvestMoney(), + lottoUser.getCountOfManualLotto() + ); + + this.change = LottoPurchaseService + .calculateChange(investMoney); + + return lottoPurchaseService + .createLottoTicket( + investMoney, + getCountOfAutoGame(investMoney, lottoUser.getCountOfManualLotto()), + changeToLottos(lottoUser.getNumbersOfManualLottos()) + ); + } + + public int getCountOfAutoGame(Money investMoney, int countOfManualLotto) { + return investMoney.divideBy(LottoPurchaseService.LOTTO_PRICE).intValue() + - countOfManualLotto; + } + + private Lottos changeToLottos(List<List<LottoNo>> numbers0fManualLottos) { + Lottos manualLottos = new Lottos(); + + for (List<LottoNo> lottoNums : numbers0fManualLottos) { + manualLottos.addLotto( + lottoPurchaseService.createManualLotto(lottoNums) + ); + } + + return manualLottos; + } + + public Money getChange() { + return change; + } +}
Java
์  ํ•˜๋‚˜ ์ฐ์„ ๋•Œ๋Š” ์ค„๋ฐ”๊ฟˆ์„ ์•ˆํ•˜์‹œ๋Š”๊ฒŒ ์ผ๋ฐ˜์ ์ž…๋‹ˆ๋‹ค. ๋ฉ”์†Œ๋“œ ํŒŒ๋ผ๋ฏธํ„ฐ๋„ 3๊ฐœ ์ด์ƒ๋ถ€ํ„ฐ ์—”ํ„ฐ๋ฅผ ์น˜์‹œ๋Š”๊ฒŒ ์–ด๋–จ๊นŒ์š”?
@@ -0,0 +1,42 @@ +import java.util.List; + +public class LottoService { + LottoUser lottoUser; + LottoSeller lottoSeller; + LottoTicket purchasedLottoTicket = null; + WinningLotto winningLotto = null; + PurchaseResultView purchaseResultView = null; + WinningResultView winningResultView = null; + + public LottoService(Money investMoney, int countOfManualLotto, List<List<LottoNo>> numbersOfManualLotto, + LottoSeller lottoSeller) { + this.lottoUser = new LottoUser(investMoney, countOfManualLotto, numbersOfManualLotto); + this.lottoSeller = lottoSeller; + } + + public LottoTicket purchaseLottoTicket() throws OutOfConditionException { + purchasedLottoTicket = lottoSeller.sellTicketTo(lottoUser); + lottoUser.setLottoTicket(purchasedLottoTicket); + + return purchasedLottoTicket; + } + + public void printPurchaseResult() { + purchaseResultView = new PurchaseResultView(); + + purchaseResultView.notifyIfChangeLeft(lottoSeller); + purchaseResultView.printPurchasedTicket(lottoUser); + } + + public void setWinningLotto(List<LottoNo> winningLottoNumbers, LottoNo bonusNo) { + winningLotto = new WinningLotto(winningLottoNumbers, bonusNo); + } + + public void printWinningResult() { + winningResultView = new WinningResultView(); + + winningResultView.printWinningResult(winningLotto, purchasedLottoTicket); + winningResultView.printEarningsRate(winningLotto, purchasedLottoTicket); + } + +}
Java
set์„ ์‚ฌ์šฉํ•˜์ง€ ์•Š๋Š”๋‹ค๋Š” ๊ฐ์ฒด์ง€ํ–ฅ ์ƒํ™œ์ฒด์กฐ ๊ทœ์น™์„ ์ ์šฉํ•ด๋ณด์‹œ๋ฉด ์ฝ”๋“œ์˜ ์„ค๊ณ„๊ฐ€ ๋‹ฌ๋ผ์งˆ ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค
@@ -0,0 +1,43 @@ +import java.util.ArrayList; +import java.util.List; + +public class LottoTicket { + private Money ticketPrice; + private Lottos autoLottos; + private Lottos manualLottos; + + public LottoTicket(Money ticketPrice, Lottos autoLottos, Lottos manualLottos) { + this.ticketPrice = ticketPrice; + this.autoLottos = autoLottos; + this.manualLottos = manualLottos; + } + + public List<Lotto> getAllLottoGames() { + List<Lotto> lottos = new ArrayList<>(); + + lottos.addAll(getManualLottos()); + lottos.addAll(getAutoLottos()); + + return lottos; + } + + public List<Lotto> getAutoLottos() { + return autoLottos.getLottos(); + } + + public List<Lotto> getManualLottos() { + return manualLottos.getLottos(); + } + + public int getCountOfAutoLotto() { + return autoLottos.getSize(); + } + + public int getCountOfManualLotto() { + return manualLottos.getSize(); + } + + public Money getTicketPrice() { + return ticketPrice; + } +}
Java
์—ฌ๊ธฐ๋„ ํ–‰์œ„๊ฐ€ ์—†๊ณ  ๋ฐ์ดํ„ฐ + getter ๋ฟ์ด๋„ค์š”. ๊ทธ๋Ÿฐ๋ฐ ์ด๋ ‡๊ฒŒ ํด๋ž˜์Šค๋ฅผ ๋‚˜๋ˆ ๋ณด๋ ค๊ณ  ์ตœ๋Œ€ํ•œ ์‹œ๋„ํ•˜์‹  ์  ๐Ÿ‘
@@ -0,0 +1,35 @@ +import java.util.List; + +public class LottoUser { + private Money investMoney; + private int countOfManualLotto; + private List<List<LottoNo>> numbersOfManualLottos; + + private LottoTicket lottoTicket; + + public LottoUser(Money investMoney, int countOfManualLotto, List<List<LottoNo>> numbersOfManualLottos) { + this.investMoney = investMoney; + this.countOfManualLotto = countOfManualLotto; + this.numbersOfManualLottos = numbersOfManualLottos; + } + + public void setLottoTicket(LottoTicket lottoTicket) { + this.lottoTicket = lottoTicket; + } + + public LottoTicket getLottoTicket() { + return lottoTicket; + } + + public int getCountOfManualLotto() { + return countOfManualLotto; + } + + public List<List<LottoNo>> getNumbersOfManualLottos() { + return numbersOfManualLottos; + } + + public Money getInvestMoney() { + return investMoney; + } +}
Java
์—ฌ๊ธฐ๋„ setter getter ๋ฟ ์ด๋„ค์š” ใ… 
@@ -0,0 +1,65 @@ +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +public final class LottoPurchaseService { + public final static Money LOTTO_PRICE = Money.valueOf(1000); + + public static Money validatePurchase(Money inputMoney, int countOfManualLotto) throws OutOfConditionException { + if (inputMoney.intValue() < LOTTO_PRICE.intValue()) { + throw new OutOfConditionException(LOTTO_PRICE + "์› ์ด์ƒ์ด ํ•„์š”ํ•ฉ๋‹ˆ๋‹ค."); + } + + if (countOfManualLotto * LOTTO_PRICE.intValue() > inputMoney.intValue()) { + throw new IllegalArgumentException("๊ธˆ์•ก์ด ์ž‘์•„ ์›ํ•˜๋Š” ๋งŒํผ ์ˆ˜๋™ ๋กœ๋˜๋ฅผ ์‚ด ์ˆ˜ ์—†์Šต๋‹ˆ๋‹ค."); + } + + return inputMoney; + } + + public static Money calculateChange(Money inputMoney) { + return Money.valueOf(inputMoney.intValue() % LOTTO_PRICE.intValue()); + } + + public Lotto createManualLotto(List<LottoNo> lottoNums) { + Collections.sort(lottoNums); + return new Lotto(lottoNums); + } + + public Lotto createAutoLotto() { + List<LottoNo> auto = new ArrayList<>(shuffleAllLottoNo().subList(0, 6)); + Collections.sort(auto); + + return new Lotto(auto); + } + + public Lottos createAutoLottos(int countOfAutoLotto) { + Lottos autoLottos = new Lottos(); + + for (int i = 0; i < countOfAutoLotto; i++) { + autoLottos.addLotto( + createAutoLotto() + ); + } + + return autoLottos; + } + + public LottoTicket createLottoTicket(Money ticketPrice, int countOfAutoLotto, Lottos manualLottos) { + return new LottoTicket( + ticketPrice, + createAutoLottos(countOfAutoLotto), + manualLottos); + } + + private List<LottoNo> shuffleAllLottoNo() { + List<LottoNo> lottoNums = new ArrayList<>(); + + for (int i = 1; i <= 45; i++) { + lottoNums.add(new LottoNo(i)); + } + Collections.shuffle(lottoNums); + + return lottoNums; + } +}
Java
๋ฐ์ดํ„ฐ์™€ ํ”„๋กœ์„ธ์Šค๊ฐ€ ๋”ฐ๋กœ ์žˆ๋Š” ๊ฒƒ == ์ ˆ์ฐจ์ง€ํ–ฅ ํ”„๋กœ๊ทธ๋ž˜๋ฐ ํ˜„ ์ƒํ™ฉ : ๋ฐ์ดํ„ฐ = LottoSeller, Ticket, User ๋“ฑ (๋ฐ์ดํ„ฐ + getter) ํ”„๋กœ์„ธ์Šค = Service (๋ฐ์ดํ„ฐ get ํ•ด์„œ ๋กœ์ง ์ฒ˜๋ฆฌ) ๋‹ต : MVC์™€ layered architecture๋ฅผ ์žŠ๊ณ  view ์™€ ๋น„์ฆˆ๋‹ˆ์Šค ๋กœ์ง์„ ๋ถ„๋ฆฌํ•˜๋Š” ๊ฒƒ๋งŒ ๊ธฐ์–ตํ•˜๊ณ  ์งœ๋ณด๊ธฐ
@@ -0,0 +1,65 @@ +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.Scanner; +import java.util.stream.Collectors; + +public final class InputView { + + public static Money scanMoney(Scanner scanner) { + System.out.println("\n๊ตฌ์ž…๊ธˆ์•ก์„ ์ž…๋ ฅํ•ด ์ฃผ์„ธ์š”."); + + return Money.valueOf(Integer.parseInt(scanner.nextLine())); + } + + public static int scanCountOfManualLotto(Scanner scanner) { + System.out.println("\n์ˆ˜๋™์œผ๋กœ ๊ตฌ๋งคํ•  ๋กœ๋˜ ์ˆ˜๋ฅผ ์ž…๋ ฅํ•ด ์ฃผ์„ธ์š”."); + + return Integer.parseInt(scanner.nextLine()); + } + + public static List<List<LottoNo>> scanNumbersOfManualLotto(Scanner scanner, int countOfManualGame) { + System.out.println("\n์ˆ˜๋™์œผ๋กœ ๊ตฌ๋งคํ•  ๋ฒˆํ˜ธ๋ฅผ ์ž…๋ ฅํ•ด ์ฃผ์„ธ์š”."); + + List<List<LottoNo>> manualLotto = new ArrayList<>(); + String input = scanner.nextLine(); + int count = countOfManualGame; + + while (!input.isEmpty() && count != 0) { + count--; + addScannedNumbers(manualLotto, input); + input = scanner.nextLine(); + } + + return manualLotto; + } + + private static void addScannedNumbers(List<List<LottoNo>> manualLotto, String input) { + manualLotto.add( + Arrays.asList(input.replaceAll(" ", "").split(",")) + .stream() + .map(Integer::parseInt) + .map(LottoNo::new) + .collect(Collectors.toList()) + ); + } + + public static List<LottoNo> scanWinningLotto(Scanner scanner) { + System.out.println("\n์ง€๋‚œ ์ฃผ ๋‹น์ฒจ ๋ฒˆํ˜ธ๋ฅผ ์ž…๋ ฅํ•ด ์ฃผ์„ธ์š”."); + + return Arrays.asList(scanner.nextLine() + .replaceAll(" ", "") + .split(",")) + .stream() + .map(Integer::parseInt) + .map(LottoNo::new) + .collect(Collectors.toList()); + } + + public static LottoNo scanBonusNo(Scanner scanner) { + System.out.println("๋ณด๋„ˆ์Šค ๋ณผ์„ ์ž…๋ ฅํ•ด ์ฃผ์„ธ์š”."); + + return new LottoNo(Integer.parseInt(scanner.nextLine())); + } + +}
Java
view ์—์„œ๋Š” ๋ฐ์ดํ„ฐ๋ฅผ scan ํ•ด์˜ค๋Š” ์ฑ…์ž„๋งŒ ์žˆ์Šต๋‹ˆ๋‹ค. ์ง€๊ธˆ์€ ๋ณ€ํ™˜ ๋กœ์ง๊นŒ์ง€ ์—ฌ๊ธฐ์„œ ์ฒ˜๋ฆฌํ•˜๊ณ  ์žˆ๋„ค์š”~!
@@ -0,0 +1,29 @@ +public final class PurchaseResultView { + public void notifyIfChangeLeft(LottoSeller seller) { + if (!seller.getChange().equals(Money.ZERO)) { + System.out.println("์ž”๋ˆ " + seller.getChange() + "์›์ด ๋‚จ์•˜์Šต๋‹ˆ๋‹ค."); + System.out.println(); + } + } + + public void printPurchasedTicket(LottoUser lottoUser) { + LottoTicket lottoTicket = lottoUser.getLottoTicket(); + + System.out.println( + "์ˆ˜๋™์œผ๋กœ " + lottoTicket.getCountOfManualLotto() + + "์žฅ, ์ž๋™์œผ๋กœ " + lottoTicket.getCountOfAutoLotto() + + "๊ฐœ๋ฅผ ๊ตฌ๋งคํ–ˆ์Šต๋‹ˆ๋‹ค." + ); + + for (Lotto manualGame : lottoTicket.getManualLottos()) { + System.out.println(manualGame.getNums()); + } + + for (Lotto autoGame : lottoTicket.getAutoLottos()) { + System.out.println(autoGame.getNums()); + } + + System.out.println(); + } + +}
Java
finall class ๋กœ ํ•˜์‹  ์ด์œ ๊ฐ€ ๊ถ๊ธˆํ•ฉ๋‹ˆ๋‹ค~
@@ -1 +1,23 @@ # spring-security +## ๐Ÿš€ 1-1๋‹จ๊ณ„ - OAuth 2.0 Login + +- [x] Github Application ๋“ฑ๋ก +- [x] ์ธ์ฆ URL ๋ฆฌ๋‹ค์ด๋ ‰ํŠธ ํ•„ํ„ฐ ๊ตฌํ˜„ +- [x] Github Access Token ํš๋“ +- [x] OAuth2 ์‚ฌ์šฉ์ž ์ •๋ณด ์กฐํšŒ +- [x] ํ›„์ฒ˜๋ฆฌ + - [x] ์ดํ›„ ํ”„๋กœํ•„ ์ •๋ณด๋ฅผ ๊ฐ€์ง€๊ณ  ํšŒ์› ๊ฐ€์ž… & ๋กœ๊ทธ์ธ์„ ๊ตฌํ˜„ํ•œ๋‹ค. + - [x] ๊ธฐ์กด ๋ฉค๋ฒ„ ์ •๋ณด๊ฐ€ ์žˆ๋Š” ๊ฒฝ์šฐ ์„ธ์…˜์— ๋กœ๊ทธ์ธ ์ •๋ณด๋ฅผ ์ €์žฅํ•œ ๋’ค "/"์œผ๋กœ ๋ฆฌ๋‹ค์ด๋ ‰ํŠธ + - [x] ์ƒˆ๋กœ์šด ๋ฉค๋ฒ„์ธ ๊ฒฝ์šฐ ํšŒ์› ๊ฐ€์ž… ํ›„ ์„ธ์…˜์— ๋กœ๊ทธ์ธ ์ •๋ณด๋ฅผ ์ €์žฅํ•œ ๋’ค "/"์œผ๋กœ ๋ฆฌ๋‹ค์ด๋ ‰ํŠธ + +## ๐Ÿš€ 1-2๋‹จ๊ณ„ - ๋ฆฌํŒฉํ„ฐ๋ง & OAuth 2.0 Resource ์—ฐ๋™ +- [x] Google ๊ณ„์ •์„ ์‚ฌ์šฉํ•œ ์ธ์ฆ, ์ธ๊ฐ€ +- [x] ๋ฆฌํŒฉํ„ฐ๋ง Google ์ธ์ฆ์„ ์ถ”๊ฐ€ํ•˜๋ฉด์„œ ๋ฐœ์ƒํ•œ ์ค‘๋ณต๋œ ์ฝ”๋“œ๋ฅผ ์ œ๊ฑฐํ•˜๊ณ , ์ฝ”๋“œ ๊ตฌ์กฐ๋ฅผ ๊ฐœ์„ ํ•œ๋‹ค. +- [x] Github๊ณผ Google ์ธ์ฆ ๋กœ์ง ๊ฐ„์˜ ์ค‘๋ณต๋œ ์ฝ”๋“œ๋ฅผ ์ œ๊ฑฐํ•˜๊ณ , ํ”„๋ ˆ์ž„์›Œํฌ์˜ ์ธ์ฆ ๋กœ์ง๊ณผ ์• ํ”Œ๋ฆฌ์ผ€์ด์…˜์˜ ๋น„์ฆˆ๋‹ˆ์Šค ๋กœ์ง์„ ๋ถ„๋ฆฌํ•œ๋‹ค. +- [x] Github๊ณผ Google์˜ ์ •๋ณด๋ฅผ properties(ํ˜น์€ yaml)ํŒŒ์ผ๋กœ ๋ถ„๋ฆฌํ•œ๋‹ค. + +## ๐Ÿš€ 2-1๋‹จ๊ณ„ - ๋ฆฌ๋‹ค์ด๋ ‰ํŠธ ํ•„ํ„ฐ +- [x] OAuth2AuthorizationRequestRedirectFilter ๊ตฌํ˜„ + +## ๐Ÿš€ 2-2๋‹จ๊ณ„ - OAuth ์ธ์ฆ ํ•„ํ„ฐ +- [x] OAuth2LoginAuthenticationFilter ๊ตฌํ˜„
Unknown
์š”๊ตฌ์‚ฌํ•ญ ์ •๋ฆฌ ๐Ÿ‘
@@ -0,0 +1,50 @@ +package nextstep.security.oauth2.authentication; + +import jakarta.servlet.FilterChain; +import jakarta.servlet.ServletException; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; +import nextstep.security.authentication.AuthenticationException; +import nextstep.security.oauth2.exchange.AuthorizationRequestRepository; +import nextstep.security.oauth2.exchange.OAuth2AuthorizationRequest; +import nextstep.security.oauth2.exchange.OAuth2AuthorizationRequestResolver; +import org.springframework.web.filter.OncePerRequestFilter; + +import java.io.IOException; + +public class OAuth2AuthorizationRequestRedirectFilter extends OncePerRequestFilter { + + private final OAuth2AuthorizationRequestResolver authorizationRequestResolver; + private final AuthorizationRequestRepository authorizationRequestRepository; + + public OAuth2AuthorizationRequestRedirectFilter(OAuth2AuthorizationRequestResolver authorizationRequestResolver, + AuthorizationRequestRepository authorizationRequestRepository) { + + this.authorizationRequestResolver = authorizationRequestResolver; + this.authorizationRequestRepository = authorizationRequestRepository; + } + + @Override + protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, + FilterChain filterChain) throws ServletException, IOException { + + try { + OAuth2AuthorizationRequest authorizationRequest = this.authorizationRequestResolver.resolve(request); + if (authorizationRequest != null) { + this.sendRedirectForAuthorization(request, response, authorizationRequest); + return; + } + } catch (Exception e) { + throw new AuthenticationException("exception ... %s".formatted(e.getMessage())); + } + + filterChain.doFilter(request, response); + } + + private void sendRedirectForAuthorization(HttpServletRequest request, HttpServletResponse response, + OAuth2AuthorizationRequest authorizationRequest) throws IOException { + + this.authorizationRequestRepository.saveAuthorizationRequest(authorizationRequest, request, response); + response.sendRedirect(authorizationRequest.getAuthorizationRequestUri()); + } +}
Java
OAuth2AuthorizationRequestResolver์—์„œ OAuth2AuthorizationRequest๋ฅผ ์ƒ์„ฑํ•  ๋•Œ, authorizationRequestUri์— ํ•„์ˆ˜์ ์ธ ์ฟผ๋ฆฌ ํŒŒ๋ผ๋ฏธํ„ฐ(client_id, response_type, scope, redirect_uri ๋“ฑ)๋ฅผ ๋ฏธ๋ฆฌ ํฌํ•จํ•  ์ˆ˜๋„ ์žˆ์„ ๊ฒƒ ๊ฐ™์€๋ฐ, ์–ด๋–ป๊ฒŒ ์ƒ๊ฐํ•˜์‹œ๋‚˜์š”? ๐Ÿ˜„ ```suggestion response.sendRedirect(authorizationRequest.getAuthorizationRequestUri()); ```
@@ -0,0 +1,115 @@ +package nextstep.security.oauth2.authentication; + +import jakarta.servlet.FilterChain; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; +import nextstep.security.authentication.AbstractAuthenticationProcessingFilter; +import nextstep.security.authentication.Authentication; +import nextstep.security.authentication.AuthenticationManager; +import nextstep.security.oauth2.authorizedclient.OAuth2AuthorizedClient; +import nextstep.security.oauth2.authorizedclient.OAuth2AuthorizedClientService; +import nextstep.security.oauth2.client.ClientRegistration; +import nextstep.security.oauth2.client.ClientRegistrationRepository; +import nextstep.security.oauth2.exception.OAuth2AuthenticationException; +import nextstep.security.oauth2.exchange.AuthorizationRequestRepository; +import nextstep.security.oauth2.exchange.HttpSessionOAuth2AuthorizationRequestRepository; +import nextstep.security.oauth2.exchange.OAuth2AuthorizationExchange; +import nextstep.security.oauth2.exchange.OAuth2AuthorizationRequest; +import nextstep.security.oauth2.exchange.OAuth2AuthorizationResponse; +import nextstep.security.oauth2.utils.OAuth2AuthorizationResponseUtils; +import org.springframework.core.convert.converter.Converter; +import org.springframework.util.MultiValueMap; + +import java.io.IOException; +import java.util.Set; + +public class OAuth2LoginAuthenticationFilter extends AbstractAuthenticationProcessingFilter { + private final AuthorizationRequestRepository authorizationRequestRepository = + new HttpSessionOAuth2AuthorizationRequestRepository(); + + private final ClientRegistrationRepository clientRegistrationRepository; + private final AuthenticationManager authenticationManager; + private final OAuth2AuthorizedClientService authorizedClientRepository; + + private final Converter<OAuth2LoginAuthenticationToken, OAuth2AuthenticationToken> authenticationResultConverter = + this::createAuthenticationResult; + + public OAuth2LoginAuthenticationFilter(ClientRegistrationRepository clientRegistrationRepository, + AuthenticationManager authenticationManager, + OAuth2AuthorizedClientService authorizedClientRepository) { + + this.clientRegistrationRepository = clientRegistrationRepository; + this.authenticationManager = authenticationManager; + this.authorizedClientRepository = authorizedClientRepository; + } + + @Override + protected boolean requiresAuthentication(HttpServletRequest request, HttpServletResponse response) { + return request.getRequestURI().startsWith("/login/oauth2/code/"); + } + + @Override + protected Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) { + + // request์—์„œ parameter๋ฅผ ๊ฐ€์ ธ์˜ค๊ธฐ + MultiValueMap<String, String> params = OAuth2AuthorizationResponseUtils.toMultiMap(request.getParameterMap()); + if (!OAuth2AuthorizationResponseUtils.isAuthorizationResponse(params)) { + throw new OAuth2AuthenticationException("authorizationRequest param is not authorization response"); + } + + // session์—์„œ authorizationRequest๋ฅผ ๊ฐ€์ ธ์˜ค๊ธฐ + OAuth2AuthorizationRequest authorizationRequest = this.authorizationRequestRepository + .removeAuthorizationRequest(request, response); + if (authorizationRequest == null) { + throw new OAuth2AuthenticationException("authorizationRequest is null"); + } + + // registrationId๋ฅผ ๊ฐ€์ ธ์˜ค๊ณ  clientRegistration์„ ๊ฐ€์ ธ์˜ค๊ธฐ + String registrationId = authorizationRequest.getRegistrationId(); + ClientRegistration clientRegistration = this.clientRegistrationRepository.findByRegistrationId(registrationId); + if (clientRegistration == null) { + throw new OAuth2AuthenticationException("client registration is null"); + } + + OAuth2AuthorizationResponse authorizationResponse = OAuth2AuthorizationResponseUtils.convert(params); + + // access token ์„ ๊ฐ€์ ธ์˜ค๊ธฐ ์œ„ํ•œ request ๊ฐ์ฒด ๋งŒ๋“ค๊ธฐ + // OAuth2LoginAuthenticationToken ๋งŒ๋“ค๊ธฐ + OAuth2LoginAuthenticationToken authRequest = new OAuth2LoginAuthenticationToken(clientRegistration, + new OAuth2AuthorizationExchange( + authorizationRequest, + authorizationResponse) + ); + + // provider ์ธ์ฆ ํ›„ authenticated๋œ OAuth2AuthenticationToken ๊ฐ์ฒด ๊ฐ€์ ธ์˜ค๊ธฐ + OAuth2LoginAuthenticationToken authResult = + (OAuth2LoginAuthenticationToken) this.authenticationManager.authenticate(authRequest); + + OAuth2AuthenticationToken oauth2Authentication = authenticationResultConverter.convert(authResult); + + // authorizedClientRepository ์— ์ €์žฅํ•  OAuth2AuthorizedClient์„ ๋งŒ๋“ค๊ณ  ์ €์žฅ + OAuth2AuthorizedClient oAuth2AuthorizedClient = new OAuth2AuthorizedClient(clientRegistration, + oauth2Authentication.getPrincipal().getName(), + authResult.getAccessToken()); + + this.authorizedClientRepository.saveAuthorizedClient(oAuth2AuthorizedClient, oauth2Authentication); + return oauth2Authentication; + } + + @Override + protected void successfulAuthentication(HttpServletRequest request, HttpServletResponse response, + FilterChain chain, Authentication authResult) throws IOException { + + super.successfulAuthentication(request, response, chain, authResult); + response.sendRedirect("/"); + } + + private OAuth2AuthenticationToken createAuthenticationResult(OAuth2LoginAuthenticationToken authenticationResult) { + Set<String> authorities = authenticationResult.getAccessToken().getScopes(); + authorities.addAll(authenticationResult.getAuthorities()); + return OAuth2AuthenticationToken.authenticated(authenticationResult.getPrincipal(), + authenticationResult.getAuthorities(), + authenticationResult.getClientRegistration().getRegistrationId()); + } + +}
Java
Spring Security์—์„œ๋Š” OAuth2AuthorizationResponseUtils.toMultiMap(request.getParameterMap())์„ ์‚ฌ์šฉํ•˜์—ฌ OAuth2 ์‘๋‹ต์„ MultiValueMap์œผ๋กœ ๋ณ€ํ™˜ํ•œ ํ›„, OAuth2AuthorizationResponseUtils.isAuthorizationResponse()๋ฅผ ํ†ตํ•ด ์œ ํšจ์„ฑ์„ ๊ฒ€์‚ฌํ•˜๋Š” ๋ฐฉ์‹์„ ์‚ฌ์šฉํ•ฉ๋‹ˆ๋‹ค. ํ•œ๋ฒˆ ํ™•์ธํ•ด ๋ณด์…”๋„ ์ข‹์„ ๊ฒƒ ๊ฐ™์•„์š” ๐Ÿ˜„
@@ -0,0 +1,115 @@ +package nextstep.security.oauth2.authentication; + +import jakarta.servlet.FilterChain; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; +import nextstep.security.authentication.AbstractAuthenticationProcessingFilter; +import nextstep.security.authentication.Authentication; +import nextstep.security.authentication.AuthenticationManager; +import nextstep.security.oauth2.authorizedclient.OAuth2AuthorizedClient; +import nextstep.security.oauth2.authorizedclient.OAuth2AuthorizedClientService; +import nextstep.security.oauth2.client.ClientRegistration; +import nextstep.security.oauth2.client.ClientRegistrationRepository; +import nextstep.security.oauth2.exception.OAuth2AuthenticationException; +import nextstep.security.oauth2.exchange.AuthorizationRequestRepository; +import nextstep.security.oauth2.exchange.HttpSessionOAuth2AuthorizationRequestRepository; +import nextstep.security.oauth2.exchange.OAuth2AuthorizationExchange; +import nextstep.security.oauth2.exchange.OAuth2AuthorizationRequest; +import nextstep.security.oauth2.exchange.OAuth2AuthorizationResponse; +import nextstep.security.oauth2.utils.OAuth2AuthorizationResponseUtils; +import org.springframework.core.convert.converter.Converter; +import org.springframework.util.MultiValueMap; + +import java.io.IOException; +import java.util.Set; + +public class OAuth2LoginAuthenticationFilter extends AbstractAuthenticationProcessingFilter { + private final AuthorizationRequestRepository authorizationRequestRepository = + new HttpSessionOAuth2AuthorizationRequestRepository(); + + private final ClientRegistrationRepository clientRegistrationRepository; + private final AuthenticationManager authenticationManager; + private final OAuth2AuthorizedClientService authorizedClientRepository; + + private final Converter<OAuth2LoginAuthenticationToken, OAuth2AuthenticationToken> authenticationResultConverter = + this::createAuthenticationResult; + + public OAuth2LoginAuthenticationFilter(ClientRegistrationRepository clientRegistrationRepository, + AuthenticationManager authenticationManager, + OAuth2AuthorizedClientService authorizedClientRepository) { + + this.clientRegistrationRepository = clientRegistrationRepository; + this.authenticationManager = authenticationManager; + this.authorizedClientRepository = authorizedClientRepository; + } + + @Override + protected boolean requiresAuthentication(HttpServletRequest request, HttpServletResponse response) { + return request.getRequestURI().startsWith("/login/oauth2/code/"); + } + + @Override + protected Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) { + + // request์—์„œ parameter๋ฅผ ๊ฐ€์ ธ์˜ค๊ธฐ + MultiValueMap<String, String> params = OAuth2AuthorizationResponseUtils.toMultiMap(request.getParameterMap()); + if (!OAuth2AuthorizationResponseUtils.isAuthorizationResponse(params)) { + throw new OAuth2AuthenticationException("authorizationRequest param is not authorization response"); + } + + // session์—์„œ authorizationRequest๋ฅผ ๊ฐ€์ ธ์˜ค๊ธฐ + OAuth2AuthorizationRequest authorizationRequest = this.authorizationRequestRepository + .removeAuthorizationRequest(request, response); + if (authorizationRequest == null) { + throw new OAuth2AuthenticationException("authorizationRequest is null"); + } + + // registrationId๋ฅผ ๊ฐ€์ ธ์˜ค๊ณ  clientRegistration์„ ๊ฐ€์ ธ์˜ค๊ธฐ + String registrationId = authorizationRequest.getRegistrationId(); + ClientRegistration clientRegistration = this.clientRegistrationRepository.findByRegistrationId(registrationId); + if (clientRegistration == null) { + throw new OAuth2AuthenticationException("client registration is null"); + } + + OAuth2AuthorizationResponse authorizationResponse = OAuth2AuthorizationResponseUtils.convert(params); + + // access token ์„ ๊ฐ€์ ธ์˜ค๊ธฐ ์œ„ํ•œ request ๊ฐ์ฒด ๋งŒ๋“ค๊ธฐ + // OAuth2LoginAuthenticationToken ๋งŒ๋“ค๊ธฐ + OAuth2LoginAuthenticationToken authRequest = new OAuth2LoginAuthenticationToken(clientRegistration, + new OAuth2AuthorizationExchange( + authorizationRequest, + authorizationResponse) + ); + + // provider ์ธ์ฆ ํ›„ authenticated๋œ OAuth2AuthenticationToken ๊ฐ์ฒด ๊ฐ€์ ธ์˜ค๊ธฐ + OAuth2LoginAuthenticationToken authResult = + (OAuth2LoginAuthenticationToken) this.authenticationManager.authenticate(authRequest); + + OAuth2AuthenticationToken oauth2Authentication = authenticationResultConverter.convert(authResult); + + // authorizedClientRepository ์— ์ €์žฅํ•  OAuth2AuthorizedClient์„ ๋งŒ๋“ค๊ณ  ์ €์žฅ + OAuth2AuthorizedClient oAuth2AuthorizedClient = new OAuth2AuthorizedClient(clientRegistration, + oauth2Authentication.getPrincipal().getName(), + authResult.getAccessToken()); + + this.authorizedClientRepository.saveAuthorizedClient(oAuth2AuthorizedClient, oauth2Authentication); + return oauth2Authentication; + } + + @Override + protected void successfulAuthentication(HttpServletRequest request, HttpServletResponse response, + FilterChain chain, Authentication authResult) throws IOException { + + super.successfulAuthentication(request, response, chain, authResult); + response.sendRedirect("/"); + } + + private OAuth2AuthenticationToken createAuthenticationResult(OAuth2LoginAuthenticationToken authenticationResult) { + Set<String> authorities = authenticationResult.getAccessToken().getScopes(); + authorities.addAll(authenticationResult.getAuthorities()); + return OAuth2AuthenticationToken.authenticated(authenticationResult.getPrincipal(), + authenticationResult.getAuthorities(), + authenticationResult.getClientRegistration().getRegistrationId()); + } + +}
Java
๋ถˆํ•„์š”ํ•œ ์˜ค๋ฒ„๋ผ์ด๋”ฉ ์ด๋ผ๊ณ  ์ƒ๊ฐ๋˜๋„ค์š”. ์ œ๊ฑฐํ•ด๋„ ๋˜๊ฒ ์Šต๋‹ˆ๋‹ค ๐Ÿ˜„
@@ -0,0 +1,115 @@ +package nextstep.security.oauth2.authentication; + +import jakarta.servlet.FilterChain; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; +import nextstep.security.authentication.AbstractAuthenticationProcessingFilter; +import nextstep.security.authentication.Authentication; +import nextstep.security.authentication.AuthenticationManager; +import nextstep.security.oauth2.authorizedclient.OAuth2AuthorizedClient; +import nextstep.security.oauth2.authorizedclient.OAuth2AuthorizedClientService; +import nextstep.security.oauth2.client.ClientRegistration; +import nextstep.security.oauth2.client.ClientRegistrationRepository; +import nextstep.security.oauth2.exception.OAuth2AuthenticationException; +import nextstep.security.oauth2.exchange.AuthorizationRequestRepository; +import nextstep.security.oauth2.exchange.HttpSessionOAuth2AuthorizationRequestRepository; +import nextstep.security.oauth2.exchange.OAuth2AuthorizationExchange; +import nextstep.security.oauth2.exchange.OAuth2AuthorizationRequest; +import nextstep.security.oauth2.exchange.OAuth2AuthorizationResponse; +import nextstep.security.oauth2.utils.OAuth2AuthorizationResponseUtils; +import org.springframework.core.convert.converter.Converter; +import org.springframework.util.MultiValueMap; + +import java.io.IOException; +import java.util.Set; + +public class OAuth2LoginAuthenticationFilter extends AbstractAuthenticationProcessingFilter { + private final AuthorizationRequestRepository authorizationRequestRepository = + new HttpSessionOAuth2AuthorizationRequestRepository(); + + private final ClientRegistrationRepository clientRegistrationRepository; + private final AuthenticationManager authenticationManager; + private final OAuth2AuthorizedClientService authorizedClientRepository; + + private final Converter<OAuth2LoginAuthenticationToken, OAuth2AuthenticationToken> authenticationResultConverter = + this::createAuthenticationResult; + + public OAuth2LoginAuthenticationFilter(ClientRegistrationRepository clientRegistrationRepository, + AuthenticationManager authenticationManager, + OAuth2AuthorizedClientService authorizedClientRepository) { + + this.clientRegistrationRepository = clientRegistrationRepository; + this.authenticationManager = authenticationManager; + this.authorizedClientRepository = authorizedClientRepository; + } + + @Override + protected boolean requiresAuthentication(HttpServletRequest request, HttpServletResponse response) { + return request.getRequestURI().startsWith("/login/oauth2/code/"); + } + + @Override + protected Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) { + + // request์—์„œ parameter๋ฅผ ๊ฐ€์ ธ์˜ค๊ธฐ + MultiValueMap<String, String> params = OAuth2AuthorizationResponseUtils.toMultiMap(request.getParameterMap()); + if (!OAuth2AuthorizationResponseUtils.isAuthorizationResponse(params)) { + throw new OAuth2AuthenticationException("authorizationRequest param is not authorization response"); + } + + // session์—์„œ authorizationRequest๋ฅผ ๊ฐ€์ ธ์˜ค๊ธฐ + OAuth2AuthorizationRequest authorizationRequest = this.authorizationRequestRepository + .removeAuthorizationRequest(request, response); + if (authorizationRequest == null) { + throw new OAuth2AuthenticationException("authorizationRequest is null"); + } + + // registrationId๋ฅผ ๊ฐ€์ ธ์˜ค๊ณ  clientRegistration์„ ๊ฐ€์ ธ์˜ค๊ธฐ + String registrationId = authorizationRequest.getRegistrationId(); + ClientRegistration clientRegistration = this.clientRegistrationRepository.findByRegistrationId(registrationId); + if (clientRegistration == null) { + throw new OAuth2AuthenticationException("client registration is null"); + } + + OAuth2AuthorizationResponse authorizationResponse = OAuth2AuthorizationResponseUtils.convert(params); + + // access token ์„ ๊ฐ€์ ธ์˜ค๊ธฐ ์œ„ํ•œ request ๊ฐ์ฒด ๋งŒ๋“ค๊ธฐ + // OAuth2LoginAuthenticationToken ๋งŒ๋“ค๊ธฐ + OAuth2LoginAuthenticationToken authRequest = new OAuth2LoginAuthenticationToken(clientRegistration, + new OAuth2AuthorizationExchange( + authorizationRequest, + authorizationResponse) + ); + + // provider ์ธ์ฆ ํ›„ authenticated๋œ OAuth2AuthenticationToken ๊ฐ์ฒด ๊ฐ€์ ธ์˜ค๊ธฐ + OAuth2LoginAuthenticationToken authResult = + (OAuth2LoginAuthenticationToken) this.authenticationManager.authenticate(authRequest); + + OAuth2AuthenticationToken oauth2Authentication = authenticationResultConverter.convert(authResult); + + // authorizedClientRepository ์— ์ €์žฅํ•  OAuth2AuthorizedClient์„ ๋งŒ๋“ค๊ณ  ์ €์žฅ + OAuth2AuthorizedClient oAuth2AuthorizedClient = new OAuth2AuthorizedClient(clientRegistration, + oauth2Authentication.getPrincipal().getName(), + authResult.getAccessToken()); + + this.authorizedClientRepository.saveAuthorizedClient(oAuth2AuthorizedClient, oauth2Authentication); + return oauth2Authentication; + } + + @Override + protected void successfulAuthentication(HttpServletRequest request, HttpServletResponse response, + FilterChain chain, Authentication authResult) throws IOException { + + super.successfulAuthentication(request, response, chain, authResult); + response.sendRedirect("/"); + } + + private OAuth2AuthenticationToken createAuthenticationResult(OAuth2LoginAuthenticationToken authenticationResult) { + Set<String> authorities = authenticationResult.getAccessToken().getScopes(); + authorities.addAll(authenticationResult.getAuthorities()); + return OAuth2AuthenticationToken.authenticated(authenticationResult.getPrincipal(), + authenticationResult.getAuthorities(), + authenticationResult.getClientRegistration().getRegistrationId()); + } + +}
Java
ํ•ด๋‹น ์ฃผ์„์€ ์ œ๊ฑฐํ•  ์˜ˆ์ •์ด์‹ค๊นŒ์š”? ๐Ÿค”
@@ -0,0 +1,115 @@ +package nextstep.security.oauth2.authentication; + +import jakarta.servlet.FilterChain; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; +import nextstep.security.authentication.AbstractAuthenticationProcessingFilter; +import nextstep.security.authentication.Authentication; +import nextstep.security.authentication.AuthenticationManager; +import nextstep.security.oauth2.authorizedclient.OAuth2AuthorizedClient; +import nextstep.security.oauth2.authorizedclient.OAuth2AuthorizedClientService; +import nextstep.security.oauth2.client.ClientRegistration; +import nextstep.security.oauth2.client.ClientRegistrationRepository; +import nextstep.security.oauth2.exception.OAuth2AuthenticationException; +import nextstep.security.oauth2.exchange.AuthorizationRequestRepository; +import nextstep.security.oauth2.exchange.HttpSessionOAuth2AuthorizationRequestRepository; +import nextstep.security.oauth2.exchange.OAuth2AuthorizationExchange; +import nextstep.security.oauth2.exchange.OAuth2AuthorizationRequest; +import nextstep.security.oauth2.exchange.OAuth2AuthorizationResponse; +import nextstep.security.oauth2.utils.OAuth2AuthorizationResponseUtils; +import org.springframework.core.convert.converter.Converter; +import org.springframework.util.MultiValueMap; + +import java.io.IOException; +import java.util.Set; + +public class OAuth2LoginAuthenticationFilter extends AbstractAuthenticationProcessingFilter { + private final AuthorizationRequestRepository authorizationRequestRepository = + new HttpSessionOAuth2AuthorizationRequestRepository(); + + private final ClientRegistrationRepository clientRegistrationRepository; + private final AuthenticationManager authenticationManager; + private final OAuth2AuthorizedClientService authorizedClientRepository; + + private final Converter<OAuth2LoginAuthenticationToken, OAuth2AuthenticationToken> authenticationResultConverter = + this::createAuthenticationResult; + + public OAuth2LoginAuthenticationFilter(ClientRegistrationRepository clientRegistrationRepository, + AuthenticationManager authenticationManager, + OAuth2AuthorizedClientService authorizedClientRepository) { + + this.clientRegistrationRepository = clientRegistrationRepository; + this.authenticationManager = authenticationManager; + this.authorizedClientRepository = authorizedClientRepository; + } + + @Override + protected boolean requiresAuthentication(HttpServletRequest request, HttpServletResponse response) { + return request.getRequestURI().startsWith("/login/oauth2/code/"); + } + + @Override + protected Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) { + + // request์—์„œ parameter๋ฅผ ๊ฐ€์ ธ์˜ค๊ธฐ + MultiValueMap<String, String> params = OAuth2AuthorizationResponseUtils.toMultiMap(request.getParameterMap()); + if (!OAuth2AuthorizationResponseUtils.isAuthorizationResponse(params)) { + throw new OAuth2AuthenticationException("authorizationRequest param is not authorization response"); + } + + // session์—์„œ authorizationRequest๋ฅผ ๊ฐ€์ ธ์˜ค๊ธฐ + OAuth2AuthorizationRequest authorizationRequest = this.authorizationRequestRepository + .removeAuthorizationRequest(request, response); + if (authorizationRequest == null) { + throw new OAuth2AuthenticationException("authorizationRequest is null"); + } + + // registrationId๋ฅผ ๊ฐ€์ ธ์˜ค๊ณ  clientRegistration์„ ๊ฐ€์ ธ์˜ค๊ธฐ + String registrationId = authorizationRequest.getRegistrationId(); + ClientRegistration clientRegistration = this.clientRegistrationRepository.findByRegistrationId(registrationId); + if (clientRegistration == null) { + throw new OAuth2AuthenticationException("client registration is null"); + } + + OAuth2AuthorizationResponse authorizationResponse = OAuth2AuthorizationResponseUtils.convert(params); + + // access token ์„ ๊ฐ€์ ธ์˜ค๊ธฐ ์œ„ํ•œ request ๊ฐ์ฒด ๋งŒ๋“ค๊ธฐ + // OAuth2LoginAuthenticationToken ๋งŒ๋“ค๊ธฐ + OAuth2LoginAuthenticationToken authRequest = new OAuth2LoginAuthenticationToken(clientRegistration, + new OAuth2AuthorizationExchange( + authorizationRequest, + authorizationResponse) + ); + + // provider ์ธ์ฆ ํ›„ authenticated๋œ OAuth2AuthenticationToken ๊ฐ์ฒด ๊ฐ€์ ธ์˜ค๊ธฐ + OAuth2LoginAuthenticationToken authResult = + (OAuth2LoginAuthenticationToken) this.authenticationManager.authenticate(authRequest); + + OAuth2AuthenticationToken oauth2Authentication = authenticationResultConverter.convert(authResult); + + // authorizedClientRepository ์— ์ €์žฅํ•  OAuth2AuthorizedClient์„ ๋งŒ๋“ค๊ณ  ์ €์žฅ + OAuth2AuthorizedClient oAuth2AuthorizedClient = new OAuth2AuthorizedClient(clientRegistration, + oauth2Authentication.getPrincipal().getName(), + authResult.getAccessToken()); + + this.authorizedClientRepository.saveAuthorizedClient(oAuth2AuthorizedClient, oauth2Authentication); + return oauth2Authentication; + } + + @Override + protected void successfulAuthentication(HttpServletRequest request, HttpServletResponse response, + FilterChain chain, Authentication authResult) throws IOException { + + super.successfulAuthentication(request, response, chain, authResult); + response.sendRedirect("/"); + } + + private OAuth2AuthenticationToken createAuthenticationResult(OAuth2LoginAuthenticationToken authenticationResult) { + Set<String> authorities = authenticationResult.getAccessToken().getScopes(); + authorities.addAll(authenticationResult.getAuthorities()); + return OAuth2AuthenticationToken.authenticated(authenticationResult.getPrincipal(), + authenticationResult.getAuthorities(), + authenticationResult.getClientRegistration().getRegistrationId()); + } + +}
Java
๋„ต๋„ต ใ…Žใ…Žใ…Ž ์ œ๊ฑฐํ•˜๋„๋ก ํ•˜๊ฒ ์Šต๋‹ˆ๋‹ค. ๐Ÿ™
@@ -0,0 +1,115 @@ +package nextstep.security.oauth2.authentication; + +import jakarta.servlet.FilterChain; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; +import nextstep.security.authentication.AbstractAuthenticationProcessingFilter; +import nextstep.security.authentication.Authentication; +import nextstep.security.authentication.AuthenticationManager; +import nextstep.security.oauth2.authorizedclient.OAuth2AuthorizedClient; +import nextstep.security.oauth2.authorizedclient.OAuth2AuthorizedClientService; +import nextstep.security.oauth2.client.ClientRegistration; +import nextstep.security.oauth2.client.ClientRegistrationRepository; +import nextstep.security.oauth2.exception.OAuth2AuthenticationException; +import nextstep.security.oauth2.exchange.AuthorizationRequestRepository; +import nextstep.security.oauth2.exchange.HttpSessionOAuth2AuthorizationRequestRepository; +import nextstep.security.oauth2.exchange.OAuth2AuthorizationExchange; +import nextstep.security.oauth2.exchange.OAuth2AuthorizationRequest; +import nextstep.security.oauth2.exchange.OAuth2AuthorizationResponse; +import nextstep.security.oauth2.utils.OAuth2AuthorizationResponseUtils; +import org.springframework.core.convert.converter.Converter; +import org.springframework.util.MultiValueMap; + +import java.io.IOException; +import java.util.Set; + +public class OAuth2LoginAuthenticationFilter extends AbstractAuthenticationProcessingFilter { + private final AuthorizationRequestRepository authorizationRequestRepository = + new HttpSessionOAuth2AuthorizationRequestRepository(); + + private final ClientRegistrationRepository clientRegistrationRepository; + private final AuthenticationManager authenticationManager; + private final OAuth2AuthorizedClientService authorizedClientRepository; + + private final Converter<OAuth2LoginAuthenticationToken, OAuth2AuthenticationToken> authenticationResultConverter = + this::createAuthenticationResult; + + public OAuth2LoginAuthenticationFilter(ClientRegistrationRepository clientRegistrationRepository, + AuthenticationManager authenticationManager, + OAuth2AuthorizedClientService authorizedClientRepository) { + + this.clientRegistrationRepository = clientRegistrationRepository; + this.authenticationManager = authenticationManager; + this.authorizedClientRepository = authorizedClientRepository; + } + + @Override + protected boolean requiresAuthentication(HttpServletRequest request, HttpServletResponse response) { + return request.getRequestURI().startsWith("/login/oauth2/code/"); + } + + @Override + protected Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) { + + // request์—์„œ parameter๋ฅผ ๊ฐ€์ ธ์˜ค๊ธฐ + MultiValueMap<String, String> params = OAuth2AuthorizationResponseUtils.toMultiMap(request.getParameterMap()); + if (!OAuth2AuthorizationResponseUtils.isAuthorizationResponse(params)) { + throw new OAuth2AuthenticationException("authorizationRequest param is not authorization response"); + } + + // session์—์„œ authorizationRequest๋ฅผ ๊ฐ€์ ธ์˜ค๊ธฐ + OAuth2AuthorizationRequest authorizationRequest = this.authorizationRequestRepository + .removeAuthorizationRequest(request, response); + if (authorizationRequest == null) { + throw new OAuth2AuthenticationException("authorizationRequest is null"); + } + + // registrationId๋ฅผ ๊ฐ€์ ธ์˜ค๊ณ  clientRegistration์„ ๊ฐ€์ ธ์˜ค๊ธฐ + String registrationId = authorizationRequest.getRegistrationId(); + ClientRegistration clientRegistration = this.clientRegistrationRepository.findByRegistrationId(registrationId); + if (clientRegistration == null) { + throw new OAuth2AuthenticationException("client registration is null"); + } + + OAuth2AuthorizationResponse authorizationResponse = OAuth2AuthorizationResponseUtils.convert(params); + + // access token ์„ ๊ฐ€์ ธ์˜ค๊ธฐ ์œ„ํ•œ request ๊ฐ์ฒด ๋งŒ๋“ค๊ธฐ + // OAuth2LoginAuthenticationToken ๋งŒ๋“ค๊ธฐ + OAuth2LoginAuthenticationToken authRequest = new OAuth2LoginAuthenticationToken(clientRegistration, + new OAuth2AuthorizationExchange( + authorizationRequest, + authorizationResponse) + ); + + // provider ์ธ์ฆ ํ›„ authenticated๋œ OAuth2AuthenticationToken ๊ฐ์ฒด ๊ฐ€์ ธ์˜ค๊ธฐ + OAuth2LoginAuthenticationToken authResult = + (OAuth2LoginAuthenticationToken) this.authenticationManager.authenticate(authRequest); + + OAuth2AuthenticationToken oauth2Authentication = authenticationResultConverter.convert(authResult); + + // authorizedClientRepository ์— ์ €์žฅํ•  OAuth2AuthorizedClient์„ ๋งŒ๋“ค๊ณ  ์ €์žฅ + OAuth2AuthorizedClient oAuth2AuthorizedClient = new OAuth2AuthorizedClient(clientRegistration, + oauth2Authentication.getPrincipal().getName(), + authResult.getAccessToken()); + + this.authorizedClientRepository.saveAuthorizedClient(oAuth2AuthorizedClient, oauth2Authentication); + return oauth2Authentication; + } + + @Override + protected void successfulAuthentication(HttpServletRequest request, HttpServletResponse response, + FilterChain chain, Authentication authResult) throws IOException { + + super.successfulAuthentication(request, response, chain, authResult); + response.sendRedirect("/"); + } + + private OAuth2AuthenticationToken createAuthenticationResult(OAuth2LoginAuthenticationToken authenticationResult) { + Set<String> authorities = authenticationResult.getAccessToken().getScopes(); + authorities.addAll(authenticationResult.getAuthorities()); + return OAuth2AuthenticationToken.authenticated(authenticationResult.getPrincipal(), + authenticationResult.getAuthorities(), + authenticationResult.getClientRegistration().getRegistrationId()); + } + +}
Java
์•„ํ•˜, OAuth2AuthorizationResponseUtils์—์„œ Request Paramater๋ฅผ Map์œผ๋กœ ๋ณ€ํ™˜ํ•˜์—ฌ ์‚ฌ์šฉํ•˜๋Š” ๋ถ€๋ถ„์„ ์ฐธ๊ณ ํ•˜์—ฌ ์ˆ˜์ •ํ•ด๋ณด์•˜์Šต๋‹ˆ๋‹ค ๐Ÿ‘
@@ -0,0 +1,50 @@ +package nextstep.security.oauth2.authentication; + +import jakarta.servlet.FilterChain; +import jakarta.servlet.ServletException; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; +import nextstep.security.authentication.AuthenticationException; +import nextstep.security.oauth2.exchange.AuthorizationRequestRepository; +import nextstep.security.oauth2.exchange.OAuth2AuthorizationRequest; +import nextstep.security.oauth2.exchange.OAuth2AuthorizationRequestResolver; +import org.springframework.web.filter.OncePerRequestFilter; + +import java.io.IOException; + +public class OAuth2AuthorizationRequestRedirectFilter extends OncePerRequestFilter { + + private final OAuth2AuthorizationRequestResolver authorizationRequestResolver; + private final AuthorizationRequestRepository authorizationRequestRepository; + + public OAuth2AuthorizationRequestRedirectFilter(OAuth2AuthorizationRequestResolver authorizationRequestResolver, + AuthorizationRequestRepository authorizationRequestRepository) { + + this.authorizationRequestResolver = authorizationRequestResolver; + this.authorizationRequestRepository = authorizationRequestRepository; + } + + @Override + protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, + FilterChain filterChain) throws ServletException, IOException { + + try { + OAuth2AuthorizationRequest authorizationRequest = this.authorizationRequestResolver.resolve(request); + if (authorizationRequest != null) { + this.sendRedirectForAuthorization(request, response, authorizationRequest); + return; + } + } catch (Exception e) { + throw new AuthenticationException("exception ... %s".formatted(e.getMessage())); + } + + filterChain.doFilter(request, response); + } + + private void sendRedirectForAuthorization(HttpServletRequest request, HttpServletResponse response, + OAuth2AuthorizationRequest authorizationRequest) throws IOException { + + this.authorizationRequestRepository.saveAuthorizationRequest(authorizationRequest, request, response); + response.sendRedirect(authorizationRequest.getAuthorizationRequestUri()); + } +}
Java
์ด๋ถ€๋ถ„์€ Redirect Filter๊ฐ€ ๋ชจ๋“  Redirect Url ์ŠคํŽ™์„ ์•Œ๊ฒŒ ๋˜๋Š” ๊ฒƒ ๊ฐ™์•„์„œ, ์ƒ์„ฑ ์ฑ…์ž„์„ Resolver์—๊ฒŒ ๋งก๊ธฐ๋Š” ๊ฒƒ์ด ์ข‹์•„๋ณด์ด๋„ค์š” !! ๐Ÿ‘
@@ -3,49 +3,96 @@ import { useNavigate } from 'react-router'; import { useRecoilState } from 'recoil'; import ReviewZoneIcon from '@/assets/reviewZone.svg'; -import { Button, ImgWithSkeleton } from '@/components'; +import { ImgWithSkeleton, LoginRequestModal } from '@/components'; import { ROUTE } from '@/constants'; -import { useGetReviewGroupData, useModals, useReviewRequestCodeParam } from '@/hooks'; +import { useGetReviewGroupData, useSearchParamAndQuery, useModals, useToastContext } from '@/hooks'; +import { useGetUserProfile } from '@/hooks/oAuth'; import { reviewRequestCodeAtom } from '@/recoil'; import { calculateParticle } from '@/utils'; import PasswordModal from './components/PasswordModal'; +import ReviewButton from './components/ReviewButton'; import * as S from './styles'; const MODAL_KEYS = { content: 'CONTENT_MODAL', - login: 'LOGIN_MODAL', + writeOnLogin: 'LOGIN_MODAL_TO_WRITE', + checkOnLogin: 'LOGIN_MODAL_TO_CHECK', }; const BUTTON_SIZE = { - width: '28rem', + width: '30rem', height: '8.5rem', }; const IMG_HEIGHT = '15rem'; const ReviewZonePage = () => { + const navigate = useNavigate(); + const { isOpen, openModal, closeModal } = useModals(); const [storedReviewRequestCode, setStoredReviewRequestCode] = useRecoilState(reviewRequestCodeAtom); + const { userProfile, isUserLoggedIn } = useGetUserProfile(); + const { showToast } = useToastContext(); - const navigate = useNavigate(); + const { param: reviewRequestCode } = useSearchParamAndQuery({ + paramKey: 'reviewRequestCode', + }); - const { reviewRequestCode } = useReviewRequestCodeParam(); + if (!reviewRequestCode) throw new Error('์œ ํšจํ•˜์ง€ ์•Š์€ ๋ฆฌ๋ทฐ ์š”์ฒญ ์ฝ”๋“œ์˜ˆ์š”'); useEffect(() => { if (!storedReviewRequestCode && reviewRequestCode) { setStoredReviewRequestCode(reviewRequestCode); } }, []); - const { data: reviewGroupData } = useGetReviewGroupData({ reviewRequestCode }); + useEffect(() => { + // ์ฟผ๋ฆฌ ํŒŒ๋ผ๋ฏธํ„ฐ๋กœ ์ „๋‹ฌ๋œ state ํŒŒ์‹ฑ + const params = new URLSearchParams(location.search); + const loginActionParam = params.get('login_action'); + if (!loginActionParam) return; + + // ๋กœ๊ทธ์ธ ์ƒํƒœ๊ฐ€ ์•„๋‹Œ ๊ฒฝ์šฐ ์ฟผ๋ฆฌ ํŒŒ๋ผ๋ฏธํ„ฐ ์ œ๊ฑฐ + if (!isUserLoggedIn) { + params.delete('login_action'); + window.history.replaceState(null, '', `${location.pathname}`); + return; + } + + if (loginActionParam === 'reviewWrite') return handleReviewWrite(); + if (loginActionParam === 'reviewCheck') return handleReviewCheck(); + }, []); - const handleReviewWritingButtonClick = () => { + const { data: reviewGroupData, isMemberLink } = useGetReviewGroupData({ reviewRequestCode }); + + const PROJECT_NAME_GUIDE = `${reviewGroupData.projectName}${calculateParticle({ target: reviewGroupData.projectName, particles: { withFinalConsonant: '์„', withoutFinalConsonant: '๋ฅผ' } })} ํ•จ๊ป˜ํ•œ`; + const REVIEWEE_NAME_GUIDE = `${reviewGroupData.revieweeName}์˜ ๋ฆฌ๋ทฐ ๊ณต๊ฐ„์ด์—์š”`; + + const handleReviewWrite = () => { + if (isUserLoggedIn) return navigate(`/${ROUTE.reviewWriting}/${reviewRequestCode}`); + openModal(MODAL_KEYS.writeOnLogin); + }; + + const handleReviewWriteGuest = () => { navigate(`/${ROUTE.reviewWriting}/${reviewRequestCode}`); }; - const handleReviewListButtonClick = () => { - openModal(MODAL_KEYS.login); + const handleReviewCheck = () => { + // ๋น„ํšŒ์›์ด ๋งŒ๋“  ๊ทธ๋ฃน์ด๋ฉด ๋น„๋ฐ€๋ฒˆํ˜ธ ์ž…๋ ฅ + if (!isMemberLink) return openModal(MODAL_KEYS.content); + // ๋ฆฌ๋ทฐ์–ด๊ฐ€ ๋กœ๊ทธ์ธ ์•ˆ ํ–ˆ์œผ๋ฉด ๋กœ๊ทธ์ธ ๋ชจ๋‹ฌ ๋„์šฐ๊ธฐ + if (!isUserLoggedIn) return openModal(MODAL_KEYS.checkOnLogin); + // ๋ฆฌ๋ทฐ์–ด๊ฐ€ ๋งํฌ ์ฃผ์ธ์ด๋ฉด ๋ชฉ๋ก ํŽ˜์ด์ง€๋กœ ์ด๋™ + if (userProfile?.memberId === reviewGroupData.revieweeId) { + return navigate(`/${ROUTE.reviewList}/${reviewRequestCode}`); + } + return showToast({ + type: 'error', + message: '๋ฆฌ๋ทฐ๋Š” ๋ณธ์ธ๋งŒ ํ™•์ธํ•  ์ˆ˜ ์žˆ์–ด์š”', + durationMS: 3000, + position: 'bottom', + }); }; return ( @@ -54,26 +101,31 @@ const ReviewZonePage = () => { <S.ReviewZoneMainImg src={ReviewZoneIcon} alt="" $height={IMG_HEIGHT} /> </ImgWithSkeleton> <S.ReviewGuideContainer> - <S.ReviewGuide>{`${reviewGroupData.projectName}${calculateParticle({ target: reviewGroupData.projectName, particles: { withFinalConsonant: '์„', withoutFinalConsonant: '๋ฅผ' } })} ํ•จ๊ป˜ํ•œ`}</S.ReviewGuide> - <S.ReviewGuide>{`${reviewGroupData.revieweeName}์˜ ๋ฆฌ๋ทฐ ๊ณต๊ฐ„์ด์—์š”`}</S.ReviewGuide> + <S.ReviewGuide>{PROJECT_NAME_GUIDE}</S.ReviewGuide> + <S.ReviewGuide>{REVIEWEE_NAME_GUIDE}</S.ReviewGuide> </S.ReviewGuideContainer> - <S.ButtonContainer> - <Button styleType="primary" type="button" onClick={handleReviewWritingButtonClick} style={BUTTON_SIZE}> - <S.ButtonTextContainer> - <S.ButtonText>๋ฆฌ๋ทฐ ์“ฐ๊ธฐ</S.ButtonText> - <S.ButtonDescription>์ž‘์„ฑํ•œ ๋ฆฌ๋ทฐ๋Š” ์ต๋ช…์œผ๋กœ ์ œ์ถœ๋ผ์š”</S.ButtonDescription> - </S.ButtonTextContainer> - </Button> - <Button styleType="secondary" type="button" onClick={handleReviewListButtonClick} style={BUTTON_SIZE}> - <S.ButtonTextContainer> - <S.ButtonText>๋ฆฌ๋ทฐ ํ™•์ธํ•˜๊ธฐ</S.ButtonText> - <S.ButtonDescription>๋น„๋ฐ€๋ฒˆํ˜ธ๋กœ ๋‚ด๊ฐ€ ๋ฐ›์€ ๋ฆฌ๋ทฐ๋ฅผ ํ™•์ธํ•  ์ˆ˜ ์žˆ์–ด์š”</S.ButtonDescription> - </S.ButtonTextContainer> - </Button> - </S.ButtonContainer> + <ReviewButton> + <ReviewButton.Write handleClick={handleReviewWrite} /> + {!isUserLoggedIn && <ReviewButton.WriteGuest handleClick={handleReviewWriteGuest} />} + <ReviewButton.Check isGroupLoggedIn={isMemberLink} handleClick={handleReviewCheck} /> + </ReviewButton> {isOpen(MODAL_KEYS.content) && ( <PasswordModal reviewRequestCode={reviewRequestCode} closeModal={() => closeModal(MODAL_KEYS.content)} /> )} + {isOpen(MODAL_KEYS.writeOnLogin) && ( + <LoginRequestModal + action="reviewWrite" + titleType="loginIntent" + closeModal={() => closeModal(MODAL_KEYS.writeOnLogin)} + /> + )} + {isOpen(MODAL_KEYS.checkOnLogin) && ( + <LoginRequestModal + action="reviewCheck" + titleType="loginIntent" + closeModal={() => closeModal(MODAL_KEYS.checkOnLogin)} + /> + )} </S.ReviewZonePage> ); };
Unknown
์ด ์ฃผ์„์„ ๋ณด๊ธฐ ์ „์—๋Š” isGroupLoggedIn์ด ๋ฌด์Šจ ๋œป์ธ์ง€ ์ถ”์ธกํ•˜๊ธฐ ์–ด๋ ค์› ์–ด์š”. ์ˆœ๊ฐ„ ์œ ์ € ๋ง๊ณ  ๋‹ค๋ฅธ ๊ทธ๋ฃน์ด ์žˆ๋‚˜? ์‹ถ์—ˆ๋Š”๋ฐ ๋งํฌ๋ฅผ ์–ด๋–ค ์ƒํƒœ๋กœ ๋งŒ๋“ค์—ˆ๋ƒ๋ฅผ ๋‚˜ํƒ€๋‚ด๋Š” ๋ณ€์ˆ˜์˜€๊ตฐ์š”~ ์ด ๋งํฌ๊ฐ€ ๋กœ๊ทธ์ธํ•œ ์‚ฌ์šฉ์ž๊ฐ€ ๋งŒ๋“  ๊ฒƒ์ธ์ง€๋ฅผ ๋ณ€์ˆ˜๋ช…์—์„œ ๋ณด๋‹ค ์ง๊ด€์ ์œผ๋กœ ๋‚˜ํƒ€๋‚ฌ์œผ๋ฉด ์ข‹๊ฒ ์–ด์š”! ๋‹ค๋ฅธ ๋ถ„๋“ค์€ ์–ด๋–ป๊ฒŒ ์ƒ๊ฐํ•˜์‹œ๋‚˜์š”?
@@ -1,5 +1,7 @@ import { ReviewGroupData } from '@/types'; +import { MOCK_USER_PROFILE } from './userProfileData'; + export const VALIDATED_PASSWORD = '1234'; export const MOCK_AUTH_TOKEN_NAME = 'mockAuthToken'; @@ -14,12 +16,18 @@ export const bothCookie = [MOCK_AUTH_TOKEN_NAME, MOCK_LOGIN_TOKEN_NAME]; */ // ๋ณ€์ˆ˜๋ช…์ด ์นด๋ฉœ ์ผ€์ด์Šค์ธ ์ด์œ ๋Š” ํšŒ์›/๋น„ํšŒ์›์— ๋”ฐ๋ผ revieweeId๊ฐ€ ๋‹ฌ๋ผ์ง€๊ธฐ ๋•Œ๋ฌธ์— reviewRequestCode๋ณด๊ณ  ํŒ๋‹จํ•ด์„œ ํšŒ์›์ด๋ฉด number, ๋น„ํšŒ์›์ด๋ฉด null๋กœ ์„ค์ • -export const REVIEW_GROUP_DATA: ReviewGroupData = { - revieweeId: 1, +export const MEMBER_REVIEW_GROUP_DATA: ReviewGroupData = { + revieweeId: MOCK_USER_PROFILE.memberId, //๐Ÿ’ก ๋ณธ์ธ์ด ๋งŒ๋“  ๋ฆฌ๋ทฐ ๋งํฌ๊ฐ€ ์•„๋‹ ๋•Œ ํ† ์ŠคํŠธ ๊ธฐ๋Šฅ์„ ํ™•์ธํ•˜๊ณ  ์‹ถ๋‹ค๋ฉด ๋‹ค๋ฅธ ๋ฆฌ๋ทฐ ์•„์ด๋””๋ฅผ ๋„ฃ์–ด์„œ ํ™•์ธํ•ด๋ณด์„ธ์š” revieweeName: '๋ฐ”๋‹ค', projectName: '2024-review-me', }; +export const NONMEMBER_REVIEW_GROUP_DATA: ReviewGroupData = { + revieweeId: null, + revieweeName: '์†๋‹˜', + projectName: '2024-review-me', +}; + /**๋ฆฌ๋ทฐ ์—ฐ๊ฒฐ ํŽ˜์ด์ง€์—์„œ ์œ ํšจํ•œ reviewRequestCode */ export const VALID_REVIEW_REQUEST_CODE = { nonMember: `ABCD1234`,
TypeScript
revieweeId๊ฐ€ ์ˆ˜์ •๋œ ์ด์œ ๊ฐ€ ๊ถ๊ธˆํ•ฉ๋‹ˆ๋‹ค! ์˜๋ฏธ ์žˆ๋Š” ๊ฐ’์ด๋ผ๋ฉด ์ƒ์ˆ˜ํ™”ํ•ด์•ผ ํ•  ๊ฒƒ ๊ฐ™์•„์„œ์š”.
@@ -3,49 +3,96 @@ import { useNavigate } from 'react-router'; import { useRecoilState } from 'recoil'; import ReviewZoneIcon from '@/assets/reviewZone.svg'; -import { Button, ImgWithSkeleton } from '@/components'; +import { ImgWithSkeleton, LoginRequestModal } from '@/components'; import { ROUTE } from '@/constants'; -import { useGetReviewGroupData, useModals, useReviewRequestCodeParam } from '@/hooks'; +import { useGetReviewGroupData, useSearchParamAndQuery, useModals, useToastContext } from '@/hooks'; +import { useGetUserProfile } from '@/hooks/oAuth'; import { reviewRequestCodeAtom } from '@/recoil'; import { calculateParticle } from '@/utils'; import PasswordModal from './components/PasswordModal'; +import ReviewButton from './components/ReviewButton'; import * as S from './styles'; const MODAL_KEYS = { content: 'CONTENT_MODAL', - login: 'LOGIN_MODAL', + writeOnLogin: 'LOGIN_MODAL_TO_WRITE', + checkOnLogin: 'LOGIN_MODAL_TO_CHECK', }; const BUTTON_SIZE = { - width: '28rem', + width: '30rem', height: '8.5rem', }; const IMG_HEIGHT = '15rem'; const ReviewZonePage = () => { + const navigate = useNavigate(); + const { isOpen, openModal, closeModal } = useModals(); const [storedReviewRequestCode, setStoredReviewRequestCode] = useRecoilState(reviewRequestCodeAtom); + const { userProfile, isUserLoggedIn } = useGetUserProfile(); + const { showToast } = useToastContext(); - const navigate = useNavigate(); + const { param: reviewRequestCode } = useSearchParamAndQuery({ + paramKey: 'reviewRequestCode', + }); - const { reviewRequestCode } = useReviewRequestCodeParam(); + if (!reviewRequestCode) throw new Error('์œ ํšจํ•˜์ง€ ์•Š์€ ๋ฆฌ๋ทฐ ์š”์ฒญ ์ฝ”๋“œ์˜ˆ์š”'); useEffect(() => { if (!storedReviewRequestCode && reviewRequestCode) { setStoredReviewRequestCode(reviewRequestCode); } }, []); - const { data: reviewGroupData } = useGetReviewGroupData({ reviewRequestCode }); + useEffect(() => { + // ์ฟผ๋ฆฌ ํŒŒ๋ผ๋ฏธํ„ฐ๋กœ ์ „๋‹ฌ๋œ state ํŒŒ์‹ฑ + const params = new URLSearchParams(location.search); + const loginActionParam = params.get('login_action'); + if (!loginActionParam) return; + + // ๋กœ๊ทธ์ธ ์ƒํƒœ๊ฐ€ ์•„๋‹Œ ๊ฒฝ์šฐ ์ฟผ๋ฆฌ ํŒŒ๋ผ๋ฏธํ„ฐ ์ œ๊ฑฐ + if (!isUserLoggedIn) { + params.delete('login_action'); + window.history.replaceState(null, '', `${location.pathname}`); + return; + } + + if (loginActionParam === 'reviewWrite') return handleReviewWrite(); + if (loginActionParam === 'reviewCheck') return handleReviewCheck(); + }, []); - const handleReviewWritingButtonClick = () => { + const { data: reviewGroupData, isMemberLink } = useGetReviewGroupData({ reviewRequestCode }); + + const PROJECT_NAME_GUIDE = `${reviewGroupData.projectName}${calculateParticle({ target: reviewGroupData.projectName, particles: { withFinalConsonant: '์„', withoutFinalConsonant: '๋ฅผ' } })} ํ•จ๊ป˜ํ•œ`; + const REVIEWEE_NAME_GUIDE = `${reviewGroupData.revieweeName}์˜ ๋ฆฌ๋ทฐ ๊ณต๊ฐ„์ด์—์š”`; + + const handleReviewWrite = () => { + if (isUserLoggedIn) return navigate(`/${ROUTE.reviewWriting}/${reviewRequestCode}`); + openModal(MODAL_KEYS.writeOnLogin); + }; + + const handleReviewWriteGuest = () => { navigate(`/${ROUTE.reviewWriting}/${reviewRequestCode}`); }; - const handleReviewListButtonClick = () => { - openModal(MODAL_KEYS.login); + const handleReviewCheck = () => { + // ๋น„ํšŒ์›์ด ๋งŒ๋“  ๊ทธ๋ฃน์ด๋ฉด ๋น„๋ฐ€๋ฒˆํ˜ธ ์ž…๋ ฅ + if (!isMemberLink) return openModal(MODAL_KEYS.content); + // ๋ฆฌ๋ทฐ์–ด๊ฐ€ ๋กœ๊ทธ์ธ ์•ˆ ํ–ˆ์œผ๋ฉด ๋กœ๊ทธ์ธ ๋ชจ๋‹ฌ ๋„์šฐ๊ธฐ + if (!isUserLoggedIn) return openModal(MODAL_KEYS.checkOnLogin); + // ๋ฆฌ๋ทฐ์–ด๊ฐ€ ๋งํฌ ์ฃผ์ธ์ด๋ฉด ๋ชฉ๋ก ํŽ˜์ด์ง€๋กœ ์ด๋™ + if (userProfile?.memberId === reviewGroupData.revieweeId) { + return navigate(`/${ROUTE.reviewList}/${reviewRequestCode}`); + } + return showToast({ + type: 'error', + message: '๋ฆฌ๋ทฐ๋Š” ๋ณธ์ธ๋งŒ ํ™•์ธํ•  ์ˆ˜ ์žˆ์–ด์š”', + durationMS: 3000, + position: 'bottom', + }); }; return ( @@ -54,26 +101,31 @@ const ReviewZonePage = () => { <S.ReviewZoneMainImg src={ReviewZoneIcon} alt="" $height={IMG_HEIGHT} /> </ImgWithSkeleton> <S.ReviewGuideContainer> - <S.ReviewGuide>{`${reviewGroupData.projectName}${calculateParticle({ target: reviewGroupData.projectName, particles: { withFinalConsonant: '์„', withoutFinalConsonant: '๋ฅผ' } })} ํ•จ๊ป˜ํ•œ`}</S.ReviewGuide> - <S.ReviewGuide>{`${reviewGroupData.revieweeName}์˜ ๋ฆฌ๋ทฐ ๊ณต๊ฐ„์ด์—์š”`}</S.ReviewGuide> + <S.ReviewGuide>{PROJECT_NAME_GUIDE}</S.ReviewGuide> + <S.ReviewGuide>{REVIEWEE_NAME_GUIDE}</S.ReviewGuide> </S.ReviewGuideContainer> - <S.ButtonContainer> - <Button styleType="primary" type="button" onClick={handleReviewWritingButtonClick} style={BUTTON_SIZE}> - <S.ButtonTextContainer> - <S.ButtonText>๋ฆฌ๋ทฐ ์“ฐ๊ธฐ</S.ButtonText> - <S.ButtonDescription>์ž‘์„ฑํ•œ ๋ฆฌ๋ทฐ๋Š” ์ต๋ช…์œผ๋กœ ์ œ์ถœ๋ผ์š”</S.ButtonDescription> - </S.ButtonTextContainer> - </Button> - <Button styleType="secondary" type="button" onClick={handleReviewListButtonClick} style={BUTTON_SIZE}> - <S.ButtonTextContainer> - <S.ButtonText>๋ฆฌ๋ทฐ ํ™•์ธํ•˜๊ธฐ</S.ButtonText> - <S.ButtonDescription>๋น„๋ฐ€๋ฒˆํ˜ธ๋กœ ๋‚ด๊ฐ€ ๋ฐ›์€ ๋ฆฌ๋ทฐ๋ฅผ ํ™•์ธํ•  ์ˆ˜ ์žˆ์–ด์š”</S.ButtonDescription> - </S.ButtonTextContainer> - </Button> - </S.ButtonContainer> + <ReviewButton> + <ReviewButton.Write handleClick={handleReviewWrite} /> + {!isUserLoggedIn && <ReviewButton.WriteGuest handleClick={handleReviewWriteGuest} />} + <ReviewButton.Check isGroupLoggedIn={isMemberLink} handleClick={handleReviewCheck} /> + </ReviewButton> {isOpen(MODAL_KEYS.content) && ( <PasswordModal reviewRequestCode={reviewRequestCode} closeModal={() => closeModal(MODAL_KEYS.content)} /> )} + {isOpen(MODAL_KEYS.writeOnLogin) && ( + <LoginRequestModal + action="reviewWrite" + titleType="loginIntent" + closeModal={() => closeModal(MODAL_KEYS.writeOnLogin)} + /> + )} + {isOpen(MODAL_KEYS.checkOnLogin) && ( + <LoginRequestModal + action="reviewCheck" + titleType="loginIntent" + closeModal={() => closeModal(MODAL_KEYS.checkOnLogin)} + /> + )} </S.ReviewZonePage> ); };
Unknown
`reviewWrite`๊ฐ€ `ActionOnLogin`ํƒ€์ž…์˜ ๊ฐ’์ด๋ผ ์—ฌ๊ธฐ์„œ๋„ ์ž๋™์™„์„ฑ์ด ๋˜๋ฉด ์ข‹์„ ๊ฒƒ ๊ฐ™์•„์š”. ํ˜„ `ActionOnLogin` ํƒ€์ž…์˜ ๊ฐ’๋“ค์„ ์ƒ์ˆ˜ํ™”ํ•˜๊ณ , `ActionOnLogin` ํƒ€์ž…์„ ์ƒ์ˆ˜์—์„œ ํŒŒ์ƒ๋œ ํƒ€์ž…์œผ๋กœ ๋งŒ๋“ค๋ฉด ์œ ์ง€๋ณด์ˆ˜๊ฐ€ ํŽธํ•  ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค! (๋‚˜์ค‘์—๋ผ๋„)
@@ -3,49 +3,96 @@ import { useNavigate } from 'react-router'; import { useRecoilState } from 'recoil'; import ReviewZoneIcon from '@/assets/reviewZone.svg'; -import { Button, ImgWithSkeleton } from '@/components'; +import { ImgWithSkeleton, LoginRequestModal } from '@/components'; import { ROUTE } from '@/constants'; -import { useGetReviewGroupData, useModals, useReviewRequestCodeParam } from '@/hooks'; +import { useGetReviewGroupData, useSearchParamAndQuery, useModals, useToastContext } from '@/hooks'; +import { useGetUserProfile } from '@/hooks/oAuth'; import { reviewRequestCodeAtom } from '@/recoil'; import { calculateParticle } from '@/utils'; import PasswordModal from './components/PasswordModal'; +import ReviewButton from './components/ReviewButton'; import * as S from './styles'; const MODAL_KEYS = { content: 'CONTENT_MODAL', - login: 'LOGIN_MODAL', + writeOnLogin: 'LOGIN_MODAL_TO_WRITE', + checkOnLogin: 'LOGIN_MODAL_TO_CHECK', }; const BUTTON_SIZE = { - width: '28rem', + width: '30rem', height: '8.5rem', }; const IMG_HEIGHT = '15rem'; const ReviewZonePage = () => { + const navigate = useNavigate(); + const { isOpen, openModal, closeModal } = useModals(); const [storedReviewRequestCode, setStoredReviewRequestCode] = useRecoilState(reviewRequestCodeAtom); + const { userProfile, isUserLoggedIn } = useGetUserProfile(); + const { showToast } = useToastContext(); - const navigate = useNavigate(); + const { param: reviewRequestCode } = useSearchParamAndQuery({ + paramKey: 'reviewRequestCode', + }); - const { reviewRequestCode } = useReviewRequestCodeParam(); + if (!reviewRequestCode) throw new Error('์œ ํšจํ•˜์ง€ ์•Š์€ ๋ฆฌ๋ทฐ ์š”์ฒญ ์ฝ”๋“œ์˜ˆ์š”'); useEffect(() => { if (!storedReviewRequestCode && reviewRequestCode) { setStoredReviewRequestCode(reviewRequestCode); } }, []); - const { data: reviewGroupData } = useGetReviewGroupData({ reviewRequestCode }); + useEffect(() => { + // ์ฟผ๋ฆฌ ํŒŒ๋ผ๋ฏธํ„ฐ๋กœ ์ „๋‹ฌ๋œ state ํŒŒ์‹ฑ + const params = new URLSearchParams(location.search); + const loginActionParam = params.get('login_action'); + if (!loginActionParam) return; + + // ๋กœ๊ทธ์ธ ์ƒํƒœ๊ฐ€ ์•„๋‹Œ ๊ฒฝ์šฐ ์ฟผ๋ฆฌ ํŒŒ๋ผ๋ฏธํ„ฐ ์ œ๊ฑฐ + if (!isUserLoggedIn) { + params.delete('login_action'); + window.history.replaceState(null, '', `${location.pathname}`); + return; + } + + if (loginActionParam === 'reviewWrite') return handleReviewWrite(); + if (loginActionParam === 'reviewCheck') return handleReviewCheck(); + }, []); - const handleReviewWritingButtonClick = () => { + const { data: reviewGroupData, isMemberLink } = useGetReviewGroupData({ reviewRequestCode }); + + const PROJECT_NAME_GUIDE = `${reviewGroupData.projectName}${calculateParticle({ target: reviewGroupData.projectName, particles: { withFinalConsonant: '์„', withoutFinalConsonant: '๋ฅผ' } })} ํ•จ๊ป˜ํ•œ`; + const REVIEWEE_NAME_GUIDE = `${reviewGroupData.revieweeName}์˜ ๋ฆฌ๋ทฐ ๊ณต๊ฐ„์ด์—์š”`; + + const handleReviewWrite = () => { + if (isUserLoggedIn) return navigate(`/${ROUTE.reviewWriting}/${reviewRequestCode}`); + openModal(MODAL_KEYS.writeOnLogin); + }; + + const handleReviewWriteGuest = () => { navigate(`/${ROUTE.reviewWriting}/${reviewRequestCode}`); }; - const handleReviewListButtonClick = () => { - openModal(MODAL_KEYS.login); + const handleReviewCheck = () => { + // ๋น„ํšŒ์›์ด ๋งŒ๋“  ๊ทธ๋ฃน์ด๋ฉด ๋น„๋ฐ€๋ฒˆํ˜ธ ์ž…๋ ฅ + if (!isMemberLink) return openModal(MODAL_KEYS.content); + // ๋ฆฌ๋ทฐ์–ด๊ฐ€ ๋กœ๊ทธ์ธ ์•ˆ ํ–ˆ์œผ๋ฉด ๋กœ๊ทธ์ธ ๋ชจ๋‹ฌ ๋„์šฐ๊ธฐ + if (!isUserLoggedIn) return openModal(MODAL_KEYS.checkOnLogin); + // ๋ฆฌ๋ทฐ์–ด๊ฐ€ ๋งํฌ ์ฃผ์ธ์ด๋ฉด ๋ชฉ๋ก ํŽ˜์ด์ง€๋กœ ์ด๋™ + if (userProfile?.memberId === reviewGroupData.revieweeId) { + return navigate(`/${ROUTE.reviewList}/${reviewRequestCode}`); + } + return showToast({ + type: 'error', + message: '๋ฆฌ๋ทฐ๋Š” ๋ณธ์ธ๋งŒ ํ™•์ธํ•  ์ˆ˜ ์žˆ์–ด์š”', + durationMS: 3000, + position: 'bottom', + }); }; return ( @@ -54,26 +101,31 @@ const ReviewZonePage = () => { <S.ReviewZoneMainImg src={ReviewZoneIcon} alt="" $height={IMG_HEIGHT} /> </ImgWithSkeleton> <S.ReviewGuideContainer> - <S.ReviewGuide>{`${reviewGroupData.projectName}${calculateParticle({ target: reviewGroupData.projectName, particles: { withFinalConsonant: '์„', withoutFinalConsonant: '๋ฅผ' } })} ํ•จ๊ป˜ํ•œ`}</S.ReviewGuide> - <S.ReviewGuide>{`${reviewGroupData.revieweeName}์˜ ๋ฆฌ๋ทฐ ๊ณต๊ฐ„์ด์—์š”`}</S.ReviewGuide> + <S.ReviewGuide>{PROJECT_NAME_GUIDE}</S.ReviewGuide> + <S.ReviewGuide>{REVIEWEE_NAME_GUIDE}</S.ReviewGuide> </S.ReviewGuideContainer> - <S.ButtonContainer> - <Button styleType="primary" type="button" onClick={handleReviewWritingButtonClick} style={BUTTON_SIZE}> - <S.ButtonTextContainer> - <S.ButtonText>๋ฆฌ๋ทฐ ์“ฐ๊ธฐ</S.ButtonText> - <S.ButtonDescription>์ž‘์„ฑํ•œ ๋ฆฌ๋ทฐ๋Š” ์ต๋ช…์œผ๋กœ ์ œ์ถœ๋ผ์š”</S.ButtonDescription> - </S.ButtonTextContainer> - </Button> - <Button styleType="secondary" type="button" onClick={handleReviewListButtonClick} style={BUTTON_SIZE}> - <S.ButtonTextContainer> - <S.ButtonText>๋ฆฌ๋ทฐ ํ™•์ธํ•˜๊ธฐ</S.ButtonText> - <S.ButtonDescription>๋น„๋ฐ€๋ฒˆํ˜ธ๋กœ ๋‚ด๊ฐ€ ๋ฐ›์€ ๋ฆฌ๋ทฐ๋ฅผ ํ™•์ธํ•  ์ˆ˜ ์žˆ์–ด์š”</S.ButtonDescription> - </S.ButtonTextContainer> - </Button> - </S.ButtonContainer> + <ReviewButton> + <ReviewButton.Write handleClick={handleReviewWrite} /> + {!isUserLoggedIn && <ReviewButton.WriteGuest handleClick={handleReviewWriteGuest} />} + <ReviewButton.Check isGroupLoggedIn={isMemberLink} handleClick={handleReviewCheck} /> + </ReviewButton> {isOpen(MODAL_KEYS.content) && ( <PasswordModal reviewRequestCode={reviewRequestCode} closeModal={() => closeModal(MODAL_KEYS.content)} /> )} + {isOpen(MODAL_KEYS.writeOnLogin) && ( + <LoginRequestModal + action="reviewWrite" + titleType="loginIntent" + closeModal={() => closeModal(MODAL_KEYS.writeOnLogin)} + /> + )} + {isOpen(MODAL_KEYS.checkOnLogin) && ( + <LoginRequestModal + action="reviewCheck" + titleType="loginIntent" + closeModal={() => closeModal(MODAL_KEYS.checkOnLogin)} + /> + )} </S.ReviewZonePage> ); };
Unknown
์ฟผ๋ฆฌ ํŒŒ๋ผ๋ฏธํ„ฐ์— ๋”ฐ๋ผ์„œ ํŽ˜์ด์ง€ ์ด๋™ํ•˜๋Š” useEffect ๋‚ด๋ถ€ ์ฝ”๋“œ๋ฅผ ๋ฐ–์œผ๋กœ ๋ถ„๋ฆฌํ–ˆ์œผ๋ฉด ์ข‹๊ฒ ์–ด์š”.
@@ -3,49 +3,96 @@ import { useNavigate } from 'react-router'; import { useRecoilState } from 'recoil'; import ReviewZoneIcon from '@/assets/reviewZone.svg'; -import { Button, ImgWithSkeleton } from '@/components'; +import { ImgWithSkeleton, LoginRequestModal } from '@/components'; import { ROUTE } from '@/constants'; -import { useGetReviewGroupData, useModals, useReviewRequestCodeParam } from '@/hooks'; +import { useGetReviewGroupData, useSearchParamAndQuery, useModals, useToastContext } from '@/hooks'; +import { useGetUserProfile } from '@/hooks/oAuth'; import { reviewRequestCodeAtom } from '@/recoil'; import { calculateParticle } from '@/utils'; import PasswordModal from './components/PasswordModal'; +import ReviewButton from './components/ReviewButton'; import * as S from './styles'; const MODAL_KEYS = { content: 'CONTENT_MODAL', - login: 'LOGIN_MODAL', + writeOnLogin: 'LOGIN_MODAL_TO_WRITE', + checkOnLogin: 'LOGIN_MODAL_TO_CHECK', }; const BUTTON_SIZE = { - width: '28rem', + width: '30rem', height: '8.5rem', }; const IMG_HEIGHT = '15rem'; const ReviewZonePage = () => { + const navigate = useNavigate(); + const { isOpen, openModal, closeModal } = useModals(); const [storedReviewRequestCode, setStoredReviewRequestCode] = useRecoilState(reviewRequestCodeAtom); + const { userProfile, isUserLoggedIn } = useGetUserProfile(); + const { showToast } = useToastContext(); - const navigate = useNavigate(); + const { param: reviewRequestCode } = useSearchParamAndQuery({ + paramKey: 'reviewRequestCode', + }); - const { reviewRequestCode } = useReviewRequestCodeParam(); + if (!reviewRequestCode) throw new Error('์œ ํšจํ•˜์ง€ ์•Š์€ ๋ฆฌ๋ทฐ ์š”์ฒญ ์ฝ”๋“œ์˜ˆ์š”'); useEffect(() => { if (!storedReviewRequestCode && reviewRequestCode) { setStoredReviewRequestCode(reviewRequestCode); } }, []); - const { data: reviewGroupData } = useGetReviewGroupData({ reviewRequestCode }); + useEffect(() => { + // ์ฟผ๋ฆฌ ํŒŒ๋ผ๋ฏธํ„ฐ๋กœ ์ „๋‹ฌ๋œ state ํŒŒ์‹ฑ + const params = new URLSearchParams(location.search); + const loginActionParam = params.get('login_action'); + if (!loginActionParam) return; + + // ๋กœ๊ทธ์ธ ์ƒํƒœ๊ฐ€ ์•„๋‹Œ ๊ฒฝ์šฐ ์ฟผ๋ฆฌ ํŒŒ๋ผ๋ฏธํ„ฐ ์ œ๊ฑฐ + if (!isUserLoggedIn) { + params.delete('login_action'); + window.history.replaceState(null, '', `${location.pathname}`); + return; + } + + if (loginActionParam === 'reviewWrite') return handleReviewWrite(); + if (loginActionParam === 'reviewCheck') return handleReviewCheck(); + }, []); - const handleReviewWritingButtonClick = () => { + const { data: reviewGroupData, isMemberLink } = useGetReviewGroupData({ reviewRequestCode }); + + const PROJECT_NAME_GUIDE = `${reviewGroupData.projectName}${calculateParticle({ target: reviewGroupData.projectName, particles: { withFinalConsonant: '์„', withoutFinalConsonant: '๋ฅผ' } })} ํ•จ๊ป˜ํ•œ`; + const REVIEWEE_NAME_GUIDE = `${reviewGroupData.revieweeName}์˜ ๋ฆฌ๋ทฐ ๊ณต๊ฐ„์ด์—์š”`; + + const handleReviewWrite = () => { + if (isUserLoggedIn) return navigate(`/${ROUTE.reviewWriting}/${reviewRequestCode}`); + openModal(MODAL_KEYS.writeOnLogin); + }; + + const handleReviewWriteGuest = () => { navigate(`/${ROUTE.reviewWriting}/${reviewRequestCode}`); }; - const handleReviewListButtonClick = () => { - openModal(MODAL_KEYS.login); + const handleReviewCheck = () => { + // ๋น„ํšŒ์›์ด ๋งŒ๋“  ๊ทธ๋ฃน์ด๋ฉด ๋น„๋ฐ€๋ฒˆํ˜ธ ์ž…๋ ฅ + if (!isMemberLink) return openModal(MODAL_KEYS.content); + // ๋ฆฌ๋ทฐ์–ด๊ฐ€ ๋กœ๊ทธ์ธ ์•ˆ ํ–ˆ์œผ๋ฉด ๋กœ๊ทธ์ธ ๋ชจ๋‹ฌ ๋„์šฐ๊ธฐ + if (!isUserLoggedIn) return openModal(MODAL_KEYS.checkOnLogin); + // ๋ฆฌ๋ทฐ์–ด๊ฐ€ ๋งํฌ ์ฃผ์ธ์ด๋ฉด ๋ชฉ๋ก ํŽ˜์ด์ง€๋กœ ์ด๋™ + if (userProfile?.memberId === reviewGroupData.revieweeId) { + return navigate(`/${ROUTE.reviewList}/${reviewRequestCode}`); + } + return showToast({ + type: 'error', + message: '๋ฆฌ๋ทฐ๋Š” ๋ณธ์ธ๋งŒ ํ™•์ธํ•  ์ˆ˜ ์žˆ์–ด์š”', + durationMS: 3000, + position: 'bottom', + }); }; return ( @@ -54,26 +101,31 @@ const ReviewZonePage = () => { <S.ReviewZoneMainImg src={ReviewZoneIcon} alt="" $height={IMG_HEIGHT} /> </ImgWithSkeleton> <S.ReviewGuideContainer> - <S.ReviewGuide>{`${reviewGroupData.projectName}${calculateParticle({ target: reviewGroupData.projectName, particles: { withFinalConsonant: '์„', withoutFinalConsonant: '๋ฅผ' } })} ํ•จ๊ป˜ํ•œ`}</S.ReviewGuide> - <S.ReviewGuide>{`${reviewGroupData.revieweeName}์˜ ๋ฆฌ๋ทฐ ๊ณต๊ฐ„์ด์—์š”`}</S.ReviewGuide> + <S.ReviewGuide>{PROJECT_NAME_GUIDE}</S.ReviewGuide> + <S.ReviewGuide>{REVIEWEE_NAME_GUIDE}</S.ReviewGuide> </S.ReviewGuideContainer> - <S.ButtonContainer> - <Button styleType="primary" type="button" onClick={handleReviewWritingButtonClick} style={BUTTON_SIZE}> - <S.ButtonTextContainer> - <S.ButtonText>๋ฆฌ๋ทฐ ์“ฐ๊ธฐ</S.ButtonText> - <S.ButtonDescription>์ž‘์„ฑํ•œ ๋ฆฌ๋ทฐ๋Š” ์ต๋ช…์œผ๋กœ ์ œ์ถœ๋ผ์š”</S.ButtonDescription> - </S.ButtonTextContainer> - </Button> - <Button styleType="secondary" type="button" onClick={handleReviewListButtonClick} style={BUTTON_SIZE}> - <S.ButtonTextContainer> - <S.ButtonText>๋ฆฌ๋ทฐ ํ™•์ธํ•˜๊ธฐ</S.ButtonText> - <S.ButtonDescription>๋น„๋ฐ€๋ฒˆํ˜ธ๋กœ ๋‚ด๊ฐ€ ๋ฐ›์€ ๋ฆฌ๋ทฐ๋ฅผ ํ™•์ธํ•  ์ˆ˜ ์žˆ์–ด์š”</S.ButtonDescription> - </S.ButtonTextContainer> - </Button> - </S.ButtonContainer> + <ReviewButton> + <ReviewButton.Write handleClick={handleReviewWrite} /> + {!isUserLoggedIn && <ReviewButton.WriteGuest handleClick={handleReviewWriteGuest} />} + <ReviewButton.Check isGroupLoggedIn={isMemberLink} handleClick={handleReviewCheck} /> + </ReviewButton> {isOpen(MODAL_KEYS.content) && ( <PasswordModal reviewRequestCode={reviewRequestCode} closeModal={() => closeModal(MODAL_KEYS.content)} /> )} + {isOpen(MODAL_KEYS.writeOnLogin) && ( + <LoginRequestModal + action="reviewWrite" + titleType="loginIntent" + closeModal={() => closeModal(MODAL_KEYS.writeOnLogin)} + /> + )} + {isOpen(MODAL_KEYS.checkOnLogin) && ( + <LoginRequestModal + action="reviewCheck" + titleType="loginIntent" + closeModal={() => closeModal(MODAL_KEYS.checkOnLogin)} + /> + )} </S.ReviewZonePage> ); };
Unknown
๋ฆฌ๋ทฐ ์—ฐ๊ฒฐ ํŽ˜์ด์ง€ ๋ถ„๊ธฐ ์ฒ˜๋ฆฌ๋กœ ์ธํ•ด, jsx ์ฝ”๋“œ๊ฐ€ ๋งŽ์•„์ง€๋‹ค๋ณด๋‹ˆ, ํ”„๋กœ์ ํŠธ ์ด๋ฆ„์— ๋”ฐ๋ฅธ ์กฐ์‚ฌ ์ฒ˜๋ฆฌ ์ฝ”๋“œ ๊ฐ€๋…์„ฑ ๋ถ€๋ถ„์„ ์‹ ๊ฒฝ์จ์•ผ๊ฒ ์–ด์š”. jsx๊ฐ€ ์•„๋‹Œ ์ƒ์œ„์—์„œ ๋ณ€์ˆ˜๋กœ ์ฒ˜๋ฆฌํ•˜๋Š” ๊ฒƒ์€ ์–ด๋–จ๊นŒ์š”?
@@ -3,49 +3,96 @@ import { useNavigate } from 'react-router'; import { useRecoilState } from 'recoil'; import ReviewZoneIcon from '@/assets/reviewZone.svg'; -import { Button, ImgWithSkeleton } from '@/components'; +import { ImgWithSkeleton, LoginRequestModal } from '@/components'; import { ROUTE } from '@/constants'; -import { useGetReviewGroupData, useModals, useReviewRequestCodeParam } from '@/hooks'; +import { useGetReviewGroupData, useSearchParamAndQuery, useModals, useToastContext } from '@/hooks'; +import { useGetUserProfile } from '@/hooks/oAuth'; import { reviewRequestCodeAtom } from '@/recoil'; import { calculateParticle } from '@/utils'; import PasswordModal from './components/PasswordModal'; +import ReviewButton from './components/ReviewButton'; import * as S from './styles'; const MODAL_KEYS = { content: 'CONTENT_MODAL', - login: 'LOGIN_MODAL', + writeOnLogin: 'LOGIN_MODAL_TO_WRITE', + checkOnLogin: 'LOGIN_MODAL_TO_CHECK', }; const BUTTON_SIZE = { - width: '28rem', + width: '30rem', height: '8.5rem', }; const IMG_HEIGHT = '15rem'; const ReviewZonePage = () => { + const navigate = useNavigate(); + const { isOpen, openModal, closeModal } = useModals(); const [storedReviewRequestCode, setStoredReviewRequestCode] = useRecoilState(reviewRequestCodeAtom); + const { userProfile, isUserLoggedIn } = useGetUserProfile(); + const { showToast } = useToastContext(); - const navigate = useNavigate(); + const { param: reviewRequestCode } = useSearchParamAndQuery({ + paramKey: 'reviewRequestCode', + }); - const { reviewRequestCode } = useReviewRequestCodeParam(); + if (!reviewRequestCode) throw new Error('์œ ํšจํ•˜์ง€ ์•Š์€ ๋ฆฌ๋ทฐ ์š”์ฒญ ์ฝ”๋“œ์˜ˆ์š”'); useEffect(() => { if (!storedReviewRequestCode && reviewRequestCode) { setStoredReviewRequestCode(reviewRequestCode); } }, []); - const { data: reviewGroupData } = useGetReviewGroupData({ reviewRequestCode }); + useEffect(() => { + // ์ฟผ๋ฆฌ ํŒŒ๋ผ๋ฏธํ„ฐ๋กœ ์ „๋‹ฌ๋œ state ํŒŒ์‹ฑ + const params = new URLSearchParams(location.search); + const loginActionParam = params.get('login_action'); + if (!loginActionParam) return; + + // ๋กœ๊ทธ์ธ ์ƒํƒœ๊ฐ€ ์•„๋‹Œ ๊ฒฝ์šฐ ์ฟผ๋ฆฌ ํŒŒ๋ผ๋ฏธํ„ฐ ์ œ๊ฑฐ + if (!isUserLoggedIn) { + params.delete('login_action'); + window.history.replaceState(null, '', `${location.pathname}`); + return; + } + + if (loginActionParam === 'reviewWrite') return handleReviewWrite(); + if (loginActionParam === 'reviewCheck') return handleReviewCheck(); + }, []); - const handleReviewWritingButtonClick = () => { + const { data: reviewGroupData, isMemberLink } = useGetReviewGroupData({ reviewRequestCode }); + + const PROJECT_NAME_GUIDE = `${reviewGroupData.projectName}${calculateParticle({ target: reviewGroupData.projectName, particles: { withFinalConsonant: '์„', withoutFinalConsonant: '๋ฅผ' } })} ํ•จ๊ป˜ํ•œ`; + const REVIEWEE_NAME_GUIDE = `${reviewGroupData.revieweeName}์˜ ๋ฆฌ๋ทฐ ๊ณต๊ฐ„์ด์—์š”`; + + const handleReviewWrite = () => { + if (isUserLoggedIn) return navigate(`/${ROUTE.reviewWriting}/${reviewRequestCode}`); + openModal(MODAL_KEYS.writeOnLogin); + }; + + const handleReviewWriteGuest = () => { navigate(`/${ROUTE.reviewWriting}/${reviewRequestCode}`); }; - const handleReviewListButtonClick = () => { - openModal(MODAL_KEYS.login); + const handleReviewCheck = () => { + // ๋น„ํšŒ์›์ด ๋งŒ๋“  ๊ทธ๋ฃน์ด๋ฉด ๋น„๋ฐ€๋ฒˆํ˜ธ ์ž…๋ ฅ + if (!isMemberLink) return openModal(MODAL_KEYS.content); + // ๋ฆฌ๋ทฐ์–ด๊ฐ€ ๋กœ๊ทธ์ธ ์•ˆ ํ–ˆ์œผ๋ฉด ๋กœ๊ทธ์ธ ๋ชจ๋‹ฌ ๋„์šฐ๊ธฐ + if (!isUserLoggedIn) return openModal(MODAL_KEYS.checkOnLogin); + // ๋ฆฌ๋ทฐ์–ด๊ฐ€ ๋งํฌ ์ฃผ์ธ์ด๋ฉด ๋ชฉ๋ก ํŽ˜์ด์ง€๋กœ ์ด๋™ + if (userProfile?.memberId === reviewGroupData.revieweeId) { + return navigate(`/${ROUTE.reviewList}/${reviewRequestCode}`); + } + return showToast({ + type: 'error', + message: '๋ฆฌ๋ทฐ๋Š” ๋ณธ์ธ๋งŒ ํ™•์ธํ•  ์ˆ˜ ์žˆ์–ด์š”', + durationMS: 3000, + position: 'bottom', + }); }; return ( @@ -54,26 +101,31 @@ const ReviewZonePage = () => { <S.ReviewZoneMainImg src={ReviewZoneIcon} alt="" $height={IMG_HEIGHT} /> </ImgWithSkeleton> <S.ReviewGuideContainer> - <S.ReviewGuide>{`${reviewGroupData.projectName}${calculateParticle({ target: reviewGroupData.projectName, particles: { withFinalConsonant: '์„', withoutFinalConsonant: '๋ฅผ' } })} ํ•จ๊ป˜ํ•œ`}</S.ReviewGuide> - <S.ReviewGuide>{`${reviewGroupData.revieweeName}์˜ ๋ฆฌ๋ทฐ ๊ณต๊ฐ„์ด์—์š”`}</S.ReviewGuide> + <S.ReviewGuide>{PROJECT_NAME_GUIDE}</S.ReviewGuide> + <S.ReviewGuide>{REVIEWEE_NAME_GUIDE}</S.ReviewGuide> </S.ReviewGuideContainer> - <S.ButtonContainer> - <Button styleType="primary" type="button" onClick={handleReviewWritingButtonClick} style={BUTTON_SIZE}> - <S.ButtonTextContainer> - <S.ButtonText>๋ฆฌ๋ทฐ ์“ฐ๊ธฐ</S.ButtonText> - <S.ButtonDescription>์ž‘์„ฑํ•œ ๋ฆฌ๋ทฐ๋Š” ์ต๋ช…์œผ๋กœ ์ œ์ถœ๋ผ์š”</S.ButtonDescription> - </S.ButtonTextContainer> - </Button> - <Button styleType="secondary" type="button" onClick={handleReviewListButtonClick} style={BUTTON_SIZE}> - <S.ButtonTextContainer> - <S.ButtonText>๋ฆฌ๋ทฐ ํ™•์ธํ•˜๊ธฐ</S.ButtonText> - <S.ButtonDescription>๋น„๋ฐ€๋ฒˆํ˜ธ๋กœ ๋‚ด๊ฐ€ ๋ฐ›์€ ๋ฆฌ๋ทฐ๋ฅผ ํ™•์ธํ•  ์ˆ˜ ์žˆ์–ด์š”</S.ButtonDescription> - </S.ButtonTextContainer> - </Button> - </S.ButtonContainer> + <ReviewButton> + <ReviewButton.Write handleClick={handleReviewWrite} /> + {!isUserLoggedIn && <ReviewButton.WriteGuest handleClick={handleReviewWriteGuest} />} + <ReviewButton.Check isGroupLoggedIn={isMemberLink} handleClick={handleReviewCheck} /> + </ReviewButton> {isOpen(MODAL_KEYS.content) && ( <PasswordModal reviewRequestCode={reviewRequestCode} closeModal={() => closeModal(MODAL_KEYS.content)} /> )} + {isOpen(MODAL_KEYS.writeOnLogin) && ( + <LoginRequestModal + action="reviewWrite" + titleType="loginIntent" + closeModal={() => closeModal(MODAL_KEYS.writeOnLogin)} + /> + )} + {isOpen(MODAL_KEYS.checkOnLogin) && ( + <LoginRequestModal + action="reviewCheck" + titleType="loginIntent" + closeModal={() => closeModal(MODAL_KEYS.checkOnLogin)} + /> + )} </S.ReviewZonePage> ); };
Unknown
ํ•˜์œ„ ์ปดํฌ๋„ŒํŠธ๋กœ ๋‚˜๋ˆˆ๋‹ค๋ฉด, ๋ถ„๋ฆฌ ์ฒ˜๋ฆฌ๋กœ ๋ณต์žกํ•œ ๋ฆฌ๋ทฐ ์—ฐ๊ฒฐ ํŽ˜์ด์ง€์˜ ์—ญํ• ์ด ํ•˜์œ„ ์ปดํฌ๋„ŒํŠธ๋ณ„๋กœ ํ•œ ๋ˆˆ์— ์ž˜ ๋ณด์ผ ๊ฑฐ ๊ฐ™์•„์š”.
@@ -1,5 +1,7 @@ import { ReviewGroupData } from '@/types'; +import { MOCK_USER_PROFILE } from './userProfileData'; + export const VALIDATED_PASSWORD = '1234'; export const MOCK_AUTH_TOKEN_NAME = 'mockAuthToken'; @@ -14,12 +16,18 @@ export const bothCookie = [MOCK_AUTH_TOKEN_NAME, MOCK_LOGIN_TOKEN_NAME]; */ // ๋ณ€์ˆ˜๋ช…์ด ์นด๋ฉœ ์ผ€์ด์Šค์ธ ์ด์œ ๋Š” ํšŒ์›/๋น„ํšŒ์›์— ๋”ฐ๋ผ revieweeId๊ฐ€ ๋‹ฌ๋ผ์ง€๊ธฐ ๋•Œ๋ฌธ์— reviewRequestCode๋ณด๊ณ  ํŒ๋‹จํ•ด์„œ ํšŒ์›์ด๋ฉด number, ๋น„ํšŒ์›์ด๋ฉด null๋กœ ์„ค์ • -export const REVIEW_GROUP_DATA: ReviewGroupData = { - revieweeId: 1, +export const MEMBER_REVIEW_GROUP_DATA: ReviewGroupData = { + revieweeId: MOCK_USER_PROFILE.memberId, //๐Ÿ’ก ๋ณธ์ธ์ด ๋งŒ๋“  ๋ฆฌ๋ทฐ ๋งํฌ๊ฐ€ ์•„๋‹ ๋•Œ ํ† ์ŠคํŠธ ๊ธฐ๋Šฅ์„ ํ™•์ธํ•˜๊ณ  ์‹ถ๋‹ค๋ฉด ๋‹ค๋ฅธ ๋ฆฌ๋ทฐ ์•„์ด๋””๋ฅผ ๋„ฃ์–ด์„œ ํ™•์ธํ•ด๋ณด์„ธ์š” revieweeName: '๋ฐ”๋‹ค', projectName: '2024-review-me', }; +export const NONMEMBER_REVIEW_GROUP_DATA: ReviewGroupData = { + revieweeId: null, + revieweeName: '์†๋‹˜', + projectName: '2024-review-me', +}; + /**๋ฆฌ๋ทฐ ์—ฐ๊ฒฐ ํŽ˜์ด์ง€์—์„œ ์œ ํšจํ•œ reviewRequestCode */ export const VALID_REVIEW_REQUEST_CODE = { nonMember: `ABCD1234`,
TypeScript
์˜๋ฏธ ์žˆ๋Š” ๊ฐ’์€ ์•„๋‹™๋‹ˆ๋‹ค๐Ÿ˜… ๋ฆฌ๋ทฐ ํ™•์ธ ์‹œ, ๋ณธ์ธ์ด ๋งŒ๋“  ๋งํฌ์ธ์ง€ ์•„๋‹Œ์ง€ ํŒ๋‹จํ•˜๋Š” ๊ณผ์ •์—์„œ ๊ฐ’์„ ๋ฐ”๊พธ๋ฉด์„œ ๋น„๊ตํ•˜๋‹ค๊ฐ€ ๊ทธ๋ƒฅ ์ปค๋ฐ‹๋๋„ค์š”. ๋ฐ”๋‹ค๊ฐ€ ์ƒ์ˆ˜ํ™” ์ž‘์—…ํ•ด์ฃผ์—ˆ์Šต๋‹ˆ๋‹ค๐Ÿ™๐Ÿป
@@ -3,49 +3,96 @@ import { useNavigate } from 'react-router'; import { useRecoilState } from 'recoil'; import ReviewZoneIcon from '@/assets/reviewZone.svg'; -import { Button, ImgWithSkeleton } from '@/components'; +import { ImgWithSkeleton, LoginRequestModal } from '@/components'; import { ROUTE } from '@/constants'; -import { useGetReviewGroupData, useModals, useReviewRequestCodeParam } from '@/hooks'; +import { useGetReviewGroupData, useSearchParamAndQuery, useModals, useToastContext } from '@/hooks'; +import { useGetUserProfile } from '@/hooks/oAuth'; import { reviewRequestCodeAtom } from '@/recoil'; import { calculateParticle } from '@/utils'; import PasswordModal from './components/PasswordModal'; +import ReviewButton from './components/ReviewButton'; import * as S from './styles'; const MODAL_KEYS = { content: 'CONTENT_MODAL', - login: 'LOGIN_MODAL', + writeOnLogin: 'LOGIN_MODAL_TO_WRITE', + checkOnLogin: 'LOGIN_MODAL_TO_CHECK', }; const BUTTON_SIZE = { - width: '28rem', + width: '30rem', height: '8.5rem', }; const IMG_HEIGHT = '15rem'; const ReviewZonePage = () => { + const navigate = useNavigate(); + const { isOpen, openModal, closeModal } = useModals(); const [storedReviewRequestCode, setStoredReviewRequestCode] = useRecoilState(reviewRequestCodeAtom); + const { userProfile, isUserLoggedIn } = useGetUserProfile(); + const { showToast } = useToastContext(); - const navigate = useNavigate(); + const { param: reviewRequestCode } = useSearchParamAndQuery({ + paramKey: 'reviewRequestCode', + }); - const { reviewRequestCode } = useReviewRequestCodeParam(); + if (!reviewRequestCode) throw new Error('์œ ํšจํ•˜์ง€ ์•Š์€ ๋ฆฌ๋ทฐ ์š”์ฒญ ์ฝ”๋“œ์˜ˆ์š”'); useEffect(() => { if (!storedReviewRequestCode && reviewRequestCode) { setStoredReviewRequestCode(reviewRequestCode); } }, []); - const { data: reviewGroupData } = useGetReviewGroupData({ reviewRequestCode }); + useEffect(() => { + // ์ฟผ๋ฆฌ ํŒŒ๋ผ๋ฏธํ„ฐ๋กœ ์ „๋‹ฌ๋œ state ํŒŒ์‹ฑ + const params = new URLSearchParams(location.search); + const loginActionParam = params.get('login_action'); + if (!loginActionParam) return; + + // ๋กœ๊ทธ์ธ ์ƒํƒœ๊ฐ€ ์•„๋‹Œ ๊ฒฝ์šฐ ์ฟผ๋ฆฌ ํŒŒ๋ผ๋ฏธํ„ฐ ์ œ๊ฑฐ + if (!isUserLoggedIn) { + params.delete('login_action'); + window.history.replaceState(null, '', `${location.pathname}`); + return; + } + + if (loginActionParam === 'reviewWrite') return handleReviewWrite(); + if (loginActionParam === 'reviewCheck') return handleReviewCheck(); + }, []); - const handleReviewWritingButtonClick = () => { + const { data: reviewGroupData, isMemberLink } = useGetReviewGroupData({ reviewRequestCode }); + + const PROJECT_NAME_GUIDE = `${reviewGroupData.projectName}${calculateParticle({ target: reviewGroupData.projectName, particles: { withFinalConsonant: '์„', withoutFinalConsonant: '๋ฅผ' } })} ํ•จ๊ป˜ํ•œ`; + const REVIEWEE_NAME_GUIDE = `${reviewGroupData.revieweeName}์˜ ๋ฆฌ๋ทฐ ๊ณต๊ฐ„์ด์—์š”`; + + const handleReviewWrite = () => { + if (isUserLoggedIn) return navigate(`/${ROUTE.reviewWriting}/${reviewRequestCode}`); + openModal(MODAL_KEYS.writeOnLogin); + }; + + const handleReviewWriteGuest = () => { navigate(`/${ROUTE.reviewWriting}/${reviewRequestCode}`); }; - const handleReviewListButtonClick = () => { - openModal(MODAL_KEYS.login); + const handleReviewCheck = () => { + // ๋น„ํšŒ์›์ด ๋งŒ๋“  ๊ทธ๋ฃน์ด๋ฉด ๋น„๋ฐ€๋ฒˆํ˜ธ ์ž…๋ ฅ + if (!isMemberLink) return openModal(MODAL_KEYS.content); + // ๋ฆฌ๋ทฐ์–ด๊ฐ€ ๋กœ๊ทธ์ธ ์•ˆ ํ–ˆ์œผ๋ฉด ๋กœ๊ทธ์ธ ๋ชจ๋‹ฌ ๋„์šฐ๊ธฐ + if (!isUserLoggedIn) return openModal(MODAL_KEYS.checkOnLogin); + // ๋ฆฌ๋ทฐ์–ด๊ฐ€ ๋งํฌ ์ฃผ์ธ์ด๋ฉด ๋ชฉ๋ก ํŽ˜์ด์ง€๋กœ ์ด๋™ + if (userProfile?.memberId === reviewGroupData.revieweeId) { + return navigate(`/${ROUTE.reviewList}/${reviewRequestCode}`); + } + return showToast({ + type: 'error', + message: '๋ฆฌ๋ทฐ๋Š” ๋ณธ์ธ๋งŒ ํ™•์ธํ•  ์ˆ˜ ์žˆ์–ด์š”', + durationMS: 3000, + position: 'bottom', + }); }; return ( @@ -54,26 +101,31 @@ const ReviewZonePage = () => { <S.ReviewZoneMainImg src={ReviewZoneIcon} alt="" $height={IMG_HEIGHT} /> </ImgWithSkeleton> <S.ReviewGuideContainer> - <S.ReviewGuide>{`${reviewGroupData.projectName}${calculateParticle({ target: reviewGroupData.projectName, particles: { withFinalConsonant: '์„', withoutFinalConsonant: '๋ฅผ' } })} ํ•จ๊ป˜ํ•œ`}</S.ReviewGuide> - <S.ReviewGuide>{`${reviewGroupData.revieweeName}์˜ ๋ฆฌ๋ทฐ ๊ณต๊ฐ„์ด์—์š”`}</S.ReviewGuide> + <S.ReviewGuide>{PROJECT_NAME_GUIDE}</S.ReviewGuide> + <S.ReviewGuide>{REVIEWEE_NAME_GUIDE}</S.ReviewGuide> </S.ReviewGuideContainer> - <S.ButtonContainer> - <Button styleType="primary" type="button" onClick={handleReviewWritingButtonClick} style={BUTTON_SIZE}> - <S.ButtonTextContainer> - <S.ButtonText>๋ฆฌ๋ทฐ ์“ฐ๊ธฐ</S.ButtonText> - <S.ButtonDescription>์ž‘์„ฑํ•œ ๋ฆฌ๋ทฐ๋Š” ์ต๋ช…์œผ๋กœ ์ œ์ถœ๋ผ์š”</S.ButtonDescription> - </S.ButtonTextContainer> - </Button> - <Button styleType="secondary" type="button" onClick={handleReviewListButtonClick} style={BUTTON_SIZE}> - <S.ButtonTextContainer> - <S.ButtonText>๋ฆฌ๋ทฐ ํ™•์ธํ•˜๊ธฐ</S.ButtonText> - <S.ButtonDescription>๋น„๋ฐ€๋ฒˆํ˜ธ๋กœ ๋‚ด๊ฐ€ ๋ฐ›์€ ๋ฆฌ๋ทฐ๋ฅผ ํ™•์ธํ•  ์ˆ˜ ์žˆ์–ด์š”</S.ButtonDescription> - </S.ButtonTextContainer> - </Button> - </S.ButtonContainer> + <ReviewButton> + <ReviewButton.Write handleClick={handleReviewWrite} /> + {!isUserLoggedIn && <ReviewButton.WriteGuest handleClick={handleReviewWriteGuest} />} + <ReviewButton.Check isGroupLoggedIn={isMemberLink} handleClick={handleReviewCheck} /> + </ReviewButton> {isOpen(MODAL_KEYS.content) && ( <PasswordModal reviewRequestCode={reviewRequestCode} closeModal={() => closeModal(MODAL_KEYS.content)} /> )} + {isOpen(MODAL_KEYS.writeOnLogin) && ( + <LoginRequestModal + action="reviewWrite" + titleType="loginIntent" + closeModal={() => closeModal(MODAL_KEYS.writeOnLogin)} + /> + )} + {isOpen(MODAL_KEYS.checkOnLogin) && ( + <LoginRequestModal + action="reviewCheck" + titleType="loginIntent" + closeModal={() => closeModal(MODAL_KEYS.checkOnLogin)} + /> + )} </S.ReviewZonePage> ); };
Unknown
๋ฐ˜์˜ํ–ˆ์Šต๋‹ˆ๋‹ค๐Ÿ‘๐Ÿป
@@ -3,49 +3,96 @@ import { useNavigate } from 'react-router'; import { useRecoilState } from 'recoil'; import ReviewZoneIcon from '@/assets/reviewZone.svg'; -import { Button, ImgWithSkeleton } from '@/components'; +import { ImgWithSkeleton, LoginRequestModal } from '@/components'; import { ROUTE } from '@/constants'; -import { useGetReviewGroupData, useModals, useReviewRequestCodeParam } from '@/hooks'; +import { useGetReviewGroupData, useSearchParamAndQuery, useModals, useToastContext } from '@/hooks'; +import { useGetUserProfile } from '@/hooks/oAuth'; import { reviewRequestCodeAtom } from '@/recoil'; import { calculateParticle } from '@/utils'; import PasswordModal from './components/PasswordModal'; +import ReviewButton from './components/ReviewButton'; import * as S from './styles'; const MODAL_KEYS = { content: 'CONTENT_MODAL', - login: 'LOGIN_MODAL', + writeOnLogin: 'LOGIN_MODAL_TO_WRITE', + checkOnLogin: 'LOGIN_MODAL_TO_CHECK', }; const BUTTON_SIZE = { - width: '28rem', + width: '30rem', height: '8.5rem', }; const IMG_HEIGHT = '15rem'; const ReviewZonePage = () => { + const navigate = useNavigate(); + const { isOpen, openModal, closeModal } = useModals(); const [storedReviewRequestCode, setStoredReviewRequestCode] = useRecoilState(reviewRequestCodeAtom); + const { userProfile, isUserLoggedIn } = useGetUserProfile(); + const { showToast } = useToastContext(); - const navigate = useNavigate(); + const { param: reviewRequestCode } = useSearchParamAndQuery({ + paramKey: 'reviewRequestCode', + }); - const { reviewRequestCode } = useReviewRequestCodeParam(); + if (!reviewRequestCode) throw new Error('์œ ํšจํ•˜์ง€ ์•Š์€ ๋ฆฌ๋ทฐ ์š”์ฒญ ์ฝ”๋“œ์˜ˆ์š”'); useEffect(() => { if (!storedReviewRequestCode && reviewRequestCode) { setStoredReviewRequestCode(reviewRequestCode); } }, []); - const { data: reviewGroupData } = useGetReviewGroupData({ reviewRequestCode }); + useEffect(() => { + // ์ฟผ๋ฆฌ ํŒŒ๋ผ๋ฏธํ„ฐ๋กœ ์ „๋‹ฌ๋œ state ํŒŒ์‹ฑ + const params = new URLSearchParams(location.search); + const loginActionParam = params.get('login_action'); + if (!loginActionParam) return; + + // ๋กœ๊ทธ์ธ ์ƒํƒœ๊ฐ€ ์•„๋‹Œ ๊ฒฝ์šฐ ์ฟผ๋ฆฌ ํŒŒ๋ผ๋ฏธํ„ฐ ์ œ๊ฑฐ + if (!isUserLoggedIn) { + params.delete('login_action'); + window.history.replaceState(null, '', `${location.pathname}`); + return; + } + + if (loginActionParam === 'reviewWrite') return handleReviewWrite(); + if (loginActionParam === 'reviewCheck') return handleReviewCheck(); + }, []); - const handleReviewWritingButtonClick = () => { + const { data: reviewGroupData, isMemberLink } = useGetReviewGroupData({ reviewRequestCode }); + + const PROJECT_NAME_GUIDE = `${reviewGroupData.projectName}${calculateParticle({ target: reviewGroupData.projectName, particles: { withFinalConsonant: '์„', withoutFinalConsonant: '๋ฅผ' } })} ํ•จ๊ป˜ํ•œ`; + const REVIEWEE_NAME_GUIDE = `${reviewGroupData.revieweeName}์˜ ๋ฆฌ๋ทฐ ๊ณต๊ฐ„์ด์—์š”`; + + const handleReviewWrite = () => { + if (isUserLoggedIn) return navigate(`/${ROUTE.reviewWriting}/${reviewRequestCode}`); + openModal(MODAL_KEYS.writeOnLogin); + }; + + const handleReviewWriteGuest = () => { navigate(`/${ROUTE.reviewWriting}/${reviewRequestCode}`); }; - const handleReviewListButtonClick = () => { - openModal(MODAL_KEYS.login); + const handleReviewCheck = () => { + // ๋น„ํšŒ์›์ด ๋งŒ๋“  ๊ทธ๋ฃน์ด๋ฉด ๋น„๋ฐ€๋ฒˆํ˜ธ ์ž…๋ ฅ + if (!isMemberLink) return openModal(MODAL_KEYS.content); + // ๋ฆฌ๋ทฐ์–ด๊ฐ€ ๋กœ๊ทธ์ธ ์•ˆ ํ–ˆ์œผ๋ฉด ๋กœ๊ทธ์ธ ๋ชจ๋‹ฌ ๋„์šฐ๊ธฐ + if (!isUserLoggedIn) return openModal(MODAL_KEYS.checkOnLogin); + // ๋ฆฌ๋ทฐ์–ด๊ฐ€ ๋งํฌ ์ฃผ์ธ์ด๋ฉด ๋ชฉ๋ก ํŽ˜์ด์ง€๋กœ ์ด๋™ + if (userProfile?.memberId === reviewGroupData.revieweeId) { + return navigate(`/${ROUTE.reviewList}/${reviewRequestCode}`); + } + return showToast({ + type: 'error', + message: '๋ฆฌ๋ทฐ๋Š” ๋ณธ์ธ๋งŒ ํ™•์ธํ•  ์ˆ˜ ์žˆ์–ด์š”', + durationMS: 3000, + position: 'bottom', + }); }; return ( @@ -54,26 +101,31 @@ const ReviewZonePage = () => { <S.ReviewZoneMainImg src={ReviewZoneIcon} alt="" $height={IMG_HEIGHT} /> </ImgWithSkeleton> <S.ReviewGuideContainer> - <S.ReviewGuide>{`${reviewGroupData.projectName}${calculateParticle({ target: reviewGroupData.projectName, particles: { withFinalConsonant: '์„', withoutFinalConsonant: '๋ฅผ' } })} ํ•จ๊ป˜ํ•œ`}</S.ReviewGuide> - <S.ReviewGuide>{`${reviewGroupData.revieweeName}์˜ ๋ฆฌ๋ทฐ ๊ณต๊ฐ„์ด์—์š”`}</S.ReviewGuide> + <S.ReviewGuide>{PROJECT_NAME_GUIDE}</S.ReviewGuide> + <S.ReviewGuide>{REVIEWEE_NAME_GUIDE}</S.ReviewGuide> </S.ReviewGuideContainer> - <S.ButtonContainer> - <Button styleType="primary" type="button" onClick={handleReviewWritingButtonClick} style={BUTTON_SIZE}> - <S.ButtonTextContainer> - <S.ButtonText>๋ฆฌ๋ทฐ ์“ฐ๊ธฐ</S.ButtonText> - <S.ButtonDescription>์ž‘์„ฑํ•œ ๋ฆฌ๋ทฐ๋Š” ์ต๋ช…์œผ๋กœ ์ œ์ถœ๋ผ์š”</S.ButtonDescription> - </S.ButtonTextContainer> - </Button> - <Button styleType="secondary" type="button" onClick={handleReviewListButtonClick} style={BUTTON_SIZE}> - <S.ButtonTextContainer> - <S.ButtonText>๋ฆฌ๋ทฐ ํ™•์ธํ•˜๊ธฐ</S.ButtonText> - <S.ButtonDescription>๋น„๋ฐ€๋ฒˆํ˜ธ๋กœ ๋‚ด๊ฐ€ ๋ฐ›์€ ๋ฆฌ๋ทฐ๋ฅผ ํ™•์ธํ•  ์ˆ˜ ์žˆ์–ด์š”</S.ButtonDescription> - </S.ButtonTextContainer> - </Button> - </S.ButtonContainer> + <ReviewButton> + <ReviewButton.Write handleClick={handleReviewWrite} /> + {!isUserLoggedIn && <ReviewButton.WriteGuest handleClick={handleReviewWriteGuest} />} + <ReviewButton.Check isGroupLoggedIn={isMemberLink} handleClick={handleReviewCheck} /> + </ReviewButton> {isOpen(MODAL_KEYS.content) && ( <PasswordModal reviewRequestCode={reviewRequestCode} closeModal={() => closeModal(MODAL_KEYS.content)} /> )} + {isOpen(MODAL_KEYS.writeOnLogin) && ( + <LoginRequestModal + action="reviewWrite" + titleType="loginIntent" + closeModal={() => closeModal(MODAL_KEYS.writeOnLogin)} + /> + )} + {isOpen(MODAL_KEYS.checkOnLogin) && ( + <LoginRequestModal + action="reviewCheck" + titleType="loginIntent" + closeModal={() => closeModal(MODAL_KEYS.checkOnLogin)} + /> + )} </S.ReviewZonePage> ); };
Unknown
์ €๋„ ๊ทธ๋ฃน ๋ณด๋‹ค๋Š” ๋งํฌ๊ฐ€ ์กฐ๊ธˆ ๋” ์ง๊ด€์ ์œผ๋กœ ์™€๋‹ฟ์•„์„œ, `isMemberLink`๋กœ ์ˆ˜์ •ํ–ˆ์Šต๋‹ˆ๋‹ค. ๋‹ค๋งŒ ๊ด€๋ จ API ํ•จ์ˆ˜ ๋ฐ ํƒ€์ž…๋ช…์ด ๋ชจ๋‘ ReviewGroup์œผ๋กœ ํ‘œ๊ธฐ๋˜์–ด ์žˆ์–ด์„œ, `ReviewGroup`์ด๋ผ๋Š” ํ‘œ๊ธฐ ์ž์ฒด๋ฅผ `ReviewLink`๋กœ ํ†ต์ผํ•˜๋Š” ๊ฒŒ ์ข‹์„ ๊ฒƒ ๊ฐ™์•„์š”. ์ด๊ฑด ๋ชจ๋‘์˜ ์˜๊ฒฌ์„ ๋“ค์–ด๋ณด๊ณ  ์‹ถ์–ด์„œ ์šฐ์„  ๋ฐ˜์˜ํ•˜์ง€ ์•Š๊ฒ ์Šต๋‹ˆ๋‹ค.
@@ -3,49 +3,96 @@ import { useNavigate } from 'react-router'; import { useRecoilState } from 'recoil'; import ReviewZoneIcon from '@/assets/reviewZone.svg'; -import { Button, ImgWithSkeleton } from '@/components'; +import { ImgWithSkeleton, LoginRequestModal } from '@/components'; import { ROUTE } from '@/constants'; -import { useGetReviewGroupData, useModals, useReviewRequestCodeParam } from '@/hooks'; +import { useGetReviewGroupData, useSearchParamAndQuery, useModals, useToastContext } from '@/hooks'; +import { useGetUserProfile } from '@/hooks/oAuth'; import { reviewRequestCodeAtom } from '@/recoil'; import { calculateParticle } from '@/utils'; import PasswordModal from './components/PasswordModal'; +import ReviewButton from './components/ReviewButton'; import * as S from './styles'; const MODAL_KEYS = { content: 'CONTENT_MODAL', - login: 'LOGIN_MODAL', + writeOnLogin: 'LOGIN_MODAL_TO_WRITE', + checkOnLogin: 'LOGIN_MODAL_TO_CHECK', }; const BUTTON_SIZE = { - width: '28rem', + width: '30rem', height: '8.5rem', }; const IMG_HEIGHT = '15rem'; const ReviewZonePage = () => { + const navigate = useNavigate(); + const { isOpen, openModal, closeModal } = useModals(); const [storedReviewRequestCode, setStoredReviewRequestCode] = useRecoilState(reviewRequestCodeAtom); + const { userProfile, isUserLoggedIn } = useGetUserProfile(); + const { showToast } = useToastContext(); - const navigate = useNavigate(); + const { param: reviewRequestCode } = useSearchParamAndQuery({ + paramKey: 'reviewRequestCode', + }); - const { reviewRequestCode } = useReviewRequestCodeParam(); + if (!reviewRequestCode) throw new Error('์œ ํšจํ•˜์ง€ ์•Š์€ ๋ฆฌ๋ทฐ ์š”์ฒญ ์ฝ”๋“œ์˜ˆ์š”'); useEffect(() => { if (!storedReviewRequestCode && reviewRequestCode) { setStoredReviewRequestCode(reviewRequestCode); } }, []); - const { data: reviewGroupData } = useGetReviewGroupData({ reviewRequestCode }); + useEffect(() => { + // ์ฟผ๋ฆฌ ํŒŒ๋ผ๋ฏธํ„ฐ๋กœ ์ „๋‹ฌ๋œ state ํŒŒ์‹ฑ + const params = new URLSearchParams(location.search); + const loginActionParam = params.get('login_action'); + if (!loginActionParam) return; + + // ๋กœ๊ทธ์ธ ์ƒํƒœ๊ฐ€ ์•„๋‹Œ ๊ฒฝ์šฐ ์ฟผ๋ฆฌ ํŒŒ๋ผ๋ฏธํ„ฐ ์ œ๊ฑฐ + if (!isUserLoggedIn) { + params.delete('login_action'); + window.history.replaceState(null, '', `${location.pathname}`); + return; + } + + if (loginActionParam === 'reviewWrite') return handleReviewWrite(); + if (loginActionParam === 'reviewCheck') return handleReviewCheck(); + }, []); - const handleReviewWritingButtonClick = () => { + const { data: reviewGroupData, isMemberLink } = useGetReviewGroupData({ reviewRequestCode }); + + const PROJECT_NAME_GUIDE = `${reviewGroupData.projectName}${calculateParticle({ target: reviewGroupData.projectName, particles: { withFinalConsonant: '์„', withoutFinalConsonant: '๋ฅผ' } })} ํ•จ๊ป˜ํ•œ`; + const REVIEWEE_NAME_GUIDE = `${reviewGroupData.revieweeName}์˜ ๋ฆฌ๋ทฐ ๊ณต๊ฐ„์ด์—์š”`; + + const handleReviewWrite = () => { + if (isUserLoggedIn) return navigate(`/${ROUTE.reviewWriting}/${reviewRequestCode}`); + openModal(MODAL_KEYS.writeOnLogin); + }; + + const handleReviewWriteGuest = () => { navigate(`/${ROUTE.reviewWriting}/${reviewRequestCode}`); }; - const handleReviewListButtonClick = () => { - openModal(MODAL_KEYS.login); + const handleReviewCheck = () => { + // ๋น„ํšŒ์›์ด ๋งŒ๋“  ๊ทธ๋ฃน์ด๋ฉด ๋น„๋ฐ€๋ฒˆํ˜ธ ์ž…๋ ฅ + if (!isMemberLink) return openModal(MODAL_KEYS.content); + // ๋ฆฌ๋ทฐ์–ด๊ฐ€ ๋กœ๊ทธ์ธ ์•ˆ ํ–ˆ์œผ๋ฉด ๋กœ๊ทธ์ธ ๋ชจ๋‹ฌ ๋„์šฐ๊ธฐ + if (!isUserLoggedIn) return openModal(MODAL_KEYS.checkOnLogin); + // ๋ฆฌ๋ทฐ์–ด๊ฐ€ ๋งํฌ ์ฃผ์ธ์ด๋ฉด ๋ชฉ๋ก ํŽ˜์ด์ง€๋กœ ์ด๋™ + if (userProfile?.memberId === reviewGroupData.revieweeId) { + return navigate(`/${ROUTE.reviewList}/${reviewRequestCode}`); + } + return showToast({ + type: 'error', + message: '๋ฆฌ๋ทฐ๋Š” ๋ณธ์ธ๋งŒ ํ™•์ธํ•  ์ˆ˜ ์žˆ์–ด์š”', + durationMS: 3000, + position: 'bottom', + }); }; return ( @@ -54,26 +101,31 @@ const ReviewZonePage = () => { <S.ReviewZoneMainImg src={ReviewZoneIcon} alt="" $height={IMG_HEIGHT} /> </ImgWithSkeleton> <S.ReviewGuideContainer> - <S.ReviewGuide>{`${reviewGroupData.projectName}${calculateParticle({ target: reviewGroupData.projectName, particles: { withFinalConsonant: '์„', withoutFinalConsonant: '๋ฅผ' } })} ํ•จ๊ป˜ํ•œ`}</S.ReviewGuide> - <S.ReviewGuide>{`${reviewGroupData.revieweeName}์˜ ๋ฆฌ๋ทฐ ๊ณต๊ฐ„์ด์—์š”`}</S.ReviewGuide> + <S.ReviewGuide>{PROJECT_NAME_GUIDE}</S.ReviewGuide> + <S.ReviewGuide>{REVIEWEE_NAME_GUIDE}</S.ReviewGuide> </S.ReviewGuideContainer> - <S.ButtonContainer> - <Button styleType="primary" type="button" onClick={handleReviewWritingButtonClick} style={BUTTON_SIZE}> - <S.ButtonTextContainer> - <S.ButtonText>๋ฆฌ๋ทฐ ์“ฐ๊ธฐ</S.ButtonText> - <S.ButtonDescription>์ž‘์„ฑํ•œ ๋ฆฌ๋ทฐ๋Š” ์ต๋ช…์œผ๋กœ ์ œ์ถœ๋ผ์š”</S.ButtonDescription> - </S.ButtonTextContainer> - </Button> - <Button styleType="secondary" type="button" onClick={handleReviewListButtonClick} style={BUTTON_SIZE}> - <S.ButtonTextContainer> - <S.ButtonText>๋ฆฌ๋ทฐ ํ™•์ธํ•˜๊ธฐ</S.ButtonText> - <S.ButtonDescription>๋น„๋ฐ€๋ฒˆํ˜ธ๋กœ ๋‚ด๊ฐ€ ๋ฐ›์€ ๋ฆฌ๋ทฐ๋ฅผ ํ™•์ธํ•  ์ˆ˜ ์žˆ์–ด์š”</S.ButtonDescription> - </S.ButtonTextContainer> - </Button> - </S.ButtonContainer> + <ReviewButton> + <ReviewButton.Write handleClick={handleReviewWrite} /> + {!isUserLoggedIn && <ReviewButton.WriteGuest handleClick={handleReviewWriteGuest} />} + <ReviewButton.Check isGroupLoggedIn={isMemberLink} handleClick={handleReviewCheck} /> + </ReviewButton> {isOpen(MODAL_KEYS.content) && ( <PasswordModal reviewRequestCode={reviewRequestCode} closeModal={() => closeModal(MODAL_KEYS.content)} /> )} + {isOpen(MODAL_KEYS.writeOnLogin) && ( + <LoginRequestModal + action="reviewWrite" + titleType="loginIntent" + closeModal={() => closeModal(MODAL_KEYS.writeOnLogin)} + /> + )} + {isOpen(MODAL_KEYS.checkOnLogin) && ( + <LoginRequestModal + action="reviewCheck" + titleType="loginIntent" + closeModal={() => closeModal(MODAL_KEYS.checkOnLogin)} + /> + )} </S.ReviewZonePage> ); };
Unknown
> ์ฟผ๋ฆฌ ํŒŒ๋ผ๋ฏธํ„ฐ์— ๋”ฐ๋ผ์„œ ํŽ˜์ด์ง€ ์ด๋™ํ•˜๋Š” useEffect ๋‚ด๋ถ€ ์ฝ”๋“œ๋ฅผ ๋ฐ–์œผ๋กœ ๋ถ„๋ฆฌ ์ข€ ๋” ์ž์„ธํ•˜๊ฒŒ ์„ค๋ช…ํ•ด์ฃผ์‹œ๊ฒ ์–ด์š”? ๋ณ„๋„์˜ ํ•จ์ˆ˜๋กœ ๋ถ„๋ฆฌํ•ด์„œ useEffect ๋‚ด๋ถ€ ์ฝ”๋“œ๋ฅผ ์งง๊ฒŒ ์œ ์ง€ํ•˜๋Š” ๊ฒƒ์ด ๋ชฉ์ ์ธ์ง€ ๊ถ๊ธˆํ•ด์š”
@@ -3,49 +3,96 @@ import { useNavigate } from 'react-router'; import { useRecoilState } from 'recoil'; import ReviewZoneIcon from '@/assets/reviewZone.svg'; -import { Button, ImgWithSkeleton } from '@/components'; +import { ImgWithSkeleton, LoginRequestModal } from '@/components'; import { ROUTE } from '@/constants'; -import { useGetReviewGroupData, useModals, useReviewRequestCodeParam } from '@/hooks'; +import { useGetReviewGroupData, useSearchParamAndQuery, useModals, useToastContext } from '@/hooks'; +import { useGetUserProfile } from '@/hooks/oAuth'; import { reviewRequestCodeAtom } from '@/recoil'; import { calculateParticle } from '@/utils'; import PasswordModal from './components/PasswordModal'; +import ReviewButton from './components/ReviewButton'; import * as S from './styles'; const MODAL_KEYS = { content: 'CONTENT_MODAL', - login: 'LOGIN_MODAL', + writeOnLogin: 'LOGIN_MODAL_TO_WRITE', + checkOnLogin: 'LOGIN_MODAL_TO_CHECK', }; const BUTTON_SIZE = { - width: '28rem', + width: '30rem', height: '8.5rem', }; const IMG_HEIGHT = '15rem'; const ReviewZonePage = () => { + const navigate = useNavigate(); + const { isOpen, openModal, closeModal } = useModals(); const [storedReviewRequestCode, setStoredReviewRequestCode] = useRecoilState(reviewRequestCodeAtom); + const { userProfile, isUserLoggedIn } = useGetUserProfile(); + const { showToast } = useToastContext(); - const navigate = useNavigate(); + const { param: reviewRequestCode } = useSearchParamAndQuery({ + paramKey: 'reviewRequestCode', + }); - const { reviewRequestCode } = useReviewRequestCodeParam(); + if (!reviewRequestCode) throw new Error('์œ ํšจํ•˜์ง€ ์•Š์€ ๋ฆฌ๋ทฐ ์š”์ฒญ ์ฝ”๋“œ์˜ˆ์š”'); useEffect(() => { if (!storedReviewRequestCode && reviewRequestCode) { setStoredReviewRequestCode(reviewRequestCode); } }, []); - const { data: reviewGroupData } = useGetReviewGroupData({ reviewRequestCode }); + useEffect(() => { + // ์ฟผ๋ฆฌ ํŒŒ๋ผ๋ฏธํ„ฐ๋กœ ์ „๋‹ฌ๋œ state ํŒŒ์‹ฑ + const params = new URLSearchParams(location.search); + const loginActionParam = params.get('login_action'); + if (!loginActionParam) return; + + // ๋กœ๊ทธ์ธ ์ƒํƒœ๊ฐ€ ์•„๋‹Œ ๊ฒฝ์šฐ ์ฟผ๋ฆฌ ํŒŒ๋ผ๋ฏธํ„ฐ ์ œ๊ฑฐ + if (!isUserLoggedIn) { + params.delete('login_action'); + window.history.replaceState(null, '', `${location.pathname}`); + return; + } + + if (loginActionParam === 'reviewWrite') return handleReviewWrite(); + if (loginActionParam === 'reviewCheck') return handleReviewCheck(); + }, []); - const handleReviewWritingButtonClick = () => { + const { data: reviewGroupData, isMemberLink } = useGetReviewGroupData({ reviewRequestCode }); + + const PROJECT_NAME_GUIDE = `${reviewGroupData.projectName}${calculateParticle({ target: reviewGroupData.projectName, particles: { withFinalConsonant: '์„', withoutFinalConsonant: '๋ฅผ' } })} ํ•จ๊ป˜ํ•œ`; + const REVIEWEE_NAME_GUIDE = `${reviewGroupData.revieweeName}์˜ ๋ฆฌ๋ทฐ ๊ณต๊ฐ„์ด์—์š”`; + + const handleReviewWrite = () => { + if (isUserLoggedIn) return navigate(`/${ROUTE.reviewWriting}/${reviewRequestCode}`); + openModal(MODAL_KEYS.writeOnLogin); + }; + + const handleReviewWriteGuest = () => { navigate(`/${ROUTE.reviewWriting}/${reviewRequestCode}`); }; - const handleReviewListButtonClick = () => { - openModal(MODAL_KEYS.login); + const handleReviewCheck = () => { + // ๋น„ํšŒ์›์ด ๋งŒ๋“  ๊ทธ๋ฃน์ด๋ฉด ๋น„๋ฐ€๋ฒˆํ˜ธ ์ž…๋ ฅ + if (!isMemberLink) return openModal(MODAL_KEYS.content); + // ๋ฆฌ๋ทฐ์–ด๊ฐ€ ๋กœ๊ทธ์ธ ์•ˆ ํ–ˆ์œผ๋ฉด ๋กœ๊ทธ์ธ ๋ชจ๋‹ฌ ๋„์šฐ๊ธฐ + if (!isUserLoggedIn) return openModal(MODAL_KEYS.checkOnLogin); + // ๋ฆฌ๋ทฐ์–ด๊ฐ€ ๋งํฌ ์ฃผ์ธ์ด๋ฉด ๋ชฉ๋ก ํŽ˜์ด์ง€๋กœ ์ด๋™ + if (userProfile?.memberId === reviewGroupData.revieweeId) { + return navigate(`/${ROUTE.reviewList}/${reviewRequestCode}`); + } + return showToast({ + type: 'error', + message: '๋ฆฌ๋ทฐ๋Š” ๋ณธ์ธ๋งŒ ํ™•์ธํ•  ์ˆ˜ ์žˆ์–ด์š”', + durationMS: 3000, + position: 'bottom', + }); }; return ( @@ -54,26 +101,31 @@ const ReviewZonePage = () => { <S.ReviewZoneMainImg src={ReviewZoneIcon} alt="" $height={IMG_HEIGHT} /> </ImgWithSkeleton> <S.ReviewGuideContainer> - <S.ReviewGuide>{`${reviewGroupData.projectName}${calculateParticle({ target: reviewGroupData.projectName, particles: { withFinalConsonant: '์„', withoutFinalConsonant: '๋ฅผ' } })} ํ•จ๊ป˜ํ•œ`}</S.ReviewGuide> - <S.ReviewGuide>{`${reviewGroupData.revieweeName}์˜ ๋ฆฌ๋ทฐ ๊ณต๊ฐ„์ด์—์š”`}</S.ReviewGuide> + <S.ReviewGuide>{PROJECT_NAME_GUIDE}</S.ReviewGuide> + <S.ReviewGuide>{REVIEWEE_NAME_GUIDE}</S.ReviewGuide> </S.ReviewGuideContainer> - <S.ButtonContainer> - <Button styleType="primary" type="button" onClick={handleReviewWritingButtonClick} style={BUTTON_SIZE}> - <S.ButtonTextContainer> - <S.ButtonText>๋ฆฌ๋ทฐ ์“ฐ๊ธฐ</S.ButtonText> - <S.ButtonDescription>์ž‘์„ฑํ•œ ๋ฆฌ๋ทฐ๋Š” ์ต๋ช…์œผ๋กœ ์ œ์ถœ๋ผ์š”</S.ButtonDescription> - </S.ButtonTextContainer> - </Button> - <Button styleType="secondary" type="button" onClick={handleReviewListButtonClick} style={BUTTON_SIZE}> - <S.ButtonTextContainer> - <S.ButtonText>๋ฆฌ๋ทฐ ํ™•์ธํ•˜๊ธฐ</S.ButtonText> - <S.ButtonDescription>๋น„๋ฐ€๋ฒˆํ˜ธ๋กœ ๋‚ด๊ฐ€ ๋ฐ›์€ ๋ฆฌ๋ทฐ๋ฅผ ํ™•์ธํ•  ์ˆ˜ ์žˆ์–ด์š”</S.ButtonDescription> - </S.ButtonTextContainer> - </Button> - </S.ButtonContainer> + <ReviewButton> + <ReviewButton.Write handleClick={handleReviewWrite} /> + {!isUserLoggedIn && <ReviewButton.WriteGuest handleClick={handleReviewWriteGuest} />} + <ReviewButton.Check isGroupLoggedIn={isMemberLink} handleClick={handleReviewCheck} /> + </ReviewButton> {isOpen(MODAL_KEYS.content) && ( <PasswordModal reviewRequestCode={reviewRequestCode} closeModal={() => closeModal(MODAL_KEYS.content)} /> )} + {isOpen(MODAL_KEYS.writeOnLogin) && ( + <LoginRequestModal + action="reviewWrite" + titleType="loginIntent" + closeModal={() => closeModal(MODAL_KEYS.writeOnLogin)} + /> + )} + {isOpen(MODAL_KEYS.checkOnLogin) && ( + <LoginRequestModal + action="reviewCheck" + titleType="loginIntent" + closeModal={() => closeModal(MODAL_KEYS.checkOnLogin)} + /> + )} </S.ReviewZonePage> ); };
Unknown
ํ•ฉ์„ฑ ์ปดํฌ๋„ŒํŠธ ํŒจํ„ด์œผ๋กœ ๊ตฌํ˜„ํ•œ ๋ฒ„ํŠผ๋“ค์„ ๊ฐ๊ฐ์˜ ์ปดํฌ๋„ŒํŠธ๋กœ ๋ถ„๋ฆฌํ•˜๋ฉด ์ข‹๊ฒ ๋‹ค๋Š” ์˜๊ฒฌ์ผ๊นŒ์š”? ๋ฒ„ํŠผ๋งˆ๋‹ค ์Šคํƒ€์ผ ์ฝ”๋“œ๊ฐ€ ๊ฐ™๊ณ , ๋‚˜๋ˆˆ๋‹ค๋ฉด Write/Check ๋‘˜๋กœ๋งŒ ๋‚˜๋ˆŒ์ง€ ๋“ฑ ์ƒ๊ฐํ•  ๋ถ€๋ถ„๋“ค์ด ์žˆ์–ด์„œ ์ข€ ๋” ๊ณ ๋ฏผํ•ด๋ณด๊ฒ ์Šต๋‹ˆ๋‹ค (์ด ๋ถ€๋ถ„ ์ฝ”๋“œ๋ฅผ ๋‹ค๋“ฌ์–ด์•ผ ํ•œ๋‹ค๋Š” ๊ฒƒ์— ๋™์˜ํ•ด์š”)
@@ -3,49 +3,96 @@ import { useNavigate } from 'react-router'; import { useRecoilState } from 'recoil'; import ReviewZoneIcon from '@/assets/reviewZone.svg'; -import { Button, ImgWithSkeleton } from '@/components'; +import { ImgWithSkeleton, LoginRequestModal } from '@/components'; import { ROUTE } from '@/constants'; -import { useGetReviewGroupData, useModals, useReviewRequestCodeParam } from '@/hooks'; +import { useGetReviewGroupData, useSearchParamAndQuery, useModals, useToastContext } from '@/hooks'; +import { useGetUserProfile } from '@/hooks/oAuth'; import { reviewRequestCodeAtom } from '@/recoil'; import { calculateParticle } from '@/utils'; import PasswordModal from './components/PasswordModal'; +import ReviewButton from './components/ReviewButton'; import * as S from './styles'; const MODAL_KEYS = { content: 'CONTENT_MODAL', - login: 'LOGIN_MODAL', + writeOnLogin: 'LOGIN_MODAL_TO_WRITE', + checkOnLogin: 'LOGIN_MODAL_TO_CHECK', }; const BUTTON_SIZE = { - width: '28rem', + width: '30rem', height: '8.5rem', }; const IMG_HEIGHT = '15rem'; const ReviewZonePage = () => { + const navigate = useNavigate(); + const { isOpen, openModal, closeModal } = useModals(); const [storedReviewRequestCode, setStoredReviewRequestCode] = useRecoilState(reviewRequestCodeAtom); + const { userProfile, isUserLoggedIn } = useGetUserProfile(); + const { showToast } = useToastContext(); - const navigate = useNavigate(); + const { param: reviewRequestCode } = useSearchParamAndQuery({ + paramKey: 'reviewRequestCode', + }); - const { reviewRequestCode } = useReviewRequestCodeParam(); + if (!reviewRequestCode) throw new Error('์œ ํšจํ•˜์ง€ ์•Š์€ ๋ฆฌ๋ทฐ ์š”์ฒญ ์ฝ”๋“œ์˜ˆ์š”'); useEffect(() => { if (!storedReviewRequestCode && reviewRequestCode) { setStoredReviewRequestCode(reviewRequestCode); } }, []); - const { data: reviewGroupData } = useGetReviewGroupData({ reviewRequestCode }); + useEffect(() => { + // ์ฟผ๋ฆฌ ํŒŒ๋ผ๋ฏธํ„ฐ๋กœ ์ „๋‹ฌ๋œ state ํŒŒ์‹ฑ + const params = new URLSearchParams(location.search); + const loginActionParam = params.get('login_action'); + if (!loginActionParam) return; + + // ๋กœ๊ทธ์ธ ์ƒํƒœ๊ฐ€ ์•„๋‹Œ ๊ฒฝ์šฐ ์ฟผ๋ฆฌ ํŒŒ๋ผ๋ฏธํ„ฐ ์ œ๊ฑฐ + if (!isUserLoggedIn) { + params.delete('login_action'); + window.history.replaceState(null, '', `${location.pathname}`); + return; + } + + if (loginActionParam === 'reviewWrite') return handleReviewWrite(); + if (loginActionParam === 'reviewCheck') return handleReviewCheck(); + }, []); - const handleReviewWritingButtonClick = () => { + const { data: reviewGroupData, isMemberLink } = useGetReviewGroupData({ reviewRequestCode }); + + const PROJECT_NAME_GUIDE = `${reviewGroupData.projectName}${calculateParticle({ target: reviewGroupData.projectName, particles: { withFinalConsonant: '์„', withoutFinalConsonant: '๋ฅผ' } })} ํ•จ๊ป˜ํ•œ`; + const REVIEWEE_NAME_GUIDE = `${reviewGroupData.revieweeName}์˜ ๋ฆฌ๋ทฐ ๊ณต๊ฐ„์ด์—์š”`; + + const handleReviewWrite = () => { + if (isUserLoggedIn) return navigate(`/${ROUTE.reviewWriting}/${reviewRequestCode}`); + openModal(MODAL_KEYS.writeOnLogin); + }; + + const handleReviewWriteGuest = () => { navigate(`/${ROUTE.reviewWriting}/${reviewRequestCode}`); }; - const handleReviewListButtonClick = () => { - openModal(MODAL_KEYS.login); + const handleReviewCheck = () => { + // ๋น„ํšŒ์›์ด ๋งŒ๋“  ๊ทธ๋ฃน์ด๋ฉด ๋น„๋ฐ€๋ฒˆํ˜ธ ์ž…๋ ฅ + if (!isMemberLink) return openModal(MODAL_KEYS.content); + // ๋ฆฌ๋ทฐ์–ด๊ฐ€ ๋กœ๊ทธ์ธ ์•ˆ ํ–ˆ์œผ๋ฉด ๋กœ๊ทธ์ธ ๋ชจ๋‹ฌ ๋„์šฐ๊ธฐ + if (!isUserLoggedIn) return openModal(MODAL_KEYS.checkOnLogin); + // ๋ฆฌ๋ทฐ์–ด๊ฐ€ ๋งํฌ ์ฃผ์ธ์ด๋ฉด ๋ชฉ๋ก ํŽ˜์ด์ง€๋กœ ์ด๋™ + if (userProfile?.memberId === reviewGroupData.revieweeId) { + return navigate(`/${ROUTE.reviewList}/${reviewRequestCode}`); + } + return showToast({ + type: 'error', + message: '๋ฆฌ๋ทฐ๋Š” ๋ณธ์ธ๋งŒ ํ™•์ธํ•  ์ˆ˜ ์žˆ์–ด์š”', + durationMS: 3000, + position: 'bottom', + }); }; return ( @@ -54,26 +101,31 @@ const ReviewZonePage = () => { <S.ReviewZoneMainImg src={ReviewZoneIcon} alt="" $height={IMG_HEIGHT} /> </ImgWithSkeleton> <S.ReviewGuideContainer> - <S.ReviewGuide>{`${reviewGroupData.projectName}${calculateParticle({ target: reviewGroupData.projectName, particles: { withFinalConsonant: '์„', withoutFinalConsonant: '๋ฅผ' } })} ํ•จ๊ป˜ํ•œ`}</S.ReviewGuide> - <S.ReviewGuide>{`${reviewGroupData.revieweeName}์˜ ๋ฆฌ๋ทฐ ๊ณต๊ฐ„์ด์—์š”`}</S.ReviewGuide> + <S.ReviewGuide>{PROJECT_NAME_GUIDE}</S.ReviewGuide> + <S.ReviewGuide>{REVIEWEE_NAME_GUIDE}</S.ReviewGuide> </S.ReviewGuideContainer> - <S.ButtonContainer> - <Button styleType="primary" type="button" onClick={handleReviewWritingButtonClick} style={BUTTON_SIZE}> - <S.ButtonTextContainer> - <S.ButtonText>๋ฆฌ๋ทฐ ์“ฐ๊ธฐ</S.ButtonText> - <S.ButtonDescription>์ž‘์„ฑํ•œ ๋ฆฌ๋ทฐ๋Š” ์ต๋ช…์œผ๋กœ ์ œ์ถœ๋ผ์š”</S.ButtonDescription> - </S.ButtonTextContainer> - </Button> - <Button styleType="secondary" type="button" onClick={handleReviewListButtonClick} style={BUTTON_SIZE}> - <S.ButtonTextContainer> - <S.ButtonText>๋ฆฌ๋ทฐ ํ™•์ธํ•˜๊ธฐ</S.ButtonText> - <S.ButtonDescription>๋น„๋ฐ€๋ฒˆํ˜ธ๋กœ ๋‚ด๊ฐ€ ๋ฐ›์€ ๋ฆฌ๋ทฐ๋ฅผ ํ™•์ธํ•  ์ˆ˜ ์žˆ์–ด์š”</S.ButtonDescription> - </S.ButtonTextContainer> - </Button> - </S.ButtonContainer> + <ReviewButton> + <ReviewButton.Write handleClick={handleReviewWrite} /> + {!isUserLoggedIn && <ReviewButton.WriteGuest handleClick={handleReviewWriteGuest} />} + <ReviewButton.Check isGroupLoggedIn={isMemberLink} handleClick={handleReviewCheck} /> + </ReviewButton> {isOpen(MODAL_KEYS.content) && ( <PasswordModal reviewRequestCode={reviewRequestCode} closeModal={() => closeModal(MODAL_KEYS.content)} /> )} + {isOpen(MODAL_KEYS.writeOnLogin) && ( + <LoginRequestModal + action="reviewWrite" + titleType="loginIntent" + closeModal={() => closeModal(MODAL_KEYS.writeOnLogin)} + /> + )} + {isOpen(MODAL_KEYS.checkOnLogin) && ( + <LoginRequestModal + action="reviewCheck" + titleType="loginIntent" + closeModal={() => closeModal(MODAL_KEYS.checkOnLogin)} + /> + )} </S.ReviewZonePage> ); };
Unknown
์Šคํƒ€์ผ ์ปดํฌ๋„ŒํŠธ๋ช…์œผ๋กœ ๋ ˆ์ด์•„์›ƒ ๊ตฌ๋ถ„์€ ํ•  ์ˆ˜ ์žˆ์ง€๋งŒ, ์ปดํฌ๋„ŒํŠธ๋“ค์ด ๋‚˜์—ด๋œ ๋А๋‚Œ์ด๋ผ ํฌ๊ฒŒ ๋ฆฌ๋ทฐ ๊ทธ๋ฃน ์ •๋ณด, ์“ฐ๊ธฐ ๋ฒ„ํŠผ, ํ™•์ธ ๋ฒ„ํŠผ, ๋ชจ๋‹ฌ๋กœ ๋‚˜๋‰˜์–ด์งˆ ์ˆ˜ ์žˆ์„ ๊ฒƒ ๊ฐ™์•„์š”. ๋ชจ๋‹ฌ์€ ํ•ด๋‹น ๋ชจ๋‹ฌ์„ ์—ด๊ฒŒํ•˜๋Š” ๋ฒ„ํŠผ๊ณผ ์—ฎ์–ด์„œ ํ•˜๋‚˜์˜ ์ปดํฌ๋„ŒํŠธ๋‚ด์—์„œ ๊ด€๋ฆฌํ•˜๋ฉด ํ๋ฆ„ ํŒŒ์•…์— ๋” ์ข‹์„ ๊ฒƒ ๊ฐ™์•„์š”.
@@ -11,12 +11,178 @@ on: jobs: code_review: runs-on: ubuntu-latest - name: ChatGPT Code Review + name: Gemini Code Review steps: - - uses: anc95/ChatGPT-CodeReview@main + - uses: actions/checkout@v4 + + - name: Setup Node.js + uses: actions/setup-node@v4 + with: + node-version: "20" + + - name: Install dependencies + run: npm install @google/generative-ai parse-diff + + - name: Review Changed Files + uses: actions/github-script@v7 env: - GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} - OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }} - # optional - LANGUAGE: Korean - MODEL: gpt-4o-mini-2024-07-18 # https://platform.openai.com/docs/models + GEMINI_API_KEY: ${{ secrets.GEMINI_API_KEY }} + GEMINI_MODEL: ${{ secrets.GEMINI_MODEL }} + MAX_CONCURRENT_REVIEWS: 3 # ๋™์‹œ์— ์ฒ˜๋ฆฌํ•  ํŒŒ์ผ ์ˆ˜ + MAX_RETRIES: 3 + RETRY_DELAY: 1000 + + with: + script: | + const { GoogleGenerativeAI } = require("@google/generative-ai"); + const parseDiff = require('parse-diff'); + // core๋Š” ์ด๋ฏธ github-script์—์„œ ์ œ๊ณต๋จ + + // ์žฌ์‹œ๋„ ๋กœ์ง์„ ํฌํ•จํ•œ API ํ˜ธ์ถœ ํ•จ์ˆ˜ + async function withRetry(fn, retries = process.env.MAX_RETRIES) { + for (let i = 0; i < retries; i++) { + try { + return await fn(); + + } catch (error) { + if (error.message.includes('rate limit') && i < retries - 1) { + const delay = process.env.RETRY_DELAY * Math.pow(2, i); + console.log(`Rate limit hit, waiting ${delay}ms before retry ${i + 1}`); + + await new Promise(resolve => setTimeout(resolve, delay)); + continue; + } + + throw error; + } + } + } + + // Gemini AI ํด๋ผ์ด์–ธํŠธ ์ดˆ๊ธฐํ™” + const genAI = new GoogleGenerativeAI(process.env.GEMINI_API_KEY); + const model = genAI.getGenerativeModel({ model: process.env.GEMINI_MODEL }); + + /** + * ์ฝ”๋“œ ๋ณ€๊ฒฝ์‚ฌํ•ญ์„ ๊ฒ€ํ† ํ•˜๊ณ  ํ”ผ๋“œ๋ฐฑ์„ ์ƒ์„ฑ + * + * @param content ๋ฆฌ๋ทฐํ•  ์ฝ”๋“œ ๋‚ด์šฉ + * @param filename ํŒŒ์ผ๋ช… + * @returns ๋ฆฌ๋ทฐ ์ฝ”๋ฉ˜ํŠธ + */ + async function reviewCode(content, filename) { + try { + // ํŒŒ์ผ๋ช… sanitize + const sanitizedFilename = filename.replace(/[^a-zA-Z0-9.-_\/]/g, '_'); + + const prompt = `๋‹น์‹ ์€ ์‹œ๋‹ˆ์–ด ๊ฐœ๋ฐœ์ž์ž…๋‹ˆ๋‹ค. ์•„๋ž˜ ${sanitizedFilename} ํŒŒ์ผ์˜ ์ฝ”๋“œ๋ฅผ ๊ฒ€ํ† ํ•˜๊ณ  ๋‹ค์Œ ์‚ฌํ•ญ๋“ค์„ ํ•œ๊ตญ์–ด๋กœ ๋ฆฌ๋ทฐํ•ด์ฃผ์„ธ์š”: + 1. ์ฝ”๋“œ์˜ ํ’ˆ์งˆ๊ณผ ๊ฐ€๋…์„ฑ + 2. ์ž ์žฌ์ ์ธ ๋ฒ„๊ทธ๋‚˜ ๋ฌธ์ œ์  + 3. ์„ฑ๋Šฅ ๊ฐœ์„  ํฌ์ธํŠธ + 4. ๋ณด์•ˆ ๊ด€๋ จ ์ด์Šˆ + 5. ๊ฐœ์„ ์„ ์œ„ํ•œ ๊ตฌ์ฒด์ ์ธ ์ œ์•ˆ + + ์ฝ”๋“œ: + ${content}`; + + const result = await withRetry(() => model.generateContent(prompt)); + const response = await result.response; + + if (!response.text()) { + throw new Error('Gemini API returned empty response'); + } + + console.log(`Successfully reviewed ${filename}`); + return response.text(); + + } catch (error) { + console.error(`Error reviewing ${filename}:`, error); + return `โš ๏ธ ์ฝ”๋“œ ๋ฆฌ๋ทฐ ์ค‘ ์˜ค๋ฅ˜๊ฐ€ ๋ฐœ์ƒํ–ˆ์Šต๋‹ˆ๋‹ค: ${error.message} + ๋‹ค์‹œ ์‹œ๋„ํ•˜์‹œ๊ฑฐ๋‚˜ ๊ด€๋ฆฌ์ž์—๊ฒŒ ๋ฌธ์˜ํ•ด์ฃผ์„ธ์š”.`; + } + } + + /** + * PR์˜ ๊ฐ ํŒŒ์ผ์„ ์ฒ˜๋ฆฌํ•˜๊ณ  ๋ฆฌ๋ทฐ ์ฝ”๋ฉ˜ํŠธ ์ž‘์„ฑ + * @param file PR์—์„œ ๋ณ€๊ฒฝ๋œ ํŒŒ์ผ ์ •๋ณด + * @param pr PR ์ •๋ณด + */ + async function processFile(file, pr) { + if (file.status === 'removed') { + console.log(`Skipping removed file: ${file.filename}`); + return; + } + + try { + if (!file.patch) { + console.warn(`No patch found for ${file.filename}, skipping.`); + return; + } + + const diff = parseDiff(file.patch)[0]; + if (!diff || !diff.chunks) { + console.log(`No valid diff found for ${file.filename}`); + return; + } + + // ๋ชจ๋“  ๋ณ€๊ฒฝ์‚ฌํ•ญ์„ ํ•˜๋‚˜๋กœ ํ•ฉ์น˜๊ธฐ (์ถ”๊ฐ€๋œ ๋ถ€๋ถ„๋งŒ ํ•„ํ„ฐ๋ง) + const changes = diff.chunks + .flatMap(chunk => chunk.changes) + .filter(change => change.type === 'add'); + + if (changes.length === 0) { + console.log(`No added changes found in ${file.filename}`); + return; + } + + // ๋ณ€๊ฒฝ์‚ฌํ•ญ์„ ํ•˜๋‚˜์˜ ๋ฌธ์ž์—ด๋กœ ํ•ฉ์น˜๊ธฐ + const content = changes.map(change => change.content).join('\n'); + const review = await reviewCode(content, file.filename); + + // PR์— ๋ฆฌ๋ทฐ ์ฝ”๋ฉ˜ํŠธ ์ž‘์„ฑ (ํŒŒ์ผ๋ช…์„ ํ—ค๋”๋กœ ์ถ”๊ฐ€) + return github.rest.issues.createComment({ + owner: context.repo.owner, + repo: context.repo.repo, + issue_number: context.issue.number, + body: `## ${file.filename} ๋ฆฌ๋ทฐ\n\n${review}` + }); + + } catch (error) { + console.error(`Error processing ${file.filename}:`, error); + throw error; + } + } + + try { + // PR ์ •๋ณด ์กฐํšŒ + const { data: pr } = await github.rest.pulls.get({ + owner: context.repo.owner, + repo: context.repo.repo, + pull_number: context.issue.number, + }); + + // ๋ณ€๊ฒฝ๋œ ํŒŒ์ผ ๋ชฉ๋ก ์กฐํšŒ + const { data: files } = await github.rest.pulls.listFiles({ + owner: context.repo.owner, + repo: context.repo.repo, + pull_number: context.issue.number, + }); + + console.log(`Starting review of ${files.length} files...`); + + // ๋ชจ๋“  ํŒŒ์ผ ์ฒ˜๋ฆฌ ์™„๋ฃŒ๋ฅผ ๊ธฐ๋‹ค๋ฆผ + const promises = []; + const batchSize = parseInt(process.env.MAX_CONCURRENT_REVIEWS); + + for (let i = 0; i < files.length; i += batchSize) { + const batch = files.slice(i, i + batchSize); + const batchPromises = batch.map(file => processFile(file, pr)); + promises.push(...batchPromises); + } + + await Promise.all(promises); + console.log('All reviews completed successfully'); + + } catch (error) { + console.error('Workflow failed:', error); + core.setFailed(`Workflow failed: ${error.message}`); + }
Unknown
์ด ์ฝ”๋“œ๋Š” GitHub Actions๋ฅผ ์ด์šฉํ•˜์—ฌ Google Gemini API๋ฅผ ํ†ตํ•ด Pull Request์— ๋Œ€ํ•œ ์ฝ”๋“œ ๋ฆฌ๋ทฐ๋ฅผ ์ž๋™ํ™”ํ•˜๋Š” ์ž‘์—…์ž…๋‹ˆ๋‹ค. ํ•˜์ง€๋งŒ ๋ช‡ ๊ฐ€์ง€ ๊ฐœ์„ ์ด ํ•„์š”ํ•ฉ๋‹ˆ๋‹ค. **1. ์ฝ”๋“œ์˜ ํ’ˆ์งˆ๊ณผ ๊ฐ€๋…์„ฑ:** * **๊ฐ€๋…์„ฑ ๊ฐœ์„ :** `reviewCode` ํ•จ์ˆ˜ ๋‚ด๋ถ€์˜ JSON ๊ตฌ์กฐ๊ฐ€ ์ค‘์ฒฉ๋˜์–ด ๊ฐ€๋…์„ฑ์ด ๋–จ์–ด์ง‘๋‹ˆ๋‹ค. ๋” ๋ช…ํ™•ํ•œ ๋ณ€์ˆ˜๋ช…์„ ์‚ฌ์šฉํ•˜๊ณ , JSON ์ƒ์„ฑ ๋ถ€๋ถ„์„ ์—ฌ๋Ÿฌ ์ค„๋กœ ๋‚˜๋ˆ„์–ด ๊ฐ€๋…์„ฑ์„ ๋†’์—ฌ์•ผ ํ•ฉ๋‹ˆ๋‹ค. ์˜ˆ๋ฅผ ๋“ค์–ด, `contents`, `parts` ๋“ฑ์˜ ๋ณ€์ˆ˜๋ช…์€ ์ปจํ…์ŠคํŠธ๋ฅผ ๋ช…ํ™•ํžˆ ํ•˜๋„๋ก ์ˆ˜์ •ํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค. * **์˜ค๋ฅ˜ ์ฒ˜๋ฆฌ ๋ถ€์กฑ:** `fetch` ํ˜ธ์ถœ๊ณผ `response.json()`์—์„œ ๋ฐœ์ƒํ•  ์ˆ˜ ์žˆ๋Š” ๋„คํŠธ์›Œํฌ ์—๋Ÿฌ๋‚˜ JSON ํŒŒ์‹ฑ ์—๋Ÿฌ์— ๋Œ€ํ•œ ์ฒ˜๋ฆฌ๊ฐ€ ์ „ํ˜€ ์—†์Šต๋‹ˆ๋‹ค. `try...catch` ๋ธ”๋ก์„ ์‚ฌ์šฉํ•˜์—ฌ ์—๋Ÿฌ๋ฅผ ์ฒ˜๋ฆฌํ•˜๊ณ , ์—๋Ÿฌ ๋กœ๊ทธ๋ฅผ ๋‚จ๊ธฐ๊ฑฐ๋‚˜ ์ ์ ˆํ•œ fallback ์ฒ˜๋ฆฌ๋ฅผ ํ•ด์•ผ ํ•ฉ๋‹ˆ๋‹ค. * **ํ•˜๋“œ์ฝ”๋”ฉ๋œ API ์—”๋“œํฌ์ธํŠธ:** `https://generativelanguage.googleapis.com/v1beta/models/gemini-1.5-flash:generateContent` ์™€ ๊ฐ™์€ API ์—”๋“œํฌ์ธํŠธ๊ฐ€ ํ•˜๋“œ์ฝ”๋”ฉ๋˜์–ด ์žˆ์Šต๋‹ˆ๋‹ค. ํ™˜๊ฒฝ ๋ณ€์ˆ˜๋กœ ๊ด€๋ฆฌํ•˜๊ฑฐ๋‚˜, ๋” ์œ ์—ฐํ•œ ๋ฐฉ๋ฒ•์„ ์‚ฌ์šฉํ•˜์—ฌ ์ถ”ํ›„ ๋ณ€๊ฒฝ์— ๋Œ€๋น„ํ•ด์•ผ ํ•ฉ๋‹ˆ๋‹ค. * **๋น„ํšจ์œจ์ ์ธ ํŒจ์น˜ ํŒŒ์ผ ์ฒ˜๋ฆฌ:** ๋ชจ๋“  ํŒŒ์ผ์˜ `patch` ์ „์ฒด๋ฅผ Gemini API์— ์ „๋‹ฌํ•ฉ๋‹ˆ๋‹ค. ํŒŒ์ผ์ด ๋งค์šฐ ํฌ๋‹ค๋ฉด API ์š”์ฒญ ์ œํ•œ์— ๊ฑธ๋ฆด ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค. ์ž‘์€ ๋‹จ์œ„๋กœ ๋‚˜๋ˆ„์–ด ์ „๋‹ฌํ•˜๊ฑฐ๋‚˜, ํŒŒ์ผ ํฌ๊ธฐ๋ฅผ ์ œํ•œํ•˜๋Š” ๋กœ์ง์ด ํ•„์š”ํ•ฉ๋‹ˆ๋‹ค. * **๋งˆ์ง€๋ง‰ ์ค„ ๋ฒˆํ˜ธ:** `line: file.patch.split('\n').length` ๋Š” ํŒŒ์ผ์˜ ๋งˆ์ง€๋ง‰ ์ค„์„ ์ง€์ •ํ•ฉ๋‹ˆ๋‹ค. ์‹ค์ œ ๋ณ€๊ฒฝ ์‚ฌํ•ญ์ด ์žˆ๋Š” ์ค„์„ ํŠน์ •ํ•˜๋Š” ๊ฒƒ์ด ๋” ์ •ํ™•ํ•ฉ๋‹ˆ๋‹ค. diff๋ฅผ ํŒŒ์‹ฑํ•˜์—ฌ ๋ณ€๊ฒฝ๋œ ์ค„์„ ์ฐพ๋Š” ๋กœ์ง์„ ์ถ”๊ฐ€ํ•ด์•ผ ํ•ฉ๋‹ˆ๋‹ค. **2. ์ž ์žฌ์ ์ธ ๋ฒ„๊ทธ๋‚˜ ๋ฌธ์ œ์ :** * **API ํ‚ค ๋…ธ์ถœ:** `GEMINI_API_KEY` ๋Š” GitHub Secrets๋กœ ๊ด€๋ฆฌ๋˜์ง€๋งŒ, ์ฝ”๋“œ ์ž์ฒด์— ์ง์ ‘์ ์œผ๋กœ ์‚ฌ์šฉ๋˜๋ฏ€๋กœ, ์ฝ”๋“œ๋ฒ ์ด์Šค๊ฐ€ ์œ ์ถœ๋  ๊ฒฝ์šฐ API ํ‚ค๊ฐ€ ๋…ธ์ถœ๋  ์œ„ํ—˜์ด ์žˆ์Šต๋‹ˆ๋‹ค. API ํ‚ค๋ฅผ ์ง์ ‘ ์‚ฌ์šฉํ•˜์ง€ ์•Š๊ณ , ์ ์ ˆํ•œ ํด๋ผ์ด์–ธํŠธ ๋ผ์ด๋ธŒ๋Ÿฌ๋ฆฌ๋ฅผ ์‚ฌ์šฉํ•˜๋Š” ๊ฒƒ์ด ์ข‹์Šต๋‹ˆ๋‹ค. Google Cloud Client Library for Node.js๋ฅผ ์‚ฌ์šฉํ•˜๋Š” ๊ฒƒ์„ ๊ณ ๋ คํ•ด ๋ณด์„ธ์š”. * **Gemini API์˜ ์‘๋‹ต ์ฒ˜๋ฆฌ:** `result.candidates[0].content.parts[0].text` ์™€ ๊ฐ™์ด Gemini API์˜ ์‘๋‹ต ๊ตฌ์กฐ์— ์ง์ ‘ ์ ‘๊ทผํ•˜๊ณ  ์žˆ์Šต๋‹ˆ๋‹ค. API ์‘๋‹ต ๊ตฌ์กฐ๊ฐ€ ๋ณ€๊ฒฝ๋˜๋ฉด ์ฝ”๋“œ๊ฐ€ ๋™์ž‘ํ•˜์ง€ ์•Š์„ ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค. ๋” ์•ˆ์ „ํ•˜๊ณ  ์œ ์—ฐํ•œ ๋ฐฉ์‹์œผ๋กœ ์‘๋‹ต์„ ์ฒ˜๋ฆฌํ•ด์•ผ ํ•ฉ๋‹ˆ๋‹ค. (์˜ˆ: ์‘๋‹ต์˜ ์œ ํšจ์„ฑ ๊ฒ€์‚ฌ) * **๋Œ€๋Ÿ‰์˜ Pull Request:** ๋งค์šฐ ํฐ Pull Request์˜ ๊ฒฝ์šฐ, API ํ˜ธ์ถœ ํšŸ์ˆ˜๊ฐ€ ๋งŽ์•„์ง€๊ณ , GitHub Actions ์‹คํ–‰ ์‹œ๊ฐ„ ์ œํ•œ์— ๊ฑธ๋ฆด ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค. * **๋น„๋™๊ธฐ ์ฒ˜๋ฆฌ ๋ˆ„๋ฝ:** `for` ๋ฃจํ”„ ๋‚ด๋ถ€์—์„œ ๋น„๋™๊ธฐ ํ•จ์ˆ˜ `reviewCode`๋ฅผ ํ˜ธ์ถœํ•˜์ง€๋งŒ, ๊ฒฐ๊ณผ๋ฅผ ๊ธฐ๋‹ค๋ฆฌ์ง€ ์•Š๊ณ  ์ˆœ์ฐจ์ ์œผ๋กœ ๋‹ค์Œ ํŒŒ์ผ์„ ์ฒ˜๋ฆฌํ•ฉ๋‹ˆ๋‹ค. `Promise.all`์„ ์‚ฌ์šฉํ•˜์—ฌ ๋ชจ๋“  ๋ฆฌ๋ทฐ๊ฐ€ ์™„๋ฃŒ๋  ๋•Œ๊นŒ์ง€ ๊ธฐ๋‹ค๋ฆฌ๋Š” ๊ฒƒ์ด ์ข‹์Šต๋‹ˆ๋‹ค. **3. ์„ฑ๋Šฅ ๊ฐœ์„  ํฌ์ธํŠธ:** * **๋ณ‘๋ ฌ ์ฒ˜๋ฆฌ:** `Promise.all` ์„ ์‚ฌ์šฉํ•˜์—ฌ ์—ฌ๋Ÿฌ ํŒŒ์ผ์˜ ์ฝ”๋“œ ๋ฆฌ๋ทฐ๋ฅผ ๋ณ‘๋ ฌ๋กœ ์ฒ˜๋ฆฌํ•˜์—ฌ ์ „์ฒด ์ฒ˜๋ฆฌ ์‹œ๊ฐ„์„ ๋‹จ์ถ•ํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค. * **์บ์‹ฑ:** ์ด์ „์— ๋ฆฌ๋ทฐํ•œ ์ฝ”๋“œ๋Š” ์บ์‹ฑํ•˜์—ฌ ์ค‘๋ณต๋œ API ํ˜ธ์ถœ์„ ์ค„์ผ ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค. * **API ์š”์ฒญ ์ตœ์ ํ™”:** ํ•œ ๋ฒˆ์— ์—ฌ๋Ÿฌ ํŒŒ์ผ์„ ์ฒ˜๋ฆฌํ•˜๊ฑฐ๋‚˜, ๋” ์ž‘์€ ๋‹จ์œ„๋กœ ํŒŒ์ผ์„ ๋ถ„ํ• ํ•˜์—ฌ API ์š”์ฒญ ํšŸ์ˆ˜๋ฅผ ์ค„์ผ ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค. **4. ๋ณด์•ˆ ๊ด€๋ จ ์ด์Šˆ:** * **API ํ‚ค ๊ด€๋ฆฌ:** ์•ž์„œ ์–ธ๊ธ‰ํ–ˆ๋“ฏ์ด, API ํ‚ค๋ฅผ ํ™˜๊ฒฝ ๋ณ€์ˆ˜๋กœ ๊ด€๋ฆฌํ•˜๊ณ , ๊ฐ€๋Šฅํ•˜๋ฉด Google Cloud Client Library๋ฅผ ์‚ฌ์šฉํ•˜์—ฌ API ํ‚ค๋ฅผ ์ง์ ‘ ๋…ธ์ถœํ•˜์ง€ ์•Š๋„๋ก ํ•ด์•ผ ํ•ฉ๋‹ˆ๋‹ค. * **์ž…๋ ฅ ๊ฒ€์ฆ:** Gemini API์— ์ „๋‹ฌํ•˜๋Š” ์ฝ”๋“œ์— ๋Œ€ํ•œ ์ž…๋ ฅ ๊ฒ€์ฆ์ด ํ•„์š”ํ•ฉ๋‹ˆ๋‹ค. ์•…์„ฑ ์ฝ”๋“œ๊ฐ€ ํฌํ•จ๋œ ๊ฒฝ์šฐ API๋ฅผ ์•…์šฉํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค. **5. ๊ฐœ์„ ์„ ์œ„ํ•œ ๊ตฌ์ฒด์ ์ธ ์ œ์•ˆ:** * **Google Cloud Client Library ์‚ฌ์šฉ:** Google Cloud Client Library for Node.js๋ฅผ ์‚ฌ์šฉํ•˜์—ฌ Gemini API๋ฅผ ๋” ์•ˆ์ „ํ•˜๊ณ  ํšจ์œจ์ ์œผ๋กœ ํ˜ธ์ถœํ•ฉ๋‹ˆ๋‹ค. * **์˜ค๋ฅ˜ ์ฒ˜๋ฆฌ ๋ฐ ๋กœ๊น… ๊ฐ•ํ™”:** `try...catch` ๋ธ”๋ก์„ ์‚ฌ์šฉํ•˜์—ฌ ์—๋Ÿฌ๋ฅผ ์ฒ˜๋ฆฌํ•˜๊ณ , ์ž์„ธํ•œ ์—๋Ÿฌ ๋กœ๊ทธ๋ฅผ ๋‚จ๊ฒจ ๋ฌธ์ œ ํ•ด๊ฒฐ์„ ์šฉ์ดํ•˜๊ฒŒ ํ•ฉ๋‹ˆ๋‹ค. * **๋น„๋™๊ธฐ ์ฒ˜๋ฆฌ ๊ฐœ์„ :** `Promise.all`์„ ์‚ฌ์šฉํ•˜์—ฌ ๋ณ‘๋ ฌ ์ฒ˜๋ฆฌ๋ฅผ ๊ตฌํ˜„ํ•ฉ๋‹ˆ๋‹ค. * **์ž…๋ ฅ ๊ฒ€์ฆ ์ถ”๊ฐ€:** Gemini API์— ์ „๋‹ฌํ•˜๋Š” ์ฝ”๋“œ๋ฅผ ๊ฒ€์ฆํ•˜์—ฌ ๋ณด์•ˆ ์ทจ์•ฝ์„ฑ์„ ๋ฐฉ์ง€ํ•ฉ๋‹ˆ๋‹ค. * **์‘๋‹ต ์ฒ˜๋ฆฌ ๊ฐœ์„ :** Gemini API์˜ ์‘๋‹ต ๊ตฌ์กฐ๋ฅผ ๊ณ ๋ คํ•˜์—ฌ ๋” ์•ˆ์ •์ ์ธ ์‘๋‹ต ์ฒ˜๋ฆฌ ๋กœ์ง์„ ๊ตฌํ˜„ํ•ฉ๋‹ˆ๋‹ค. schema validation์„ ๊ณ ๋ คํ•ด๋ณผ ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค. * **์ฝ”๋“œ ๋ถ„ํ• :** `reviewCode` ํ•จ์ˆ˜๋ฅผ ๋” ์ž‘๊ณ  ํŠน์ • ๊ธฐ๋Šฅ์„ ๋‹ด๋‹นํ•˜๋Š” ์—ฌ๋Ÿฌ ํ•จ์ˆ˜๋กœ ๋ถ„ํ• ํ•˜์—ฌ ๊ฐ€๋…์„ฑ๊ณผ ์œ ์ง€๋ณด์ˆ˜์„ฑ์„ ๋†’์ž…๋‹ˆ๋‹ค. * **Diff ํŒŒ์‹ฑ:** `file.patch` ๋Œ€์‹  diff๋ฅผ ํŒŒ์‹ฑํ•˜์—ฌ ์‹ค์ œ ๋ณ€๊ฒฝ๋œ ์ค„์„ ์ฐพ์•„ ์ •ํ™•ํ•œ ์œ„์น˜์— ๋ฆฌ๋ทฐ ์ฝ”๋ฉ˜ํŠธ๋ฅผ ๋‚จ๊น๋‹ˆ๋‹ค. `diff` ๋ผ์ด๋ธŒ๋Ÿฌ๋ฆฌ๋ฅผ ์‚ฌ์šฉํ•˜๋Š” ๊ฒƒ์„ ๊ณ ๋ คํ•ด๋ณด์„ธ์š”. * **Rate Limiting:** Gemini API์˜ rate limit์„ ๊ณ ๋ คํ•˜์—ฌ ์š”์ฒญ ๋นˆ๋„๋ฅผ ์กฐ์ ˆํ•˜๋Š” ๋ฉ”์ปค๋‹ˆ์ฆ˜์„ ์ถ”๊ฐ€ํ•ด์•ผ ํ•ฉ๋‹ˆ๋‹ค. ์š”์•ฝํ•˜์ž๋ฉด, ์ด ์ฝ”๋“œ๋Š” ๊ธฐ๋Šฅ์ ์œผ๋กœ๋Š” ๋™์ž‘ํ•˜์ง€๋งŒ, ๋ณด์•ˆ, ์˜ค๋ฅ˜ ์ฒ˜๋ฆฌ, ์„ฑ๋Šฅ ์ธก๋ฉด์—์„œ ๊ฐœ์„ ์ด ํ•„์š”ํ•ฉ๋‹ˆ๋‹ค. ์œ„์—์„œ ์ œ์‹œ๋œ ์ œ์•ˆ์„ ๋ฐ”ํƒ•์œผ๋กœ ์ฝ”๋“œ๋ฅผ ๊ฐœ์„ ํ•˜๋ฉด ๋” ์•ˆ์ „ํ•˜๊ณ  ํšจ์œจ์ ์ธ ์ฝ”๋“œ ๋ฆฌ๋ทฐ ์‹œ์Šคํ…œ์„ ๊ตฌ์ถ•ํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค. ํŠนํžˆ Google Cloud Client Library ์‚ฌ์šฉ์€ ํ•„์ˆ˜์ ์œผ๋กœ ๊ณ ๋ คํ•ด์•ผ ํ•  ๋ถ€๋ถ„์ž…๋‹ˆ๋‹ค.
@@ -11,12 +11,178 @@ on: jobs: code_review: runs-on: ubuntu-latest - name: ChatGPT Code Review + name: Gemini Code Review steps: - - uses: anc95/ChatGPT-CodeReview@main + - uses: actions/checkout@v4 + + - name: Setup Node.js + uses: actions/setup-node@v4 + with: + node-version: "20" + + - name: Install dependencies + run: npm install @google/generative-ai parse-diff + + - name: Review Changed Files + uses: actions/github-script@v7 env: - GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} - OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }} - # optional - LANGUAGE: Korean - MODEL: gpt-4o-mini-2024-07-18 # https://platform.openai.com/docs/models + GEMINI_API_KEY: ${{ secrets.GEMINI_API_KEY }} + GEMINI_MODEL: ${{ secrets.GEMINI_MODEL }} + MAX_CONCURRENT_REVIEWS: 3 # ๋™์‹œ์— ์ฒ˜๋ฆฌํ•  ํŒŒ์ผ ์ˆ˜ + MAX_RETRIES: 3 + RETRY_DELAY: 1000 + + with: + script: | + const { GoogleGenerativeAI } = require("@google/generative-ai"); + const parseDiff = require('parse-diff'); + // core๋Š” ์ด๋ฏธ github-script์—์„œ ์ œ๊ณต๋จ + + // ์žฌ์‹œ๋„ ๋กœ์ง์„ ํฌํ•จํ•œ API ํ˜ธ์ถœ ํ•จ์ˆ˜ + async function withRetry(fn, retries = process.env.MAX_RETRIES) { + for (let i = 0; i < retries; i++) { + try { + return await fn(); + + } catch (error) { + if (error.message.includes('rate limit') && i < retries - 1) { + const delay = process.env.RETRY_DELAY * Math.pow(2, i); + console.log(`Rate limit hit, waiting ${delay}ms before retry ${i + 1}`); + + await new Promise(resolve => setTimeout(resolve, delay)); + continue; + } + + throw error; + } + } + } + + // Gemini AI ํด๋ผ์ด์–ธํŠธ ์ดˆ๊ธฐํ™” + const genAI = new GoogleGenerativeAI(process.env.GEMINI_API_KEY); + const model = genAI.getGenerativeModel({ model: process.env.GEMINI_MODEL }); + + /** + * ์ฝ”๋“œ ๋ณ€๊ฒฝ์‚ฌํ•ญ์„ ๊ฒ€ํ† ํ•˜๊ณ  ํ”ผ๋“œ๋ฐฑ์„ ์ƒ์„ฑ + * + * @param content ๋ฆฌ๋ทฐํ•  ์ฝ”๋“œ ๋‚ด์šฉ + * @param filename ํŒŒ์ผ๋ช… + * @returns ๋ฆฌ๋ทฐ ์ฝ”๋ฉ˜ํŠธ + */ + async function reviewCode(content, filename) { + try { + // ํŒŒ์ผ๋ช… sanitize + const sanitizedFilename = filename.replace(/[^a-zA-Z0-9.-_\/]/g, '_'); + + const prompt = `๋‹น์‹ ์€ ์‹œ๋‹ˆ์–ด ๊ฐœ๋ฐœ์ž์ž…๋‹ˆ๋‹ค. ์•„๋ž˜ ${sanitizedFilename} ํŒŒ์ผ์˜ ์ฝ”๋“œ๋ฅผ ๊ฒ€ํ† ํ•˜๊ณ  ๋‹ค์Œ ์‚ฌํ•ญ๋“ค์„ ํ•œ๊ตญ์–ด๋กœ ๋ฆฌ๋ทฐํ•ด์ฃผ์„ธ์š”: + 1. ์ฝ”๋“œ์˜ ํ’ˆ์งˆ๊ณผ ๊ฐ€๋…์„ฑ + 2. ์ž ์žฌ์ ์ธ ๋ฒ„๊ทธ๋‚˜ ๋ฌธ์ œ์  + 3. ์„ฑ๋Šฅ ๊ฐœ์„  ํฌ์ธํŠธ + 4. ๋ณด์•ˆ ๊ด€๋ จ ์ด์Šˆ + 5. ๊ฐœ์„ ์„ ์œ„ํ•œ ๊ตฌ์ฒด์ ์ธ ์ œ์•ˆ + + ์ฝ”๋“œ: + ${content}`; + + const result = await withRetry(() => model.generateContent(prompt)); + const response = await result.response; + + if (!response.text()) { + throw new Error('Gemini API returned empty response'); + } + + console.log(`Successfully reviewed ${filename}`); + return response.text(); + + } catch (error) { + console.error(`Error reviewing ${filename}:`, error); + return `โš ๏ธ ์ฝ”๋“œ ๋ฆฌ๋ทฐ ์ค‘ ์˜ค๋ฅ˜๊ฐ€ ๋ฐœ์ƒํ–ˆ์Šต๋‹ˆ๋‹ค: ${error.message} + ๋‹ค์‹œ ์‹œ๋„ํ•˜์‹œ๊ฑฐ๋‚˜ ๊ด€๋ฆฌ์ž์—๊ฒŒ ๋ฌธ์˜ํ•ด์ฃผ์„ธ์š”.`; + } + } + + /** + * PR์˜ ๊ฐ ํŒŒ์ผ์„ ์ฒ˜๋ฆฌํ•˜๊ณ  ๋ฆฌ๋ทฐ ์ฝ”๋ฉ˜ํŠธ ์ž‘์„ฑ + * @param file PR์—์„œ ๋ณ€๊ฒฝ๋œ ํŒŒ์ผ ์ •๋ณด + * @param pr PR ์ •๋ณด + */ + async function processFile(file, pr) { + if (file.status === 'removed') { + console.log(`Skipping removed file: ${file.filename}`); + return; + } + + try { + if (!file.patch) { + console.warn(`No patch found for ${file.filename}, skipping.`); + return; + } + + const diff = parseDiff(file.patch)[0]; + if (!diff || !diff.chunks) { + console.log(`No valid diff found for ${file.filename}`); + return; + } + + // ๋ชจ๋“  ๋ณ€๊ฒฝ์‚ฌํ•ญ์„ ํ•˜๋‚˜๋กœ ํ•ฉ์น˜๊ธฐ (์ถ”๊ฐ€๋œ ๋ถ€๋ถ„๋งŒ ํ•„ํ„ฐ๋ง) + const changes = diff.chunks + .flatMap(chunk => chunk.changes) + .filter(change => change.type === 'add'); + + if (changes.length === 0) { + console.log(`No added changes found in ${file.filename}`); + return; + } + + // ๋ณ€๊ฒฝ์‚ฌํ•ญ์„ ํ•˜๋‚˜์˜ ๋ฌธ์ž์—ด๋กœ ํ•ฉ์น˜๊ธฐ + const content = changes.map(change => change.content).join('\n'); + const review = await reviewCode(content, file.filename); + + // PR์— ๋ฆฌ๋ทฐ ์ฝ”๋ฉ˜ํŠธ ์ž‘์„ฑ (ํŒŒ์ผ๋ช…์„ ํ—ค๋”๋กœ ์ถ”๊ฐ€) + return github.rest.issues.createComment({ + owner: context.repo.owner, + repo: context.repo.repo, + issue_number: context.issue.number, + body: `## ${file.filename} ๋ฆฌ๋ทฐ\n\n${review}` + }); + + } catch (error) { + console.error(`Error processing ${file.filename}:`, error); + throw error; + } + } + + try { + // PR ์ •๋ณด ์กฐํšŒ + const { data: pr } = await github.rest.pulls.get({ + owner: context.repo.owner, + repo: context.repo.repo, + pull_number: context.issue.number, + }); + + // ๋ณ€๊ฒฝ๋œ ํŒŒ์ผ ๋ชฉ๋ก ์กฐํšŒ + const { data: files } = await github.rest.pulls.listFiles({ + owner: context.repo.owner, + repo: context.repo.repo, + pull_number: context.issue.number, + }); + + console.log(`Starting review of ${files.length} files...`); + + // ๋ชจ๋“  ํŒŒ์ผ ์ฒ˜๋ฆฌ ์™„๋ฃŒ๋ฅผ ๊ธฐ๋‹ค๋ฆผ + const promises = []; + const batchSize = parseInt(process.env.MAX_CONCURRENT_REVIEWS); + + for (let i = 0; i < files.length; i += batchSize) { + const batch = files.slice(i, i + batchSize); + const batchPromises = batch.map(file => processFile(file, pr)); + promises.push(...batchPromises); + } + + await Promise.all(promises); + console.log('All reviews completed successfully'); + + } catch (error) { + console.error('Workflow failed:', error); + core.setFailed(`Workflow failed: ${error.message}`); + }
Unknown
## Gemini Code Review Workflow ํŒŒ์ผ ๋ฆฌ๋ทฐ (code_review.yml) ๋‹ค์Œ์€ ์ œ๊ณต๋œ `code_review.yml` ํŒŒ์ผ์— ๋Œ€ํ•œ ์ƒ์„ธ ๋ฆฌ๋ทฐ์ž…๋‹ˆ๋‹ค. ์‹œ๋‹ˆ์–ด ๊ฐœ๋ฐœ์ž์˜ ๊ด€์ ์—์„œ ์ฝ”๋“œ ํ’ˆ์งˆ, ์ž ์žฌ์  ๋ฌธ์ œ์ , ์„ฑ๋Šฅ ๊ฐœ์„ , ๋ณด์•ˆ ์ด์Šˆ ๋ฐ ๊ฐœ์„  ์ œ์•ˆ์„ ๋‹ค๋ฃน๋‹ˆ๋‹ค. **1. ์ฝ”๋“œ์˜ ํ’ˆ์งˆ๊ณผ ๊ฐ€๋…์„ฑ** * **์ „๋ฐ˜์ ์œผ๋กœ ์–‘ํ˜ธ:** ์ฝ”๋“œ์˜ ๊ตฌ์กฐ๊ฐ€ ๋น„๊ต์  ๋ช…ํ™•ํ•˜๊ณ , ์ฃผ์„์ด ์ ์ ˆํ•˜๊ฒŒ ์‚ฌ์šฉ๋˜์–ด ๊ฐ€๋…์„ฑ์ด ๋†’์Šต๋‹ˆ๋‹ค. ํ•จ์ˆ˜๋ณ„ ์—ญํ•  ๋ถ„๋‹ด๋„ ์ž˜ ๋˜์–ด ์žˆ์Šต๋‹ˆ๋‹ค. * **ํ•จ์ˆ˜๋ช…:** ํ•จ์ˆ˜๋ช…(`reviewCode`, `processFile`)์€ ์—ญํ• ์„ ๋ช…ํ™•ํžˆ ์„ค๋ช…ํ•˜๋ฉฐ, ์ฝ”๋“œ ์ดํ•ด๋„๋ฅผ ๋†’์ž…๋‹ˆ๋‹ค. * **์ฃผ์„:** ๊ฐ ํ•จ์ˆ˜ ๋ฐ ์ฃผ์š” ๋กœ์ง์— ๋Œ€ํ•œ ์„ค๋ช… ์ฃผ์„์ด ์กด์žฌํ•˜์—ฌ ์ฝ”๋“œ์˜ ์˜๋„๋ฅผ ํŒŒ์•…ํ•˜๊ธฐ ์šฉ์ดํ•ฉ๋‹ˆ๋‹ค. ํ•˜์ง€๋งŒ ๋” ์ž์„ธํ•œ ์„ค๋ช…์ด ํ•„์š”ํ•œ ๋ถ€๋ถ„๋„ ์žˆ์Šต๋‹ˆ๋‹ค (์˜ˆ: `chunk` ํ•จ์ˆ˜). * **๋ณ€์ˆ˜๋ช…:** ๋ณ€์ˆ˜๋ช…์€ ์ „๋ฐ˜์ ์œผ๋กœ ๋ช…ํ™•ํ•˜๊ณ  ์˜๋ฏธ๋ฅผ ์ž˜ ๋‚˜ํƒ€๋ƒ…๋‹ˆ๋‹ค. **2. ์ž ์žฌ์ ์ธ ๋ฒ„๊ทธ๋‚˜ ๋ฌธ์ œ์ ** * **์—๋Ÿฌ ํ•ธ๋“ค๋ง:** `reviewCode` ํ•จ์ˆ˜์—์„œ Gemini API ํ˜ธ์ถœ ์‹คํŒจ ์‹œ ์˜ค๋ฅ˜ ๋ฉ”์‹œ์ง€๋ฅผ ๋ฐ˜ํ™˜ํ•˜์ง€๋งŒ, ์ดํ›„ ํ”„๋กœ์„ธ์Šค์—์„œ ํ•ด๋‹น ์˜ค๋ฅ˜๋ฅผ ์–ด๋–ป๊ฒŒ ์ฒ˜๋ฆฌํ•˜๋Š”์ง€์— ๋Œ€ํ•œ ๊ณ ๋ ค๊ฐ€ ๋ถ€์กฑํ•ฉ๋‹ˆ๋‹ค. ์˜ˆ๋ฅผ ๋“ค์–ด, ์˜ค๋ฅ˜๊ฐ€ ๋ฐœ์ƒํ•œ ํŒŒ์ผ์— ๋Œ€ํ•œ ๋ฆฌ๋ทฐ ์ฝ”๋ฉ˜ํŠธ ์ž‘์„ฑ์„ ์ค‘๋‹จํ•˜๊ณ , ๋‹ค๋ฅธ ํŒŒ์ผ๋“ค์„ ๊ณ„์† ์ฒ˜๋ฆฌํ•˜๋Š” ๊ฒƒ์ด ์ ์ ˆํ•œ์ง€ ํ™•์ธํ•ด์•ผ ํ•ฉ๋‹ˆ๋‹ค. * **API Rate Limiting:** `MAX_CONCURRENT_REVIEWS`๋ฅผ ์‚ฌ์šฉํ•˜์—ฌ rate limiting์„ ๋ฐฉ์ง€ํ•˜๋Š” ๊ฒƒ์€ ์ข‹์€ ์ „๋žต์ด์ง€๋งŒ, Gemini API ์ž์ฒด๊ฐ€ rate limiting์„ ์ ์šฉํ•  ์ˆ˜ ์žˆ์œผ๋ฏ€๋กœ, ๋” robustํ•œ ์—๋Ÿฌ ์ฒ˜๋ฆฌ ๋ฐ ์žฌ์‹œ๋„ ๋กœ์ง์ด ํ•„์š”ํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค. ํŠนํžˆ, ์˜ค๋ฅ˜ ๋ฉ”์‹œ์ง€๋ฅผ ํŒŒ์‹ฑํ•˜์—ฌ rate limit ๊ด€๋ จ ์—๋Ÿฌ์ธ์ง€ ํ™•์ธํ•˜๊ณ , ์ง€์ˆ˜ ๋ฐฑ์˜คํ”„(exponential backoff) ์ „๋žต์„ ์ ์šฉํ•˜๋Š” ๊ฒƒ์„ ๊ณ ๋ คํ•ด๋ณผ ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค. * **diff ํŒŒ์‹ฑ ์‹คํŒจ:** `parseDiff(file.patch)[0]`์—์„œ `file.patch`๊ฐ€ ์œ ํšจํ•˜์ง€ ์•Š์€ ๊ฒฝ์šฐ (์˜ˆ: binary ํŒŒ์ผ), ์—๋Ÿฌ๊ฐ€ ๋ฐœ์ƒํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค. `parseDiff` ํ•จ์ˆ˜์˜ ๊ฒฐ๊ณผ๋ฅผ ์ œ๋Œ€๋กœ ๊ฒ€์‚ฌํ•˜๊ณ , ์—๋Ÿฌ ๋ฐœ์ƒ ์‹œ ์ ์ ˆํ•œ ๋กœ๊น… ๋˜๋Š” ์Šคํ‚ต ์ฒ˜๋ฆฌ๋ฅผ ํ•ด์•ผ ํ•ฉ๋‹ˆ๋‹ค. * **๋นˆ ์‘๋‹ต ์ฒ˜๋ฆฌ:** `response.text()`๊ฐ€ ๋น„์–ด์žˆ๋Š” ๊ฒฝ์šฐ ์—๋Ÿฌ๋ฅผ ๋˜์ง€์ง€๋งŒ, ์ด ๊ฒฝ์šฐ GitHub์— ์–ด๋–ค ์ฝ”๋ฉ˜ํŠธ๊ฐ€ ๋‚จ๊ฒจ์ง€๋Š”์ง€ ๋ช…ํ™•ํ•˜์ง€ ์•Š์Šต๋‹ˆ๋‹ค. ๋นˆ ์‘๋‹ต์— ๋Œ€ํ•œ ๋” ์‚ฌ์šฉ์ž ์นœํ™”์ ์ธ ๋ฉ”์‹œ์ง€ (์˜ˆ: "Gemini API์—์„œ ์œ ํšจํ•œ ์‘๋‹ต์„ ๋ฐ›์ง€ ๋ชปํ–ˆ์Šต๋‹ˆ๋‹ค.")๋ฅผ ๋‚จ๊ธฐ๋Š” ๊ฒƒ์ด ์ข‹์Šต๋‹ˆ๋‹ค. * **`lineNumber` ๋ณ€์ˆ˜:** `lineNumber`๋Š” ์ฒญํฌ์˜ ์‹œ์ž‘ ๋ผ์ธ์„ ๋‚˜ํƒ€๋‚ด์ง€๋งŒ, ๋ฆฌ๋ทฐ๊ฐ€ ํŠน์ • ์ฝ”๋“œ ๋ผ์ธ์— ๋Œ€ํ•œ ๊ฒƒ์ผ ๊ฒฝ์šฐ ํ•ด๋‹น ๋ผ์ธ์„ ์ •ํ™•ํžˆ ๊ฐ€๋ฆฌํ‚ค์ง€ ์•Š์„ ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค. ๋”์šฑ ์ •๋ฐ€ํ•œ ๋ฆฌ๋ทฐ๋ฅผ ์œ„ํ•ด change๊ฐ€ ๋ฐœ์ƒํ•œ ๋ผ์ธ ๋ฒˆํ˜ธ๋ฅผ ํŠน์ •ํ•˜๋Š” ๋กœ์ง์„ ์ถ”๊ฐ€ํ•˜๋Š” ๊ฒƒ์„ ๊ณ ๋ คํ•ด๋ณผ ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค. * **์‚ญ์ œ๋œ ํŒŒ์ผ ์ฒ˜๋ฆฌ:** `file.status === 'removed'`์ธ ๊ฒฝ์šฐ ์Šคํ‚ตํ•˜์ง€๋งŒ, ์‹ค์ œ๋กœ ์‚ญ์ œ๋œ ํŒŒ์ผ์— ๋Œ€ํ•œ ์ฝ”๋ฉ˜ํŠธ๋ฅผ ๋‚จ๊ธฐ๋Š” ๊ฒƒ์ด ์œ ์šฉํ•œ ๊ฒฝ์šฐ๋„ ์žˆ์„ ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค (์˜ˆ: ์™œ ์‚ญ์ œ๋˜์—ˆ๋Š”์ง€, ๋Œ€์ฒด ์ฝ”๋“œ๋Š” ๋ฌด์—‡์ธ์ง€ ๋“ฑ). ์ƒํ™ฉ์— ๋”ฐ๋ผ ์‚ญ์ œ๋œ ํŒŒ์ผ์— ๋Œ€ํ•œ ๊ฐ„๋‹จํ•œ ์ฝ”๋ฉ˜ํŠธ๋ฅผ ์ถ”๊ฐ€ํ•˜๋Š” ๊ฒƒ์„ ๊ณ ๋ คํ•ด๋ณผ ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค. **3. ์„ฑ๋Šฅ ๊ฐœ์„  ํฌ์ธํŠธ** * **์ฒญํฌ ์ฒ˜๋ฆฌ:** ํ˜„์žฌ ์ฝ”๋“œ๋Š” ๊ฐ ์ฒญํฌ๋ณ„๋กœ `reviewCode` ํ•จ์ˆ˜๋ฅผ ํ˜ธ์ถœํ•ฉ๋‹ˆ๋‹ค. ์ด๋Š” Gemini API ํ˜ธ์ถœ ํšŸ์ˆ˜๋ฅผ ๋Š˜๋ฆฌ๊ณ  ์ „์ฒด ์‹คํ–‰ ์‹œ๊ฐ„์„ ์ฆ๊ฐ€์‹œํ‚ฌ ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค. ๊ฐ€๋Šฅํ•˜๋‹ค๋ฉด, ์—ฌ๋Ÿฌ ์ฒญํฌ๋ฅผ ๋ฌถ์–ด์„œ ํ•œ ๋ฒˆ์— `reviewCode` ํ•จ์ˆ˜๋ฅผ ํ˜ธ์ถœํ•˜๋Š” ๊ฒƒ์„ ๊ณ ๋ คํ•ด๋ณผ ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค. (ํ”„๋กฌํ”„ํŠธ ํฌ๊ธฐ ์ œํ•œ์„ ๊ณ ๋ คํ•ด์•ผ ํ•จ) * **๋ณ‘๋ ฌ ์ฒ˜๋ฆฌ:** ํ˜„์žฌ ํŒŒ์ผ ๋ชฉ๋ก์„ ์ˆœํšŒํ•˜๋ฉด์„œ `processFile` ํ•จ์ˆ˜๋ฅผ ๋ณ‘๋ ฌ๋กœ ์‹คํ–‰ํ•˜์ง€๋งŒ, `processFile` ํ•จ์ˆ˜ ๋‚ด์—์„œ๋„ ์ฒญํฌ๋“ค์„ ๋ณ‘๋ ฌ๋กœ ์ฒ˜๋ฆฌํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค. `Promise.all`์„ ์‚ฌ์šฉํ•˜์—ฌ ์ฒญํฌ ์ฒ˜๋ฆฌ ์†๋„๋ฅผ ๊ฐœ์„ ํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค. ๋‹ค๋งŒ, Gemini API์˜ rate limiting์„ ๋”์šฑ ์ฃผ์˜ํ•ด์•ผ ํ•ฉ๋‹ˆ๋‹ค. * **์บ์‹ฑ:** ๋งŒ์•ฝ ๋™์ผํ•œ ์ฝ”๋“œ๊ฐ€ ์—ฌ๋Ÿฌ ๋ฒˆ ๋ฆฌ๋ทฐ๋˜๋Š” ๊ฒฝ์šฐ, Gemini API์˜ ์‘๋‹ต์„ ์บ์‹ฑํ•˜์—ฌ ๋ถˆํ•„์š”ํ•œ API ํ˜ธ์ถœ์„ ์ค„์ผ ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค. (์บ์‹ฑ ์ „๋žต ๋ฐ ๋งŒ๋ฃŒ ์‹œ๊ฐ„์„ ์‹ ์ค‘ํ•˜๊ฒŒ ๊ฒฐ์ •ํ•ด์•ผ ํ•จ) **4. ๋ณด์•ˆ ๊ด€๋ จ ์ด์Šˆ** * **API Key ๊ด€๋ฆฌ:** Gemini API ํ‚ค(`GEMINI_API_KEY`)๋ฅผ GitHub Secrets์— ์•ˆ์ „ํ•˜๊ฒŒ ์ €์žฅํ•˜๋Š” ๊ฒƒ์€ ๋งค์šฐ ์ค‘์š”ํ•ฉ๋‹ˆ๋‹ค. * **ํ”„๋กฌํ”„ํŠธ ์ธ์ ์…˜:** Gemini API์— ์ „๋‹ฌ๋˜๋Š” ํ”„๋กฌํ”„ํŠธ์— ์‚ฌ์šฉ์ž ์ž…๋ ฅ (ํŠนํžˆ `filename`)์ด ํฌํ•จ๋˜์–ด ์žˆ์Šต๋‹ˆ๋‹ค. ์•…์˜์ ์ธ ์‚ฌ์šฉ์ž๊ฐ€ ํŒŒ์ผ ์ด๋ฆ„์„ ์กฐ์ž‘ํ•˜์—ฌ ์˜๋„์น˜ ์•Š์€ ๊ฒฐ๊ณผ๋ฅผ ์ดˆ๋ž˜ํ•  ์ˆ˜ ์žˆ๋Š” ํ”„๋กฌํ”„ํŠธ ์ธ์ ์…˜ ๊ณต๊ฒฉ์— ์ทจ์•ฝํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค. ํŒŒ์ผ ์ด๋ฆ„์— ๋Œ€ํ•œ ์œ ํšจ์„ฑ ๊ฒ€์‚ฌ ๋˜๋Š” ํ•„ํ„ฐ๋ง์„ ์ถ”๊ฐ€ํ•˜๋Š” ๊ฒƒ์„ ๊ณ ๋ คํ•ด์•ผ ํ•ฉ๋‹ˆ๋‹ค. * **์ฝ”๋“œ ์‹คํ–‰:** `actions/github-script` ์•ก์…˜์€ JavaScript ์ฝ”๋“œ๋ฅผ ์‹คํ–‰ํ•˜๋ฏ€๋กœ, ์˜์กด์„ฑ ํŒจํ‚ค์ง€(`@google/generative-ai`, `parse-diff`)์— ๋Œ€ํ•œ ๋ณด์•ˆ ์ทจ์•ฝ์  ๊ด€๋ฆฌ๊ฐ€ ์ค‘์š”ํ•ฉ๋‹ˆ๋‹ค. ์ •๊ธฐ์ ์œผ๋กœ ์˜์กด์„ฑ ํŒจํ‚ค์ง€๋ฅผ ์—…๋ฐ์ดํŠธํ•˜๊ณ , ๋ณด์•ˆ ๊ฒ€์‚ฌ๋ฅผ ์ˆ˜ํ–‰ํ•ด์•ผ ํ•ฉ๋‹ˆ๋‹ค. **5. ๊ฐœ์„ ์„ ์œ„ํ•œ ๊ตฌ์ฒด์ ์ธ ์ œ์•ˆ** * **์ƒ์„ธํ•œ ๋กœ๊น…:** ๊ฐ ๋‹จ๊ณ„๋ณ„๋กœ ๋กœ๊ทธ๋ฅผ ์ถ”๊ฐ€ํ•˜์—ฌ ๋””๋ฒ„๊น… ๋ฐ ๋ชจ๋‹ˆํ„ฐ๋ง์„ ์šฉ์ดํ•˜๊ฒŒ ํ•ฉ๋‹ˆ๋‹ค. ํŠนํžˆ, API ํ˜ธ์ถœ ์„ฑ๊ณต/์‹คํŒจ ์—ฌ๋ถ€, rate limiting ๋ฐœ์ƒ ์—ฌ๋ถ€, ํŒŒ์ผ ์ฒ˜๋ฆฌ ์‹œ๊ฐ„ ๋“ฑ์„ ๋กœ๊น…ํ•ฉ๋‹ˆ๋‹ค. * **์—๋Ÿฌ ์ฒ˜๋ฆฌ ๊ฐœ์„ :** `reviewCode` ํ•จ์ˆ˜์—์„œ ๋ฐœ์ƒํ•œ ์˜ค๋ฅ˜๋ฅผ ๋” ์ž์„ธํžˆ ์ฒ˜๋ฆฌํ•˜๊ณ , GitHub ์ฝ”๋ฉ˜ํŠธ๋ฅผ ํ†ตํ•ด ์‚ฌ์šฉ์ž์—๊ฒŒ ์•Œ๋ฆฝ๋‹ˆ๋‹ค. ์˜ˆ๋ฅผ ๋“ค์–ด, ์˜ค๋ฅ˜ ์œ ํ˜• (API ์˜ค๋ฅ˜, rate limiting, ํŒŒ์‹ฑ ์˜ค๋ฅ˜ ๋“ฑ)์„ ๋ช…์‹œํ•˜๊ณ , ๋ฌธ์ œ ํ•ด๊ฒฐ์„ ์œ„ํ•œ ๊ฐ€์ด๋“œ๋ผ์ธ์„ ์ œ๊ณตํ•ฉ๋‹ˆ๋‹ค. * **ํ…Œ์ŠคํŠธ ์ผ€์ด์Šค ์ถ”๊ฐ€:** ์ฝ”๋“œ ๋ณ€๊ฒฝ ์‚ฌํ•ญ์„ ๊ฒ€์ฆํ•˜๊ธฐ ์œ„ํ•œ ํ…Œ์ŠคํŠธ ์ผ€์ด์Šค๋ฅผ ์ถ”๊ฐ€ํ•ฉ๋‹ˆ๋‹ค. ํŠนํžˆ, ๋‹ค์–‘ํ•œ ํŒŒ์ผ ํ˜•์‹ (ํ…์ŠคํŠธ, JSON, YAML ๋“ฑ) ๋ฐ diff ํ˜•์‹์— ๋Œ€ํ•œ ํ…Œ์ŠคํŠธ๋ฅผ ์ˆ˜ํ–‰ํ•˜์—ฌ ์ฝ”๋“œ์˜ ์•ˆ์ •์„ฑ์„ ํ™•๋ณดํ•ฉ๋‹ˆ๋‹ค. * **๊ตฌ์„ฑ ์˜ต์…˜ ์ถ”๊ฐ€:** `MAX_CONCURRENT_REVIEWS` ์™ธ์—๋„, Gemini ๋ชจ๋ธ (`GEMINI_MODEL`) ๋ฐ ํ”„๋กฌํ”„ํŠธ ํ…œํ”Œ๋ฆฟ์„ ๊ตฌ์„ฑ ์˜ต์…˜์œผ๋กœ ์ œ๊ณตํ•˜์—ฌ ์‚ฌ์šฉ์ž๊ฐ€ ํ•„์š”์— ๋”ฐ๋ผ ์„ค์ •์„ ๋ณ€๊ฒฝํ•  ์ˆ˜ ์žˆ๋„๋ก ํ•ฉ๋‹ˆ๋‹ค. * **์ฝ”๋“œ ๋ฆฌ๋ทฐ ๊ฒฐ๊ณผ ์š”์•ฝ:** ๊ฐ ํŒŒ์ผ๋ณ„ ๋ฆฌ๋ทฐ ๊ฒฐ๊ณผ๋ฅผ ์š”์•ฝํ•˜์—ฌ PR์— ๋Œ€ํ•œ ์ „์ฒด์ ์ธ ์ฝ”๋“œ ํ’ˆ์งˆ์„ ํŒŒ์•…ํ•˜๊ธฐ ์‰ฝ๊ฒŒ ํ•ฉ๋‹ˆ๋‹ค. ์˜ˆ๋ฅผ ๋“ค์–ด, "์ด X๊ฐœ์˜ ํŒŒ์ผ์—์„œ Y๊ฐœ์˜ ๋ฌธ์ œ์ ์ด ๋ฐœ๊ฒฌ๋˜์—ˆ์Šต๋‹ˆ๋‹ค. ์ž์„ธํ•œ ๋‚ด์šฉ์€ ๊ฐ ํŒŒ์ผ์˜ ์ฝ”๋ฉ˜ํŠธ๋ฅผ ์ฐธ์กฐํ•˜์„ธ์š”."์™€ ๊ฐ™์€ ์š”์•ฝ ์ •๋ณด๋ฅผ ์ œ๊ณตํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค. * **ํ”„๋กฌํ”„ํŠธ ์ตœ์ ํ™”:** ์ฝ”๋“œ ๋ฆฌ๋ทฐ ํ’ˆ์งˆ์„ ๋†’์ด๊ธฐ ์œ„ํ•ด Gemini API์— ์ „๋‹ฌ๋˜๋Š” ํ”„๋กฌํ”„ํŠธ๋ฅผ ์ง€์†์ ์œผ๋กœ ๊ฐœ์„ ํ•ฉ๋‹ˆ๋‹ค. ์˜ˆ๋ฅผ ๋“ค์–ด, ์ฝ”๋“œ ๋ฆฌ๋ทฐ ๊ธฐ์ค€์„ ๋”์šฑ ๋ช…ํ™•ํ•˜๊ฒŒ ์ œ์‹œํ•˜๊ฑฐ๋‚˜, ํŠน์ • ํ”„๋กœ๊ทธ๋ž˜๋ฐ ์–ธ์–ด ๋˜๋Š” ํ”„๋ ˆ์ž„์›Œํฌ์— ๋Œ€ํ•œ ์ง€์นจ์„ ์ถ”๊ฐ€ํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค. * **PR ํ…œํ”Œ๋ฆฟ ํ™œ์šฉ:** PR ์ž‘์„ฑ์ž๊ฐ€ ์ฝ”๋“œ ๋ณ€๊ฒฝ ์‚ฌํ•ญ์— ๋Œ€ํ•œ ์ •๋ณด๋ฅผ ๋ฏธ๋ฆฌ ์ œ๊ณตํ•˜๋„๋ก PR ํ…œํ”Œ๋ฆฟ์„ ํ™œ์šฉํ•ฉ๋‹ˆ๋‹ค. ์ด๋Š” Gemini API๊ฐ€ ๋”์šฑ ์ •ํ™•ํ•˜๊ณ  ๊ด€๋ จ์„ฑ ๋†’์€ ๋ฆฌ๋ทฐ๋ฅผ ์ƒ์„ฑํ•˜๋Š” ๋ฐ ๋„์›€์ด ๋  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค. **๊ฒฐ๋ก :** ์ „๋ฐ˜์ ์œผ๋กœ ์ž˜ ์ž‘์„ฑ๋œ ์›Œํฌํ”Œ๋กœ์šฐ ํŒŒ์ผ์ด์ง€๋งŒ, ์—๋Ÿฌ ์ฒ˜๋ฆฌ, API Rate Limiting, ๋ณด์•ˆ ๋ฐ ์„ฑ๋Šฅ ์ธก๋ฉด์—์„œ ๊ฐœ์„ ํ•  ์—ฌ์ง€๊ฐ€ ์žˆ์Šต๋‹ˆ๋‹ค. ์ œ์•ˆ๋œ ๊ฐœ์„  ์‚ฌํ•ญ๋“ค์„ ์ ์šฉํ•˜์—ฌ ์ฝ”๋“œ ๋ฆฌ๋ทฐ ํ”„๋กœ์„ธ์Šค๋ฅผ ๋”์šฑ ์•ˆ์ •์ ์ด๊ณ  ํšจ์œจ์ ์œผ๋กœ ๋งŒ๋“ค ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค. ํŠนํžˆ, ์‹ค์ œ ์šด์˜ ํ™˜๊ฒฝ์—์„œ ๋ฐœ์ƒํ•  ์ˆ˜ ์žˆ๋Š” ๋‹ค์–‘ํ•œ ์˜ˆ์™ธ ์ƒํ™ฉ์„ ๊ณ ๋ คํ•˜์—ฌ ์ฝ”๋“œ๋ฅผ ๋ณด์™„ํ•˜๋Š” ๊ฒƒ์ด ์ค‘์š”ํ•ฉ๋‹ˆ๋‹ค.
@@ -11,12 +11,178 @@ on: jobs: code_review: runs-on: ubuntu-latest - name: ChatGPT Code Review + name: Gemini Code Review steps: - - uses: anc95/ChatGPT-CodeReview@main + - uses: actions/checkout@v4 + + - name: Setup Node.js + uses: actions/setup-node@v4 + with: + node-version: "20" + + - name: Install dependencies + run: npm install @google/generative-ai parse-diff + + - name: Review Changed Files + uses: actions/github-script@v7 env: - GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} - OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }} - # optional - LANGUAGE: Korean - MODEL: gpt-4o-mini-2024-07-18 # https://platform.openai.com/docs/models + GEMINI_API_KEY: ${{ secrets.GEMINI_API_KEY }} + GEMINI_MODEL: ${{ secrets.GEMINI_MODEL }} + MAX_CONCURRENT_REVIEWS: 3 # ๋™์‹œ์— ์ฒ˜๋ฆฌํ•  ํŒŒ์ผ ์ˆ˜ + MAX_RETRIES: 3 + RETRY_DELAY: 1000 + + with: + script: | + const { GoogleGenerativeAI } = require("@google/generative-ai"); + const parseDiff = require('parse-diff'); + // core๋Š” ์ด๋ฏธ github-script์—์„œ ์ œ๊ณต๋จ + + // ์žฌ์‹œ๋„ ๋กœ์ง์„ ํฌํ•จํ•œ API ํ˜ธ์ถœ ํ•จ์ˆ˜ + async function withRetry(fn, retries = process.env.MAX_RETRIES) { + for (let i = 0; i < retries; i++) { + try { + return await fn(); + + } catch (error) { + if (error.message.includes('rate limit') && i < retries - 1) { + const delay = process.env.RETRY_DELAY * Math.pow(2, i); + console.log(`Rate limit hit, waiting ${delay}ms before retry ${i + 1}`); + + await new Promise(resolve => setTimeout(resolve, delay)); + continue; + } + + throw error; + } + } + } + + // Gemini AI ํด๋ผ์ด์–ธํŠธ ์ดˆ๊ธฐํ™” + const genAI = new GoogleGenerativeAI(process.env.GEMINI_API_KEY); + const model = genAI.getGenerativeModel({ model: process.env.GEMINI_MODEL }); + + /** + * ์ฝ”๋“œ ๋ณ€๊ฒฝ์‚ฌํ•ญ์„ ๊ฒ€ํ† ํ•˜๊ณ  ํ”ผ๋“œ๋ฐฑ์„ ์ƒ์„ฑ + * + * @param content ๋ฆฌ๋ทฐํ•  ์ฝ”๋“œ ๋‚ด์šฉ + * @param filename ํŒŒ์ผ๋ช… + * @returns ๋ฆฌ๋ทฐ ์ฝ”๋ฉ˜ํŠธ + */ + async function reviewCode(content, filename) { + try { + // ํŒŒ์ผ๋ช… sanitize + const sanitizedFilename = filename.replace(/[^a-zA-Z0-9.-_\/]/g, '_'); + + const prompt = `๋‹น์‹ ์€ ์‹œ๋‹ˆ์–ด ๊ฐœ๋ฐœ์ž์ž…๋‹ˆ๋‹ค. ์•„๋ž˜ ${sanitizedFilename} ํŒŒ์ผ์˜ ์ฝ”๋“œ๋ฅผ ๊ฒ€ํ† ํ•˜๊ณ  ๋‹ค์Œ ์‚ฌํ•ญ๋“ค์„ ํ•œ๊ตญ์–ด๋กœ ๋ฆฌ๋ทฐํ•ด์ฃผ์„ธ์š”: + 1. ์ฝ”๋“œ์˜ ํ’ˆ์งˆ๊ณผ ๊ฐ€๋…์„ฑ + 2. ์ž ์žฌ์ ์ธ ๋ฒ„๊ทธ๋‚˜ ๋ฌธ์ œ์  + 3. ์„ฑ๋Šฅ ๊ฐœ์„  ํฌ์ธํŠธ + 4. ๋ณด์•ˆ ๊ด€๋ จ ์ด์Šˆ + 5. ๊ฐœ์„ ์„ ์œ„ํ•œ ๊ตฌ์ฒด์ ์ธ ์ œ์•ˆ + + ์ฝ”๋“œ: + ${content}`; + + const result = await withRetry(() => model.generateContent(prompt)); + const response = await result.response; + + if (!response.text()) { + throw new Error('Gemini API returned empty response'); + } + + console.log(`Successfully reviewed ${filename}`); + return response.text(); + + } catch (error) { + console.error(`Error reviewing ${filename}:`, error); + return `โš ๏ธ ์ฝ”๋“œ ๋ฆฌ๋ทฐ ์ค‘ ์˜ค๋ฅ˜๊ฐ€ ๋ฐœ์ƒํ–ˆ์Šต๋‹ˆ๋‹ค: ${error.message} + ๋‹ค์‹œ ์‹œ๋„ํ•˜์‹œ๊ฑฐ๋‚˜ ๊ด€๋ฆฌ์ž์—๊ฒŒ ๋ฌธ์˜ํ•ด์ฃผ์„ธ์š”.`; + } + } + + /** + * PR์˜ ๊ฐ ํŒŒ์ผ์„ ์ฒ˜๋ฆฌํ•˜๊ณ  ๋ฆฌ๋ทฐ ์ฝ”๋ฉ˜ํŠธ ์ž‘์„ฑ + * @param file PR์—์„œ ๋ณ€๊ฒฝ๋œ ํŒŒ์ผ ์ •๋ณด + * @param pr PR ์ •๋ณด + */ + async function processFile(file, pr) { + if (file.status === 'removed') { + console.log(`Skipping removed file: ${file.filename}`); + return; + } + + try { + if (!file.patch) { + console.warn(`No patch found for ${file.filename}, skipping.`); + return; + } + + const diff = parseDiff(file.patch)[0]; + if (!diff || !diff.chunks) { + console.log(`No valid diff found for ${file.filename}`); + return; + } + + // ๋ชจ๋“  ๋ณ€๊ฒฝ์‚ฌํ•ญ์„ ํ•˜๋‚˜๋กœ ํ•ฉ์น˜๊ธฐ (์ถ”๊ฐ€๋œ ๋ถ€๋ถ„๋งŒ ํ•„ํ„ฐ๋ง) + const changes = diff.chunks + .flatMap(chunk => chunk.changes) + .filter(change => change.type === 'add'); + + if (changes.length === 0) { + console.log(`No added changes found in ${file.filename}`); + return; + } + + // ๋ณ€๊ฒฝ์‚ฌํ•ญ์„ ํ•˜๋‚˜์˜ ๋ฌธ์ž์—ด๋กœ ํ•ฉ์น˜๊ธฐ + const content = changes.map(change => change.content).join('\n'); + const review = await reviewCode(content, file.filename); + + // PR์— ๋ฆฌ๋ทฐ ์ฝ”๋ฉ˜ํŠธ ์ž‘์„ฑ (ํŒŒ์ผ๋ช…์„ ํ—ค๋”๋กœ ์ถ”๊ฐ€) + return github.rest.issues.createComment({ + owner: context.repo.owner, + repo: context.repo.repo, + issue_number: context.issue.number, + body: `## ${file.filename} ๋ฆฌ๋ทฐ\n\n${review}` + }); + + } catch (error) { + console.error(`Error processing ${file.filename}:`, error); + throw error; + } + } + + try { + // PR ์ •๋ณด ์กฐํšŒ + const { data: pr } = await github.rest.pulls.get({ + owner: context.repo.owner, + repo: context.repo.repo, + pull_number: context.issue.number, + }); + + // ๋ณ€๊ฒฝ๋œ ํŒŒ์ผ ๋ชฉ๋ก ์กฐํšŒ + const { data: files } = await github.rest.pulls.listFiles({ + owner: context.repo.owner, + repo: context.repo.repo, + pull_number: context.issue.number, + }); + + console.log(`Starting review of ${files.length} files...`); + + // ๋ชจ๋“  ํŒŒ์ผ ์ฒ˜๋ฆฌ ์™„๋ฃŒ๋ฅผ ๊ธฐ๋‹ค๋ฆผ + const promises = []; + const batchSize = parseInt(process.env.MAX_CONCURRENT_REVIEWS); + + for (let i = 0; i < files.length; i += batchSize) { + const batch = files.slice(i, i + batchSize); + const batchPromises = batch.map(file => processFile(file, pr)); + promises.push(...batchPromises); + } + + await Promise.all(promises); + console.log('All reviews completed successfully'); + + } catch (error) { + console.error('Workflow failed:', error); + core.setFailed(`Workflow failed: ${error.message}`); + }
Unknown
## .github/workflows/code_review.yml ์ฝ”๋“œ ๋ฆฌ๋ทฐ ๋‹ค์Œ์€ ์ฃผ์–ด์ง„ `.github/workflows/code_review.yml` ํŒŒ์ผ์— ๋Œ€ํ•œ ์ฝ”๋“œ ๋ฆฌ๋ทฐ์ž…๋‹ˆ๋‹ค. **1. ์ฝ”๋“œ ํ’ˆ์งˆ ๋ฐ ๊ฐ€๋…์„ฑ** * **์ „๋ฐ˜์ ์œผ๋กœ ์–‘ํ˜ธ:** ์ฝ”๋“œ๋Š” ๋น„๊ต์  ๊น”๋”ํ•˜๊ณ  ๊ฐ€๋…์„ฑ์ด ์ข‹์Šต๋‹ˆ๋‹ค. ์ฃผ์„๋„ ์ ์ ˆํ•˜๊ฒŒ ๋‹ฌ๋ ค ์žˆ์–ด ์ฝ”๋“œ์˜ ์˜๋„๋ฅผ ํŒŒ์•…ํ•˜๋Š” ๋ฐ ๋„์›€์ด ๋ฉ๋‹ˆ๋‹ค. * **์ผ๊ด€์„ฑ:** ๋“ค์—ฌ์“ฐ๊ธฐ, ๋ณ€์ˆ˜๋ช… ๊ทœ์น™ ๋“ฑ์ด ์ผ๊ด€์„ฑ์„ ์œ ์ง€ํ•˜๊ณ  ์žˆ์Šต๋‹ˆ๋‹ค. * **๋ชจ๋“ˆํ™”:** `reviewCode`, `processFile` ๋“ฑ์˜ ํ•จ์ˆ˜๋กœ ๋กœ์ง์„ ๋ถ„๋ฆฌํ•˜์—ฌ ์žฌ์‚ฌ์šฉ์„ฑ๊ณผ ์œ ์ง€๋ณด์ˆ˜์„ฑ์„ ๋†’์˜€์Šต๋‹ˆ๋‹ค. * **ํ†ต๊ณ„ ์ˆ˜์ง‘:** `stats` ๊ฐ์ฒด๋ฅผ ์‚ฌ์šฉํ•˜์—ฌ ์ฝ”๋“œ ๋ฆฌ๋ทฐ ๊ณผ์ •์— ๋Œ€ํ•œ ํ†ต๊ณ„๋ฅผ ์ˆ˜์ง‘ํ•˜๋Š” ๊ฒƒ์€ ์œ ์šฉํ•ฉ๋‹ˆ๋‹ค. ๋ฌธ์ œ ๋ฐœ์ƒ ์‹œ ๋””๋ฒ„๊น…์— ๋„์›€์ด ๋  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค. **2. ์ž ์žฌ์ ์ธ ๋ฒ„๊ทธ ๋˜๋Š” ๋ฌธ์ œ์ ** * **์—๋Ÿฌ ํ•ธ๋“ค๋ง:** `try...catch` ๋ธ”๋ก์„ ์‚ฌ์šฉํ•˜์—ฌ ์—๋Ÿฌ๋ฅผ ์ฒ˜๋ฆฌํ•˜๊ณ  ์žˆ์ง€๋งŒ, ์—๋Ÿฌ ๋ฉ”์‹œ์ง€๋ฅผ ์‚ฌ์šฉ์ž์—๊ฒŒ ์นœ์ ˆํ•˜๊ฒŒ ๋ณด์—ฌ์ฃผ๋Š” ๊ฒƒ์€ ์ค‘์š”ํ•ฉ๋‹ˆ๋‹ค. `reviewCode` ํ•จ์ˆ˜์—์„œ ์—๋Ÿฌ ๋ฐœ์ƒ ์‹œ "โš ๏ธ ์ฝ”๋“œ ๋ฆฌ๋ทฐ ์ค‘ ์˜ค๋ฅ˜๊ฐ€ ๋ฐœ์ƒํ–ˆ์Šต๋‹ˆ๋‹ค..."์™€ ๊ฐ™์€ ๋ฉ”์‹œ์ง€๋ฅผ ๋ณด์—ฌ์ฃผ๋Š” ๊ฒƒ์€ ์ข‹์€ ์˜ˆ์‹œ์ž…๋‹ˆ๋‹ค. * **Rate Limit ์ฒ˜๋ฆฌ:** `withRetry` ํ•จ์ˆ˜๋ฅผ ํ†ตํ•ด rate limit์„ ์ฒ˜๋ฆฌํ•˜๋Š” ๊ฒƒ์€ ์ข‹์Šต๋‹ˆ๋‹ค. ํ•˜์ง€๋งŒ `RETRY_DELAY`๋ฅผ ๊ณ ์ • ๊ฐ’์œผ๋กœ ์‚ฌ์šฉํ•˜๋Š” ๊ฒƒ๋ณด๋‹ค, ๋ฐฑ์˜คํ”„(backoff) ์ „๋žต์„ ์‚ฌ์šฉํ•˜๋Š” ๊ฒƒ์ด ์ข‹์Šต๋‹ˆ๋‹ค. ์˜ˆ๋ฅผ ๋“ค์–ด, ๋งค retry๋งˆ๋‹ค ๋”œ๋ ˆ์ด๋ฅผ ๋Š˜๋ฆฌ๋Š” ๋ฐฉ์‹์ž…๋‹ˆ๋‹ค. * **`file.patch` ์—๋Ÿฌ ์ฒ˜๋ฆฌ:** `parseDiff(file.patch)[0]` ๋ถ€๋ถ„์—์„œ, `file.patch`๊ฐ€ ์กด์žฌํ•˜์ง€ ์•Š๊ฑฐ๋‚˜ ์œ ํšจํ•˜์ง€ ์•Š์€ ๊ฒฝ์šฐ์— ๋Œ€ํ•œ ์˜ˆ์™ธ ์ฒ˜๋ฆฌ๊ฐ€ ํ•„์š”ํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค. `parseDiff` ํ•จ์ˆ˜๊ฐ€ ์—๋Ÿฌ๋ฅผ ๋˜์งˆ ๊ฐ€๋Šฅ์„ฑ์ด ์žˆ๋Š”์ง€ ํ™•์ธํ•˜๊ณ , ์žˆ๋‹ค๋ฉด `try...catch` ๋ธ”๋ก์œผ๋กœ ๊ฐ์‹ธ๋Š” ๊ฒƒ์„ ๊ณ ๋ คํ•˜์‹ญ์‹œ์˜ค. * **ํŒŒ์ผ ์ด๋ฆ„ sanitize:** ํŒŒ์ผ ์ด๋ฆ„ sanitize ๋กœ์ง์ด ์ถฉ๋ถ„ํžˆ ์•ˆ์ „ํ•œ์ง€ ๊ฒ€ํ† ํ•ด์•ผ ํ•ฉ๋‹ˆ๋‹ค. ํŠนํžˆ ํŠน์ˆ˜๋ฌธ์ž๊ฐ€ ํฌํ•จ๋œ ๊ฒฝ์šฐ ์˜ˆ์ƒ์น˜ ๋ชปํ•œ ๊ฒฐ๊ณผ๋ฅผ ์ดˆ๋ž˜ํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค. * **๋™์‹œ์„ฑ ์ฒ˜๋ฆฌ:** `MAX_CONCURRENT_REVIEWS`๋ฅผ ์‚ฌ์šฉํ•˜์—ฌ ๋™์‹œ์„ฑ ์ฒ˜๋ฆฌ๋ฅผ ํ•˜๋Š” ๊ฒƒ์€ ์ข‹์ง€๋งŒ, ํŒŒ์ผ ์ˆ˜๊ฐ€ ์ ์„ ๊ฒฝ์šฐ ๋ณ‘๋ ฌ ์ฒ˜๋ฆฌ๊ฐ€ ์˜คํžˆ๋ ค ์˜ค๋ฒ„ํ—ค๋“œ๊ฐ€ ๋  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค. ํŒŒ์ผ ์ˆ˜์— ๋”ฐ๋ผ ๋™์‹œ์„ฑ ์ฒ˜๋ฆฌ๋ฅผ ํ™œ์„ฑํ™”/๋น„ํ™œ์„ฑํ™”ํ•˜๋Š” ๋กœ์ง์„ ์ถ”๊ฐ€ํ•˜๋Š” ๊ฒƒ์„ ๊ณ ๋ คํ•ด๋ณผ ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค. * **`summary` ์—๋Ÿฌ ๋ฉ”์‹œ์ง€ ๋ˆ„๋ฝ:** `stats.issues`์— ๋‹ด๊ธด ์—๋Ÿฌ ๋ฉ”์‹œ์ง€๊ฐ€ ๋งค์šฐ ๊ธธ ๊ฒฝ์šฐ, summary ์ฝ”๋ฉ˜ํŠธ์— ์ „๋ถ€ ๋‹ด๊ธฐ์ง€ ์•Š์„ ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค. summary ์ฝ”๋ฉ˜ํŠธ์˜ ์ตœ๋Œ€ ๊ธธ์ด๋ฅผ ๊ณ ๋ คํ•˜์—ฌ ๋ฉ”์‹œ์ง€๋ฅผ ์ž๋ฅด๊ฑฐ๋‚˜ ์š”์•ฝํ•˜๋Š” ๋ฐฉ์•ˆ์„ ๊ณ ๋ คํ•ด๋ณผ ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค. * **๋ฆฌ๋ทฐ ์ฝ”๋ฉ˜ํŠธ ์œ„์น˜:** ์ฒซ ๋ฒˆ์งธ ์ฒญํฌ์˜ ์‹œ์ž‘ ๋ผ์ธ์—๋งŒ ๋ฆฌ๋ทฐ ์ฝ”๋ฉ˜ํŠธ๋ฅผ ์ž‘์„ฑํ•˜๋Š” ๊ฒƒ์€ ๋ณ€๊ฒฝ ์‚ฌํ•ญ์ด ์—ฌ๋Ÿฌ ์ฒญํฌ์— ๊ฑธ์ณ ์žˆ์„ ๊ฒฝ์šฐ ๋ˆ„๋ฝ๋˜๋Š” ๋ถ€๋ถ„์ด ์žˆ์„ ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค. ๊ฐ ์ฒญํฌ๋ณ„๋กœ ์ฝ”๋ฉ˜ํŠธ๋ฅผ ์ž‘์„ฑํ•˜๊ฑฐ๋‚˜, ๋ณ€๊ฒฝ ์‚ฌํ•ญ ์ „์ฒด์— ๋Œ€ํ•œ ์ฝ”๋ฉ˜ํŠธ๋ฅผ ์ž‘์„ฑํ•˜๋Š” ๊ฒƒ์„ ๊ณ ๋ คํ•ด๋ณผ ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค. * **`create-or-update-comment` ์•ก์…˜์˜ ์ค‘๋ณต ํ—ค๋”:** workflow ๋งˆ์ง€๋ง‰ ๋ถ€๋ถ„์— "## Code Review Summary" ํ—ค๋”๊ฐ€ ์ค‘๋ณต๋ฉ๋‹ˆ๋‹ค. ์ด์ „ ์ฝ”๋“œ์—์„œ Summary๋ฅผ ์ด๋ฏธ ์ƒ์„ฑํ–ˆ์œผ๋ฏ€๋กœ, ๋งˆ์ง€๋ง‰ ์•ก์…˜์—์„œ๋Š” ๊ฐ„๋‹จํ•œ ์™„๋ฃŒ ๋ฉ”์‹œ์ง€๋งŒ ๋‚จ๊ธฐ๋Š” ๊ฒƒ์ด ์ข‹์Šต๋‹ˆ๋‹ค. **3. ์„ฑ๋Šฅ ๊ฐœ์„  ํฌ์ธํŠธ** * **API ํ˜ธ์ถœ ์ตœ์ ํ™”:** Gemini API ํ˜ธ์ถœ ํšŸ์ˆ˜๋ฅผ ์ค„์ด๋Š” ๊ฒƒ์ด ์ค‘์š”ํ•ฉ๋‹ˆ๋‹ค. ๊ฐ€๋Šฅํ•˜๋‹ค๋ฉด ์—ฌ๋Ÿฌ ํŒŒ์ผ์— ๋Œ€ํ•œ ๋ฆฌ๋ทฐ๋ฅผ ํ•œ ๋ฒˆ์˜ API ํ˜ธ์ถœ๋กœ ์ฒ˜๋ฆฌํ•˜๋Š” ๊ฒƒ์„ ๊ณ ๋ คํ•˜์‹ญ์‹œ์˜ค. (Gemini API์˜ ์ตœ๋Œ€ ์ž…๋ ฅ ํฌ๊ธฐ ์ œํ•œ์„ ๊ณ ๋ คํ•ด์•ผ ํ•ฉ๋‹ˆ๋‹ค.) * **๋ถˆํ•„์š”ํ•œ ๋ฐ์ดํ„ฐ ์ฒ˜๋ฆฌ:** PR ์ •๋ณด ์กฐํšŒ(`github.rest.pulls.get`)๋Š” ๋ชจ๋“  ํŒŒ์ผ์— ๋Œ€ํ•ด ๋™์ผํ•˜๊ฒŒ ์ˆ˜ํ–‰๋ฉ๋‹ˆ๋‹ค. PR ์ •๋ณด๋ฅผ ํ•œ ๋ฒˆ๋งŒ ์กฐํšŒํ•˜๊ณ , ํŒŒ์ผ ์ฒ˜๋ฆฌ ํ•จ์ˆ˜์— ์ „๋‹ฌํ•˜๋Š” ๊ฒƒ์ด ํšจ์œจ์ ์ž…๋‹ˆ๋‹ค. * **`parse-diff` ๊ฒฐ๊ณผ ์บ์‹ฑ:** `parse-diff`๋Š” ๋น„๊ต์  ๋ฌด๊ฑฐ์šด ์ž‘์—…์ผ ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค. `file.patch`๊ฐ€ ๋™์ผํ•œ ๊ฒฝ์šฐ `parse-diff` ๊ฒฐ๊ณผ๋ฅผ ์บ์‹ฑํ•˜์—ฌ ์žฌ์‚ฌ์šฉํ•˜๋Š” ๊ฒƒ์„ ๊ณ ๋ คํ•ด๋ณผ ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค. (๋‹จ, ๋ฉ”๋ชจ๋ฆฌ ์‚ฌ์šฉ๋Ÿ‰์„ ๊ณ ๋ คํ•ด์•ผ ํ•ฉ๋‹ˆ๋‹ค.) **4. ๋ณด์•ˆ ๊ด€๋ จ ์ด์Šˆ** * **API ํ‚ค ๋ณด์•ˆ:** `GEMINI_API_KEY`๋Š” GitHub Actions secrets์— ์•ˆ์ „ํ•˜๊ฒŒ ์ €์žฅ๋˜์–ด ์žˆ์œผ๋ฏ€๋กœ ์•ˆ์ „ํ•ฉ๋‹ˆ๋‹ค. ํ•˜์ง€๋งŒ, ์ฝ”๋“œ ๋‚ด์—์„œ API ํ‚ค๊ฐ€ ๋…ธ์ถœ๋˜์ง€ ์•Š๋„๋ก ์ฃผ์˜ํ•ด์•ผ ํ•ฉ๋‹ˆ๋‹ค. * **์ž…๋ ฅ๊ฐ’ ๊ฒ€์ฆ:** ์‚ฌ์šฉ์ž๋กœ๋ถ€ํ„ฐ ์ž…๋ ฅ๋ฐ›๋Š” ๋ฐ์ดํ„ฐ (์˜ˆ: ํŒŒ์ผ ์ด๋ฆ„, ์ฝ”๋“œ ๋‚ด์šฉ)์— ๋Œ€ํ•œ ๊ฒ€์ฆ์„ ์ˆ˜ํ–‰ํ•˜์—ฌ injection ๊ณต๊ฒฉ์„ ๋ฐฉ์ง€ํ•ด์•ผ ํ•ฉ๋‹ˆ๋‹ค. ํŒŒ์ผ ์ด๋ฆ„ sanitize๋Š” ์ข‹์€ ์˜ˆ์‹œ์ด์ง€๋งŒ, ๋‹ค๋ฅธ ์ž…๋ ฅ๊ฐ’์— ๋Œ€ํ•ด์„œ๋„ ๊ฒ€์ฆ์„ ์ˆ˜ํ–‰ํ•ด์•ผ ํ•ฉ๋‹ˆ๋‹ค. * **์„œ๋“œํŒŒํ‹ฐ ๋ผ์ด๋ธŒ๋Ÿฌ๋ฆฌ:** `@google/generative-ai`, `parse-diff` ๋“ฑ ์„œ๋“œํŒŒํ‹ฐ ๋ผ์ด๋ธŒ๋Ÿฌ๋ฆฌ์˜ ๋ณด์•ˆ ์ทจ์•ฝ์ ์„ ์ฃผ๊ธฐ์ ์œผ๋กœ ํ™•์ธํ•˜๊ณ  ์—…๋ฐ์ดํŠธํ•ด์•ผ ํ•ฉ๋‹ˆ๋‹ค. Dependabot ๋“ฑ์„ ์‚ฌ์šฉํ•˜์—ฌ ์˜์กด์„ฑ ๊ด€๋ฆฌ๋ฅผ ์ž๋™ํ™”ํ•˜๋Š” ๊ฒƒ์„ ๊ณ ๋ คํ•˜์‹ญ์‹œ์˜ค. **5. ๊ฐœ์„ ์„ ์œ„ํ•œ ๊ตฌ์ฒด์ ์ธ ์ œ์•ˆ** 1. **๋ฐฑ์˜คํ”„(Backoff) ์ „๋žต ์ ์šฉ:** `withRetry` ํ•จ์ˆ˜์—์„œ `RETRY_DELAY`๋ฅผ ๊ณ ์ • ๊ฐ’ ๋Œ€์‹  ์ง€์ˆ˜ ๋ฐฑ์˜คํ”„(exponential backoff) ์ „๋žต์„ ์‚ฌ์šฉํ•˜์—ฌ rate limit ์ƒํ™ฉ์— ๋”์šฑ ํšจ๊ณผ์ ์œผ๋กœ ๋Œ€์‘ํ•ฉ๋‹ˆ๋‹ค. ```javascript async function withRetry(fn, retries = process.env.MAX_RETRIES) { for (let i = 0; i < retries; i++) { try { return await fn(); } catch (error) { if (error.message.includes('rate limit') && i < retries - 1) { const delay = process.env.RETRY_DELAY * Math.pow(2, i); // ์ง€์ˆ˜ ๋ฐฑ์˜คํ”„ console.log(`Rate limit hit, waiting ${delay}ms before retry ${i + 1}`); await new Promise(resolve => setTimeout(resolve, delay)); continue; } throw error; } } } ``` 2. **PR ์ •๋ณด ์บ์‹ฑ:** PR ์ •๋ณด๋ฅผ ํ•œ ๋ฒˆ๋งŒ ์กฐํšŒํ•˜๊ณ , `processFile` ํ•จ์ˆ˜์— ์ „๋‹ฌํ•ฉ๋‹ˆ๋‹ค. ```javascript // PR ์ •๋ณด ์กฐํšŒ const { data: pr } = await github.rest.pulls.get({ owner: context.repo.owner, repo: context.repo.repo, pull_number: context.issue.number, }); // ํŒŒ์ผ ์ฒ˜๋ฆฌ (3๊ฐœ์”ฉ ๋™์‹œ ์ฒ˜๋ฆฌ) for (let i = 0; i < files.length; i += 3) { const batch = files.slice(i, i + 3); await Promise.all(batch.map(file => processFile(file, pr))); } // processFile ํ•จ์ˆ˜ ์ˆ˜์ • async function processFile(file, pr) { ... } ``` 3. **Rate Limit ์ •๋ณด ๋กœ๊น…:** rate limit์— ๊ฑธ๋ ธ์„ ๋•Œ, ๋‚จ์•„์žˆ๋Š” limit๊ณผ reset ์‹œ๊ฐ„ ์ •๋ณด๋ฅผ ๋กœ๊ทธ์— ์ถœ๋ ฅํ•˜์—ฌ ๋””๋ฒ„๊น…์— ํ™œ์šฉํ•ฉ๋‹ˆ๋‹ค. (Gemini API์—์„œ ํ•ด๋‹น ์ •๋ณด๋ฅผ ์ œ๊ณตํ•˜๋Š”์ง€ ํ™•์ธํ•ด์•ผ ํ•ฉ๋‹ˆ๋‹ค.) 4. **์ƒ์„ธ ์—๋Ÿฌ ๋กœ๊น…:** ์—๋Ÿฌ ๋ฐœ์ƒ ์‹œ ์Šคํƒ ํŠธ๋ ˆ์ด์Šค ์ „์ฒด๋ฅผ ๋กœ๊น…ํ•˜์—ฌ ๋ฌธ์ œ ํ•ด๊ฒฐ์— ๋„์›€์„ ์ค๋‹ˆ๋‹ค. ```javascript console.error(`Error reviewing ${filename}:`, error, error.stack); ``` 5. **๋ฆฌ๋ทฐ ์š”์•ฝ ๊ฐœ์„ :** summary ์ฝ”๋ฉ˜ํŠธ์— ์—๋Ÿฌ ๋ฉ”์‹œ์ง€๊ฐ€ ์ž˜๋ ค์„œ ํ‘œ์‹œ๋˜๋Š” ๋ฌธ์ œ๋ฅผ ํ•ด๊ฒฐํ•˜๊ธฐ ์œ„ํ•ด, ์—๋Ÿฌ ๋ฉ”์‹œ์ง€๋ฅผ ์š”์•ฝํ•˜๊ฑฐ๋‚˜, ์—๋Ÿฌ ๋ฉ”์‹œ์ง€ ์ „์ฒด๋ฅผ ํ‘œ์‹œํ•  ์ˆ˜ ์žˆ๋Š” ๋ณ„๋„์˜ ํŽ˜์ด์ง€๋ฅผ ๋งํฌํ•˜๋Š” ๋ฐฉ์•ˆ์„ ๊ณ ๋ คํ•ด๋ณผ ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค. 6. **๋งˆ์ง€๋ง‰ ์ฝ”๋ฉ˜ํŠธ ์•ก์…˜ ์ˆ˜์ •:** ๋งˆ์ง€๋ง‰ ์ฝ”๋ฉ˜ํŠธ ์•ก์…˜์—์„œ ํ—ค๋”๋ฅผ ์ œ๊ฑฐํ•˜๊ณ , ๊ฐ„๋‹จํ•œ ์™„๋ฃŒ ๋ฉ”์‹œ์ง€๋งŒ ๋‚จ๊น๋‹ˆ๋‹ค. ```yaml - name: Create or Update Comment uses: peter-evans/create-or-update-comment@v3 with: comment-id: ${{ steps.fc.outputs.comment-id }} issue-number: ${{ github.event.pull_request.number }} body: | ์ฝ”๋“œ ๋ฆฌ๋ทฐ๊ฐ€ ์™„๋ฃŒ๋˜์—ˆ์Šต๋‹ˆ๋‹ค. ๊ฐ ํŒŒ์ผ์˜ ๋ณ€๊ฒฝ์‚ฌํ•ญ์— ๋Œ€ํ•œ ํ”ผ๋“œ๋ฐฑ์„ ํ™•์ธํ•ด์ฃผ์„ธ์š”. edit-mode: replace ``` ์ด๋Ÿฌํ•œ ๊ฐœ์„  ์‚ฌํ•ญ๋“ค์„ ์ ์šฉํ•˜๋ฉด ์ฝ”๋“œ ๋ฆฌ๋ทฐ ์›Œํฌํ”Œ๋กœ์šฐ์˜ ํ’ˆ์งˆ, ์„ฑ๋Šฅ, ์•ˆ์ •์„ฑ์„ ๋”์šฑ ํ–ฅ์ƒ์‹œํ‚ฌ ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.
@@ -0,0 +1,88 @@ +import styled from "styled-components"; + +export const ReviewSectionName = styled.h2` + +`; + +export const ReviewFormArea = styled.div` + position: absolute; + width: 918px; + height: 240px; + padding: 14px 23px; + background-color: #00462A; + border-radius: 20px; + flex-direction: column; + gap: 15px; +`; + +export const Conditions = styled.div` + display: flex; + flex-direction: row; + align-items: center; + gap: 15px; +`; + +export const IfReward = styled.label` + display: flex; + align-items: center; + gap: 4px; + flex-direction: row-reverse; + color: #FFFFFF; + font-size: 14px; +`; + +export const Checkbox = styled.input` + width: 16px; + height: 16px; + cursor: pointer; + border-radius: 20px; +`; + +export const Number = styled.input` + margin-left: 20px; + border-radius: 20px; + padding: 8px; + border: none; + width: 100px; +`; + +export const DropDown = styled.select` + border-radius: 20px; + padding: 8px; + border: none; + width: 100px; + cursor: pointer; + appearance: none; + + option{ + font-size: 14px; + color: #333333; + } +`; + +export const ReviewContent = styled.div` + margin-top: 15px; + width: 884px; + height: 99px; + + textarea { + width: 100%; + height: 100%; + resize: none; + overflow: auto; + border-radius: 18px; + padding: 12px 17px; + border: none; + font-size: 14px; + } +`; + +export const Button = styled.button` + margin-top: 40px; + outline: none; + border: none; + width: 923px; + height: 50px; + background-color: #F0F7F4; + border-radius: 20px; +`; \ No newline at end of file
Unknown
styled-component ๊น”๋”ํ•˜๊ฒŒ ์ž˜ ์“ฐ์‹  ๊ฒƒ ๊ฐ™์•„์š”! ์ˆ˜๊ณ  ๋งŽ์œผ์…จ์Šต๋‹ˆ๋‹ค~
@@ -0,0 +1,91 @@ +package christmas.Controller; + +import christmas.Domain.EventBenefitSettler; +import christmas.Domain.EventPlanner; +import christmas.Event.EventBadge; +import christmas.View.InputView; +import christmas.View.OutputView; +import java.util.Map; + +public class EventController { + public EventPlanner eventPlanner; + public EventBenefitSettler eventBenefitSettler; + + public void eventStart() { + OutputView.printWelcomeMessage(); + takeVisitDate(); + + takeOrder(); + + int preDiscountTotalOrderPrice = handlePreDiscountTotalOrderPrice(); + + handleBenefit(preDiscountTotalOrderPrice); + } + + public void takeVisitDate() { + try { + String visitDate = InputView.readVisitDate(); + eventBenefitSettler = new EventBenefitSettler(visitDate); + } catch (NumberFormatException e) { + OutputView.printException(e); + takeVisitDate(); + } catch (IllegalArgumentException e) { + OutputView.printException(e); + takeVisitDate(); + } + } + + public void takeOrder() { + try { + String orderMenu = InputView.readMenuOrder(); + eventPlanner = new EventPlanner(orderMenu); + OutputView.printOrderMenu(orderMenu); + } catch (NumberFormatException e) { + OutputView.printException(e); + takeOrder(); + } catch (IllegalArgumentException e) { + OutputView.printException(e); + takeOrder(); + } + } + + public void handleBenefit(int preDiscountTotalOrderPrice) { + Map<String, Integer> categoryCount = eventPlanner.calculateCategoryCount(); + + Map<String, Integer> receivedBenefits = handleReceivedBenefits(categoryCount, preDiscountTotalOrderPrice); + int benefitsTotalAmount = handlebenefitsTotalAmount(receivedBenefits); + handleDiscountedTotalAmount(receivedBenefits, preDiscountTotalOrderPrice); + handleEventBadge(benefitsTotalAmount); + } + + public Map<String, Integer> handleReceivedBenefits(Map<String, Integer> categoryCount, int preDiscountTotalOrderPrice){ + Map<String, Integer> receivedBenefits = eventBenefitSettler.calculateReceivedBenefits(categoryCount, + preDiscountTotalOrderPrice); + OutputView.printReceivedBenefits(receivedBenefits); + return receivedBenefits; + } + + public int handlebenefitsTotalAmount(Map<String, Integer> receivedBenefits){ + int benefitsTotalAmount = eventBenefitSettler.caculateBenefitsTotalAmount(receivedBenefits); + OutputView.printBenefitsTotalAmount(benefitsTotalAmount); + return benefitsTotalAmount; + } + + public void handleDiscountedTotalAmount(Map<String, Integer> receivedBenefits, int preDiscountTotalOrderPrice){ + int discountedTotalAmount = eventBenefitSettler.calculateDiscountedTotalAmount(receivedBenefits, + preDiscountTotalOrderPrice); + OutputView.printDiscountedTotalAmount(discountedTotalAmount); + } + + public void handleEventBadge(int benefitsTotalAmount){ + String eventBadgeType = EventBadge.findMyEventBadgeType(benefitsTotalAmount); + OutputView.printEventBadgeType(eventBadgeType); + } + + public int handlePreDiscountTotalOrderPrice() { + int preDiscountTotalOrderPrice = eventPlanner.calculatePreDiscountTotalOrderPrice(); + OutputView.printPreDicountTotalOrderPrice(preDiscountTotalOrderPrice); + OutputView.printGiftMenu(preDiscountTotalOrderPrice); + return preDiscountTotalOrderPrice; + } +}
Java
```suggestion public void takeVisitDate() { try { String visitDate = InputView.readVisitDate(); eventBenefitSettler = new EventBenefitSettler(visitDate); } catch (IllegalArgumentException e) { OutputView.printException(e); takeVisitDate(); } } ``` ์ €๋„ ๋ฐฉ๊ธˆ ์ฐพ์•„์„œ ์•Œ๊ฒŒ ๋˜์—ˆ๋Š”๋ฐ `NumberFormatException` ์˜ ๋ถ€๋ชจ ์˜ˆ์™ธ๊ฐ€ `IllegalArgumentException` ์ด๋”๋ผ๊ณ ์š”! ๊ทธ๋ž˜์„œ ๊ตณ์ด ๋‘˜์˜ ์˜ˆ์™ธ๋ฅผ ๋‚˜๋ˆ„์ง€ ์•Š๊ณ  `IllegalArgumentException` ๋งŒ ์žก์•„์ค˜๋„ ๊ฐ™์ด ์žกํž ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค! ใ…Žใ…Ž
@@ -0,0 +1,92 @@ +package christmas.Util; + +import static christmas.Event.EventOption.EVENT_END_DATE; +import static christmas.Event.EventOption.EVENT_START_DATE; +import static christmas.Event.EventOption.MAX_ORDER_QUANTITY; +import static christmas.Message.OutputMessage.NOT_A_VALID_DATE; + +import christmas.Domain.MenuBoard; +import christmas.Message.OutputMessage; + +import java.util.HashSet; +import java.util.Set; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +public class OrderMenuValidator { + public static void validateDate(String input) { + int number = Integer.parseInt(input); + if (number < EVENT_START_DATE || number > EVENT_END_DATE) { + throw new IllegalArgumentException(NOT_A_VALID_DATE); + } + } + + public static void checkValidOrderForm(String input) { + String pattern = "^[๊ฐ€-ํžฃ]+-[0-9]+(,\\s*[๊ฐ€-ํžฃ]+-[0-9]+)*$"; // ๋ฉ”๋‰ด ์ž…๋ ฅ ํ˜•์‹ + if (!input.matches(pattern)) { + throw new IllegalArgumentException(OutputMessage.INVALID_ORDER_FORM_ERROR); + } + } + + public static void checkDuplicateMenu(String input) { + // ์ •๊ทœํ‘œํ˜„์‹ ํŒจํ„ด + String pattern = "([๊ฐ€-ํžฃ]+)-([1-9]\\d*|0*[1-9]\\d+)(?:,|$)"; + + // ์ •๊ทœํ‘œํ˜„์‹์— ๋งž๋Š” ํŒจํ„ด์„ ์ƒ์„ฑ + Pattern regexPattern = Pattern.compile(pattern); + Matcher matcher = regexPattern.matcher(input); + + Set<String> menuSet = new HashSet<>(); + // ๋งค์นญ๋œ ๊ฒฐ๊ณผ๋ฅผ ์ถœ๋ ฅ + while (matcher.find()) { + String menuName = matcher.group(1); + if (!menuSet.add(menuName)) { + throw new IllegalArgumentException(OutputMessage.INVALID_ORDER_FORM_ERROR); + } + } + } + + public static void checkMaxOrderQuantity(String input) { + String pattern = "([๊ฐ€-ํžฃ]+)-([1-9]\\d*|0*[1-9]\\d+)(?:,|$)"; + // ์ •๊ทœํ‘œํ˜„์‹์— ๋งž๋Š” ํŒจํ„ด์„ ์ƒ์„ฑ + Pattern regexPattern = Pattern.compile(pattern); + Matcher matcher = regexPattern.matcher(input); + int menuQuantity = 0; + // ๋งค์นญ๋œ ๊ฒฐ๊ณผ๋ฅผ ์ถœ๋ ฅ + while (matcher.find()) { + menuQuantity += Integer.parseInt(matcher.group(2)); + } + if (menuQuantity > MAX_ORDER_QUANTITY) { + throw new IllegalArgumentException(OutputMessage.INVALID_MAX_ORDER_QAUNTITY_ERROR); + } + } + + public static void checkMenuContainsOnlyDrink(String input) { + String pattern = "([๊ฐ€-ํžฃ]+)-([1-9]\\d*|0*[1-9]\\d+)(?:,|$)"; + + Pattern regexPattern = Pattern.compile(pattern); + Matcher matcher = regexPattern.matcher(input); + int menuNum = 0; + int drinkNum = 0; + + while (matcher.find()) { + if (isDrinkMenu(matcher.group(1))) { + drinkNum++; + } + menuNum++; + } + if (drinkNum == menuNum) { + throw new IllegalArgumentException(OutputMessage.MENU_CONTAIN_ONLY_DRINK_ERROR); + } + } + + public static boolean isDrinkMenu(String orderMenu) { + for (MenuBoard menu : MenuBoard.values()) { + if (orderMenu.equals(menu.getMenuName()) && menu.getMenuCategory().equals("์Œ๋ฃŒ")) { + return true; + } + } + return false; + } + +}
Java
์ •๊ทœํ‘œํ˜„์‹์„ ์ •๋ง ์ž˜ ํ™œ์šฉํ•˜์‹œ๋Š”๊ตฐ์š”!๐Ÿ‘๐Ÿ‘ ๊ทธ๋Ÿฐ๋ฐ `(?:,|$)` ๋Š” ์–ด๋–ค ์—ญํ• ์„ ํ•˜๋Š”์ง€ ๊ถ๊ธˆํ•ฉ๋‹ˆ๋‹ค!
@@ -0,0 +1,92 @@ +package christmas.Util; + +import static christmas.Event.EventOption.EVENT_END_DATE; +import static christmas.Event.EventOption.EVENT_START_DATE; +import static christmas.Event.EventOption.MAX_ORDER_QUANTITY; +import static christmas.Message.OutputMessage.NOT_A_VALID_DATE; + +import christmas.Domain.MenuBoard; +import christmas.Message.OutputMessage; + +import java.util.HashSet; +import java.util.Set; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +public class OrderMenuValidator { + public static void validateDate(String input) { + int number = Integer.parseInt(input); + if (number < EVENT_START_DATE || number > EVENT_END_DATE) { + throw new IllegalArgumentException(NOT_A_VALID_DATE); + } + } + + public static void checkValidOrderForm(String input) { + String pattern = "^[๊ฐ€-ํžฃ]+-[0-9]+(,\\s*[๊ฐ€-ํžฃ]+-[0-9]+)*$"; // ๋ฉ”๋‰ด ์ž…๋ ฅ ํ˜•์‹ + if (!input.matches(pattern)) { + throw new IllegalArgumentException(OutputMessage.INVALID_ORDER_FORM_ERROR); + } + } + + public static void checkDuplicateMenu(String input) { + // ์ •๊ทœํ‘œํ˜„์‹ ํŒจํ„ด + String pattern = "([๊ฐ€-ํžฃ]+)-([1-9]\\d*|0*[1-9]\\d+)(?:,|$)"; + + // ์ •๊ทœํ‘œํ˜„์‹์— ๋งž๋Š” ํŒจํ„ด์„ ์ƒ์„ฑ + Pattern regexPattern = Pattern.compile(pattern); + Matcher matcher = regexPattern.matcher(input); + + Set<String> menuSet = new HashSet<>(); + // ๋งค์นญ๋œ ๊ฒฐ๊ณผ๋ฅผ ์ถœ๋ ฅ + while (matcher.find()) { + String menuName = matcher.group(1); + if (!menuSet.add(menuName)) { + throw new IllegalArgumentException(OutputMessage.INVALID_ORDER_FORM_ERROR); + } + } + } + + public static void checkMaxOrderQuantity(String input) { + String pattern = "([๊ฐ€-ํžฃ]+)-([1-9]\\d*|0*[1-9]\\d+)(?:,|$)"; + // ์ •๊ทœํ‘œํ˜„์‹์— ๋งž๋Š” ํŒจํ„ด์„ ์ƒ์„ฑ + Pattern regexPattern = Pattern.compile(pattern); + Matcher matcher = regexPattern.matcher(input); + int menuQuantity = 0; + // ๋งค์นญ๋œ ๊ฒฐ๊ณผ๋ฅผ ์ถœ๋ ฅ + while (matcher.find()) { + menuQuantity += Integer.parseInt(matcher.group(2)); + } + if (menuQuantity > MAX_ORDER_QUANTITY) { + throw new IllegalArgumentException(OutputMessage.INVALID_MAX_ORDER_QAUNTITY_ERROR); + } + } + + public static void checkMenuContainsOnlyDrink(String input) { + String pattern = "([๊ฐ€-ํžฃ]+)-([1-9]\\d*|0*[1-9]\\d+)(?:,|$)"; + + Pattern regexPattern = Pattern.compile(pattern); + Matcher matcher = regexPattern.matcher(input); + int menuNum = 0; + int drinkNum = 0; + + while (matcher.find()) { + if (isDrinkMenu(matcher.group(1))) { + drinkNum++; + } + menuNum++; + } + if (drinkNum == menuNum) { + throw new IllegalArgumentException(OutputMessage.MENU_CONTAIN_ONLY_DRINK_ERROR); + } + } + + public static boolean isDrinkMenu(String orderMenu) { + for (MenuBoard menu : MenuBoard.values()) { + if (orderMenu.equals(menu.getMenuName()) && menu.getMenuCategory().equals("์Œ๋ฃŒ")) { + return true; + } + } + return false; + } + +}
Java
`isDrinkMenu` ๋Š” `MenuBoard` ์—๊ฒŒ ๋„˜๊ฒจ์ฃผ๋ฉด ์–ด๋–จ๊นŒ์š”?? ์Œ๋ฃŒ๋ฅผ ํ™•์ธํ•˜๋Š” ์ฑ…์ž„์€ `MenuBoard` ๊ฐ€ ๊ฐ€์ง€๊ณ  ์žˆ๋Š”๊ฒŒ ๋” ์–ด์šธ๋ฆด ๊ฒƒ ๊ฐ™์•„์š”! ๐Ÿ˜
@@ -0,0 +1,92 @@ +package christmas.Util; + +import static christmas.Event.EventOption.EVENT_END_DATE; +import static christmas.Event.EventOption.EVENT_START_DATE; +import static christmas.Event.EventOption.MAX_ORDER_QUANTITY; +import static christmas.Message.OutputMessage.NOT_A_VALID_DATE; + +import christmas.Domain.MenuBoard; +import christmas.Message.OutputMessage; + +import java.util.HashSet; +import java.util.Set; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +public class OrderMenuValidator { + public static void validateDate(String input) { + int number = Integer.parseInt(input); + if (number < EVENT_START_DATE || number > EVENT_END_DATE) { + throw new IllegalArgumentException(NOT_A_VALID_DATE); + } + } + + public static void checkValidOrderForm(String input) { + String pattern = "^[๊ฐ€-ํžฃ]+-[0-9]+(,\\s*[๊ฐ€-ํžฃ]+-[0-9]+)*$"; // ๋ฉ”๋‰ด ์ž…๋ ฅ ํ˜•์‹ + if (!input.matches(pattern)) { + throw new IllegalArgumentException(OutputMessage.INVALID_ORDER_FORM_ERROR); + } + } + + public static void checkDuplicateMenu(String input) { + // ์ •๊ทœํ‘œํ˜„์‹ ํŒจํ„ด + String pattern = "([๊ฐ€-ํžฃ]+)-([1-9]\\d*|0*[1-9]\\d+)(?:,|$)"; + + // ์ •๊ทœํ‘œํ˜„์‹์— ๋งž๋Š” ํŒจํ„ด์„ ์ƒ์„ฑ + Pattern regexPattern = Pattern.compile(pattern); + Matcher matcher = regexPattern.matcher(input); + + Set<String> menuSet = new HashSet<>(); + // ๋งค์นญ๋œ ๊ฒฐ๊ณผ๋ฅผ ์ถœ๋ ฅ + while (matcher.find()) { + String menuName = matcher.group(1); + if (!menuSet.add(menuName)) { + throw new IllegalArgumentException(OutputMessage.INVALID_ORDER_FORM_ERROR); + } + } + } + + public static void checkMaxOrderQuantity(String input) { + String pattern = "([๊ฐ€-ํžฃ]+)-([1-9]\\d*|0*[1-9]\\d+)(?:,|$)"; + // ์ •๊ทœํ‘œํ˜„์‹์— ๋งž๋Š” ํŒจํ„ด์„ ์ƒ์„ฑ + Pattern regexPattern = Pattern.compile(pattern); + Matcher matcher = regexPattern.matcher(input); + int menuQuantity = 0; + // ๋งค์นญ๋œ ๊ฒฐ๊ณผ๋ฅผ ์ถœ๋ ฅ + while (matcher.find()) { + menuQuantity += Integer.parseInt(matcher.group(2)); + } + if (menuQuantity > MAX_ORDER_QUANTITY) { + throw new IllegalArgumentException(OutputMessage.INVALID_MAX_ORDER_QAUNTITY_ERROR); + } + } + + public static void checkMenuContainsOnlyDrink(String input) { + String pattern = "([๊ฐ€-ํžฃ]+)-([1-9]\\d*|0*[1-9]\\d+)(?:,|$)"; + + Pattern regexPattern = Pattern.compile(pattern); + Matcher matcher = regexPattern.matcher(input); + int menuNum = 0; + int drinkNum = 0; + + while (matcher.find()) { + if (isDrinkMenu(matcher.group(1))) { + drinkNum++; + } + menuNum++; + } + if (drinkNum == menuNum) { + throw new IllegalArgumentException(OutputMessage.MENU_CONTAIN_ONLY_DRINK_ERROR); + } + } + + public static boolean isDrinkMenu(String orderMenu) { + for (MenuBoard menu : MenuBoard.values()) { + if (orderMenu.equals(menu.getMenuName()) && menu.getMenuCategory().equals("์Œ๋ฃŒ")) { + return true; + } + } + return false; + } + +}
Java
ํ•ด๋‹น ์ •๊ทœํ‘œํ˜„์‹์ด ๋ฐ˜๋ณต๋˜๋Š” ๊ฒƒ ๊ฐ™์•„์š”! ๊ทธ๋ ‡๋‹ค๋ฉด Pattern ๊ฐ์ฒด๋ฅผ ์บ์‹ฑํ•ด์ฃผ๋ฉด ์–ด๋–จ๊นŒ์š”?? ๋””์Šค์ฝ”๋“œ ํ•จ๊ป˜ ๋‚˜๋ˆ„๊ธฐ์— ํ˜„์ง€๋‹˜์ด[ ๊ณต์œ ํ•˜์‹  ๊ธ€](https://velog.io/@dlguswl936/%EA%B3%B5%EB%B6%80%ED%95%9C-%EA%B2%83-String.matches%EB%8A%94-%EC%99%9C-%EC%84%B1%EB%8A%A5%EC%97%90-%EC%95%88-%EC%A2%8B%EC%9D%84%EA%B9%8C#%EA%B2%B0%EB%A1%A0-pattern-%EA%B0%9D%EC%B2%B4%EB%A5%BC-%EC%BA%90%EC%8B%B1%ED%95%B4%EB%91%90%EA%B8%B0)์ด ๋„์›€์ด ๋˜์‹ค ๊ฒƒ ๊ฐ™์•„์„œ ๊ณต์œ ํ•ฉ๋‹ˆ๋‹ค!