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
 |
@@ -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)์ด ๋์์ด ๋์ค ๊ฒ ๊ฐ์์ ๊ณต์ ํฉ๋๋ค! |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.