code
stringlengths 41
34.3k
| lang
stringclasses 8
values | review
stringlengths 1
4.74k
|
|---|---|---|
@@ -0,0 +1,30 @@
+package christmas.Util;
+
+public class CommaFormatter {
+ public static String formatWithComma(int number) {
+ String numberStr = Integer.toString(number);
+ int length = numberStr.length();
+
+ if (length <= 3) {
+ return numberStr;
+ }
+ String result = insertComma(numberStr, length);
+
+ return result;
+ }
+
+ private static String insertComma(String number, int length) {
+ int count = 0;
+ StringBuilder result = new StringBuilder();
+ for (int i = length - 1; i >= 0; i--) {
+ result.insert(0, number.charAt(i));
+ count++;
+
+ if (count == 3 && i != 0) {
+ result.insert(0, ',');
+ count = 0;
+ }
+ }
+ return result.toString();
+ }
+}
|
Java
|
์ฝค๋ง๋ฅผ ์ํด ์ ์ฉ ๊ฐ์ฒด๋ฅผ ๋ง๋ค์ด์ฃผ์
จ๊ตฐ์! ์ง์ ๋ง๋ค์ด์ฃผ๋ ๊ฒ๋ ์ข๋ค์!
๊ทธ๋ฐ๋ฐ ๋ ๋จ์๋ฅผ ์ํ ์ฝค๋ง๋ฅผ ๋ฃ์ด์ฃผ๋ ๊ธฐ๋ฅ์ ์๋ฐ์์ ์ ๊ณตํ๊ณ ์๋ต๋๋ค! ใ
ใ
DecimalFormat ์ ๋ํด์ ์์๋ณด์๋ฉด ์ข์ ๊ฒ ๊ฐ์์! ์ ๊ฐ [์ฐธ๊ณ ํ๋ ๊ธ](https://jamesdreaming.tistory.com/203)์ ๊ณต์ ํฉ๋๋ค!
|
@@ -0,0 +1,67 @@
+package christmas.Domain;
+
+import christmas.Util.OrderMenuValidator;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+
+public class EventPlanner {
+ private final List<Menu> orderMenu;
+
+ public EventPlanner(String menu) {
+ validateOrderMenuForm(menu);
+ List<Menu> orderMenu = createOrderMenuRepository(menu);
+ this.orderMenu = orderMenu;
+ }
+
+ public int calculatePreDiscountTotalOrderPrice() {
+ int totalOrderPrice = 0;
+ for (Menu menu : orderMenu) {
+ totalOrderPrice += menu.getMenuTotalPrice();
+ }
+ return totalOrderPrice;
+ }
+
+ public Map<String, Integer> calculateCategoryCount() {
+ Map<String, Integer> categoryCount = new HashMap<>();
+ int count = 0;
+ for (Menu menu : orderMenu) {
+ String menuCategory = menu.getMenuCategory();
+ if (categoryCount.containsKey(menuCategory)) {
+ count = categoryCount.get(menuCategory) + menu.getMenuQuantity();
+ categoryCount.put(menuCategory, count);
+ }
+ if (!categoryCount.containsKey(menuCategory)) {
+ categoryCount.put(menuCategory, menu.getMenuQuantity());
+ }
+ }
+ return categoryCount;
+ }
+
+ private List<Menu> createOrderMenuRepository(String orderMenu) {
+ List<Menu> menuList = new ArrayList<>();
+ String pattern = "([๊ฐ-ํฃ]+)-([1-9]\\d*|0*[1-9]\\d+)(?:,|$)";
+
+ // ์ ๊ทํํ์์ ๋ง๋ ํจํด์ ์์ฑ
+ Pattern regexPattern = Pattern.compile(pattern);
+ Matcher matcher = regexPattern.matcher(orderMenu);
+
+ // ๋งค์นญ๋ ๊ฒฐ๊ณผ๋ฅผ ์ถ๋ ฅ
+ while (matcher.find()) {
+ String menuName = matcher.group(1);
+ String menuQuantity = matcher.group(2);
+ menuList.add(new Menu(menuName, menuQuantity));
+ }
+ return menuList;
+ }
+
+ private void validateOrderMenuForm(String orderedMenu) {
+ OrderMenuValidator.checkValidOrderForm(orderedMenu);
+ OrderMenuValidator.checkDuplicateMenu(orderedMenu);
+ OrderMenuValidator.checkMaxOrderQuantity(orderedMenu);
+ OrderMenuValidator.checkMenuContainsOnlyDrink(orderedMenu);
+ }
+}
|
Java
|
```suggestion
public Map<String, Integer> calculateCategoryCount() {
Map<String, Integer> categoryCount = new HashMap<>();
int count = 0;
for (Menu menu : orderMenu) {
String menuCategory = menu.getMenuCategory();
categoryCount.put(menuCategory, categoryCount.getOrDefault(menuCategory, 0) + 1)
}
return categoryCount;
}
```
`getOrDefault` ๋ฅผ ์ฌ์ฉํ๋ค๋ฉด ๊ฐ๋จํ๊ฒ ๋ฐ๊ฟ์ค ์ ์๋ต๋๋ค! ใ
ใ
๊ฐ์ด ์๋ค๋ฉด ํด๋น ๊ฐ์ ๊ฐ์ ธ์ค๊ณ ์์ผ๋ฉด default ๋ก ์ง์ ํด์ค ๊ฐ(์ฌ๊ธฐ์ 0)์ ๊ฐ์ ธ์ค๋ ๊ธฐ๋ฅ์
๋๋ค!
|
@@ -0,0 +1,102 @@
+package christmas.Domain;
+
+import christmas.Event.EventBenefit;
+import christmas.Event.EventOption;
+import christmas.Event.SpecialDiscountDay;
+import christmas.Util.OrderMenuValidator;
+import java.time.DayOfWeek;
+import java.time.LocalDate;
+import java.util.HashMap;
+import java.util.Map;
+
+public class EventBenefitSettler {
+ private final int visitDate;
+
+ public EventBenefitSettler(String visitDate) {
+ OrderMenuValidator.validateDate(visitDate);
+ this.visitDate = Integer.parseInt(visitDate);
+ }
+
+ public Map<String, Integer> calculateReceivedBenefits(Map<String, Integer> categoryCount,
+ int preDiscountTotalOrderPrice) {
+ Map<String, Integer> receivedBenefits = new HashMap<>();
+ if (preDiscountTotalOrderPrice >= EventOption.MINIMUM_ORDER_PRICE_TO_GET_DISCOUNT) {
+ caculateChristmasDDayDiscount(receivedBenefits);
+ caculateWeekdayDiscount(receivedBenefits, categoryCount);
+ caculateWeekendDiscount(receivedBenefits, categoryCount);
+ caculateSpecialDiscount(receivedBenefits);
+ checkGiftMenu(receivedBenefits, preDiscountTotalOrderPrice);
+ }
+ return receivedBenefits;
+ }
+
+ public int caculateBenefitsTotalAmount(Map<String, Integer> receivedBenefits) {
+ int benefitsTotalAmount = 0;
+ for (Map.Entry<String, Integer> benefit : receivedBenefits.entrySet()) {
+ benefitsTotalAmount += benefit.getValue();
+ }
+ return benefitsTotalAmount;
+ }
+
+ public int calculateDiscountedTotalAmount(Map<String, Integer> receivedBenefits, int preDiscountTotalOrderPrice) {
+ int discountedTotalAmount = preDiscountTotalOrderPrice;
+ for (Map.Entry<String, Integer> benefit : receivedBenefits.entrySet()) {
+ if (benefit.getKey() != EventBenefit.GIFT_MENU.getEventType()) {
+ discountedTotalAmount -= benefit.getValue();
+ }
+ }
+ return discountedTotalAmount;
+ }
+
+ private void caculateSpecialDiscount(Map<String, Integer> receivedBenefits) {
+ if (SpecialDiscountDay.isSpecialDay(this.visitDate)) {
+ receivedBenefits.put(EventBenefit.SPECIAL_DISCOUNT.getEventType(),
+ EventBenefit.SPECIAL_DISCOUNT.getBenefitAmount());
+ }
+ }
+
+ private void checkGiftMenu(Map<String, Integer> receivedBenefits, int preDiscountTotalOrderPrice) {
+ if (preDiscountTotalOrderPrice >= EventOption.MINIMUM_ORDER_PRICE_TO_GET_GIFT_MENU) {
+ receivedBenefits.put(EventBenefit.GIFT_MENU.getEventType(), EventBenefit.GIFT_MENU.getBenefitAmount());
+ }
+ }
+
+ private void caculateChristmasDDayDiscount(Map<String, Integer> receivedBenefits) {
+ int discount = 0;
+ if (this.visitDate <= EventOption.CHRISTMAS_D_DAY_EVENT_END_DATE) {
+ discount = EventOption.CHRISTMAS_D_DAY_START_DISCOUNT_AMOUNT;
+ discount += EventBenefit.CHRISTMAS_D_DAY_DISCOUNT.getBenefitTotalAmount(this.visitDate - 1);
+ receivedBenefits.put(EventBenefit.CHRISTMAS_D_DAY_DISCOUNT.getEventType(), discount);
+ }
+ }
+
+ private void caculateWeekdayDiscount(Map<String, Integer> receivedBenefits, Map<String, Integer> categoryCount) {
+ int discount = 0;
+ if (!isWeekend()) {
+ try {
+ int countDessert = categoryCount.get(EventBenefit.WEEKDAY_DISCOUNT.getEventTarget()); // ์๋์ง๋ฅผ ์ฒดํฌ
+ discount += EventBenefit.WEEKDAY_DISCOUNT.getBenefitTotalAmount(countDessert);
+ receivedBenefits.put(EventBenefit.WEEKDAY_DISCOUNT.getEventType(), discount);
+ } catch (NullPointerException e) {
+ }
+ }
+ }
+
+ private void caculateWeekendDiscount(Map<String, Integer> receivedBenefits, Map<String, Integer> categoryCount) {
+ int discount = 0;
+ if (isWeekend()) {
+ try {
+ int countMain = categoryCount.get(EventBenefit.WEEKEND_DISCOUNT.getEventTarget()); // ์๋์ง๋ฅผ ์ฒดํฌ
+ discount += EventBenefit.WEEKEND_DISCOUNT.getBenefitTotalAmount(countMain);
+ receivedBenefits.put(EventBenefit.WEEKDAY_DISCOUNT.getEventType(), discount);
+ } catch (NullPointerException e) {
+ }
+ }
+ }
+
+ private boolean isWeekend() {
+ LocalDate date = LocalDate.of(EventOption.EVENT_YEAR, EventOption.EVENT_MONTH, this.visitDate);
+ DayOfWeek dayOfWeek = date.getDayOfWeek();
+ return dayOfWeek == DayOfWeek.FRIDAY || dayOfWeek == DayOfWeek.SATURDAY;
+ }
+}
|
Java
|
`LocalDate` ๋ฅผ ํ์ฉํ๋ฉด ์์ผ์ ํ์
ํ ์ ์๊ตฐ์! ๋ฐฐ์๊ฐ๋๋ค! ๐
|
@@ -0,0 +1,7 @@
+package nextstep.security.role;
+
+import java.util.Collection;
+
+public interface RoleHierarchy {
+ Collection<GrantedAuthority> getReachableRoles(Collection<GrantedAuthority> authorities);
+}
|
Java
|
> ๊ทธ๋ฐ๋ฐ Spring Security ์ฝ๋ ์ ๋ฐ์์๋ Authority๋ฅผ ์ฃผ๋ก ์ฌ์ฉํ๋๋ฐ,
> RoleHierarchy์์ ํน๋ณํ Role์ด๋ผ๋ ์ฉ์ด๋ฅผ ์ฌ์ฉํ๋ ์ด์ ๊ฐ ๊ถ๊ธํ๋ค์.
> ์ด๋ ๊ฒ Role์ด๋ผ๋ ์ฉ์ด๋ฅผ ์ฌ์ฉํ๋ ์ด์ ๋ ์ญํ ๋ก ๋น๊ตํ๋ค๊ณ ๋ช
์์ ์ผ๋ก ๋ณด์ฌ์ฃผ๊ธฐ ์ํด์ ์ผ๊น์??
ํน์ ์ด๋ ์ฝ๋์์ `RoleHierarchy.getReachableRoles`๋ก ๋์ด์์๊น์? ์ค์ ์คํ๋ง ์ํ๋ฆฌํฐ ์ฝ๋์์๋ ๋ง์ํด์ฃผ์ ๋๋ก authority๋ผ๋ ํํ์ ์ฌ์ฉํ๊ณ ์์ด์.
```java
Collection<? extends GrantedAuthority> getReachableGrantedAuthorities(
Collection<? extends GrantedAuthority> authorities);
```
https://github.com/spring-projects/spring-security/blob/main/core/src/main/java/org/springframework/security/access/hierarchicalroles/RoleHierarchy.java
|
@@ -17,6 +17,7 @@
import nextstep.security.matcher.AnyRequestMatcher;
import nextstep.security.matcher.MvcRequestMatcher;
import nextstep.security.matcher.RequestMatcherEntry;
+import nextstep.security.role.*;
import nextstep.security.userdetails.UserDetails;
import nextstep.security.userdetails.UserDetailsService;
import org.springframework.context.annotation.Bean;
@@ -27,6 +28,7 @@
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
+import java.util.stream.Collectors;
@EnableAspectJAutoProxy
@Configuration
@@ -50,20 +52,17 @@ public FilterChainProxy filterChainProxy(List<SecurityFilterChain> securityFilte
@Bean
public SecuredMethodInterceptor securedMethodInterceptor() {
- AuthorityAuthorizationManager<Set<String>> authorityAuthorizationManager = new AuthorityAuthorizationManager<>();
+ AuthorityAuthorizationManager<Set<GrantedAuthority>> authorityAuthorizationManager = new AuthorityAuthorizationManager<>(roleHierarchy());
return new SecuredMethodInterceptor(new SecuredAuthorizationManager(authorityAuthorizationManager));
}
-// @Bean
-// public SecuredAspect securedAspect() {
-// return new SecuredAspect();
-// }
@Bean
public RequestMatcherDelegatingAuthorizationManager requestMatcherDelegatingAuthorizationManager() {
List<RequestMatcherEntry<AuthorizationManager<HttpServletRequest>>> 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 AuthorityAuthorizationManager<>()));
- mappings.add(new RequestMatcherEntry<>(new MvcRequestMatcher(HttpMethod.GET, "/search", "/login"), new PermitAllAuthorizationManager()));
+ mappings.add(new RequestMatcherEntry<>(new MvcRequestMatcher(HttpMethod.GET, "/members"), new AuthorityAuthorizationManager<>(new NullRoleHierarchy())));
+ mappings.add(new RequestMatcherEntry<>(new MvcRequestMatcher(HttpMethod.GET, "/search"), new PermitAllAuthorizationManager()));
+ mappings.add(new RequestMatcherEntry<>(new MvcRequestMatcher(HttpMethod.GET, "/login"), new PermitAllAuthorizationManager()));
mappings.add(new RequestMatcherEntry<>(new AnyRequestMatcher(), new DenyAllAuthorizationManager()));
return new RequestMatcherDelegatingAuthorizationManager(mappings);
}
@@ -98,10 +97,20 @@ public String getPassword() {
}
@Override
- public Set<String> getAuthorities() {
- return member.getRoles();
+ public Set<GrantedAuthority> getAuthorities() {
+ return member.getRoles()
+ .stream()
+ .map(SimpleGrantedAuthority::new)
+ .collect(Collectors.toSet());
}
};
};
}
+
+ @Bean
+ public RoleHierarchy roleHierarchy() {
+ return RoleHierarchyImpl.builder()
+ .role("ADMIN").addImplies("MEMBER")
+ .build();
+ }
}
|
Java
|
์ ์ถ๊ฐํด์ฃผ์
จ๋ค์ ๐
|
@@ -0,0 +1,10 @@
+package nextstep.security.role;
+
+import java.util.Collection;
+
+public class NullRoleHierarchy implements RoleHierarchy {
+ @Override
+ public Collection<GrantedAuthority> getReachableRoles(Collection<GrantedAuthority> authorities) {
+ return authorities;
+ }
+}
|
Java
|
`RoleHierarchy`์ ์๋ฌธ๋ช
๊ทธ๋๋ก ์ด ์ธํฐํ์ด์ค์ ์ญํ ์ "์ญํ ๊ณ์ธต"์ ๋ง๋ค์ด์ฃผ๋ ๊ฒ์ด์์. ๊ทธ๋์ ๊ตฌํ์ฒด๋ค๋ ์ญํ ๊ณ์ธต์ ๋ง๋ค์ด์ฃผ๋ ๊ฒ์ผ๋ก ๊ตฌ์ฑ์ด ๋์ด์ผํ๋๋ฐ์.
`NullRoleHierarchy`์ด๋ผ๋ ๊ฒ์ null์ด๋ผ๋ ๋ง์ด ํํ๋์ด์๊ธฐ๋ํ์ง๋ง ์ง์ญํ๋ฉด "์ญํ ๊ณ์ธต์ด ์๋ค"์
๋๋ค. ๊ณ์ธต์ด ์๋ค๋ ๊ฒ์ด์ง authority๊ฐ ์๋ค๋ ๋ป์ ์๋๊ธฐ ๋๋ฌธ์ empty๋ฅผ ๋ฐํํ๊ธฐ๋ณด๋ค๋ ์ธ์
๋ ํ๋ผ๋ฉํฐ๋ฅผ ๊ทธ๋๋ก ๋ฐํํด์ฃผ๋ ๊ฒ์ด ๊ทธ ๋ชฉ์ ์ด๋ผ๊ณ ๋ณผ ์ ์์ด์.
|
@@ -0,0 +1,96 @@
+package nextstep.security.role;
+
+import org.springframework.util.StringUtils;
+
+import java.util.*;
+
+public class RoleHierarchyImpl implements RoleHierarchy {
+
+ private static final List<GrantedAuthority> EMPTY_AUTHORITIES = Collections.emptyList();
+
+ private final Map<String, Set<GrantedAuthority>> roleHierarchy;
+
+
+ public RoleHierarchyImpl(Map<String, Set<GrantedAuthority>> roleHierarchy) {
+ this.roleHierarchy = new HashMap<>(roleHierarchy);
+ }
+
+ public static Builder builder() {
+ return new RoleHierarchyImpl.Builder();
+ }
+
+ @Override
+ public Collection<GrantedAuthority> getReachableRoles(Collection<GrantedAuthority> authorities) {
+ if (authorities == null || authorities.isEmpty()) {
+ return EMPTY_AUTHORITIES;
+ }
+
+ Set<GrantedAuthority> reachableRoles = new HashSet<>();
+ for (GrantedAuthority authority : authorities) {
+ reachableRoles.add(authority);
+
+ Collection<GrantedAuthority> impliedAuthorities = roleHierarchy.get(authority.getAuthority());
+ if (impliedAuthorities != null) {
+ reachableRoles.addAll(impliedAuthorities);
+ }
+ }
+
+ return reachableRoles;
+ }
+
+ public static final class Builder {
+
+ private final Map<String, Set<GrantedAuthority>> hierarchy;
+
+ private Builder() {
+ this.hierarchy = new HashMap<>();
+ }
+
+ public Builder.ImpliedRoles role(String role) {
+ if (!StringUtils.hasText(role)) {
+ throw new IllegalArgumentException("role must not be null or empty");
+ }
+
+ return new Builder.ImpliedRoles(role);
+ }
+
+ public RoleHierarchyImpl build() {
+ return new RoleHierarchyImpl(this.hierarchy);
+ }
+
+ private RoleHierarchyImpl.Builder addHierarchy(String role, String... impliedRoles) {
+ Set<GrantedAuthority> grantedAuthorities = new HashSet<>();
+
+ for (String impliedRole : impliedRoles) {
+ grantedAuthorities.add(new SimpleGrantedAuthority(impliedRole));
+ }
+
+ this.hierarchy.put(role, grantedAuthorities);
+ return this;
+ }
+
+ public final class ImpliedRoles {
+
+ private final String role;
+
+ private ImpliedRoles(String role) {
+ this.role = role;
+ }
+
+ public Builder addImplies(String... impliedRoles) {
+ if (impliedRoles == null) {
+ throw new IllegalArgumentException("at least one implied role must be provided");
+ }
+
+ for (String impliedRole : impliedRoles) {
+ if (!StringUtils.hasText(impliedRole)) {
+ throw new IllegalArgumentException("at least one implied role must be provided");
+ }
+ }
+
+ return Builder.this.addHierarchy(this.role, impliedRoles);
+ }
+ }
+
+ }
+}
|
Java
|
```suggestion
private static final List<GrantedAuthority> EMPTY_AUTHORITIES = Collections.emptyList();
private final Map<String, Set<GrantedAuthority>> roleHierarchy;
```
์์๋ ์๋ฐ ์ปจ๋ฒค์
์ ๊ฐ์ฅ ์์ ์์ด์ผํ๊ณ , `roleHierarchy`๋ ์ ๊ทผ์ ์ด๊ฐ ํ์ํด๋ณด์ด๋ค์ :)
|
@@ -0,0 +1,96 @@
+package nextstep.security.role;
+
+import org.springframework.util.StringUtils;
+
+import java.util.*;
+
+public class RoleHierarchyImpl implements RoleHierarchy {
+
+ private static final List<GrantedAuthority> EMPTY_AUTHORITIES = Collections.emptyList();
+
+ private final Map<String, Set<GrantedAuthority>> roleHierarchy;
+
+
+ public RoleHierarchyImpl(Map<String, Set<GrantedAuthority>> roleHierarchy) {
+ this.roleHierarchy = new HashMap<>(roleHierarchy);
+ }
+
+ public static Builder builder() {
+ return new RoleHierarchyImpl.Builder();
+ }
+
+ @Override
+ public Collection<GrantedAuthority> getReachableRoles(Collection<GrantedAuthority> authorities) {
+ if (authorities == null || authorities.isEmpty()) {
+ return EMPTY_AUTHORITIES;
+ }
+
+ Set<GrantedAuthority> reachableRoles = new HashSet<>();
+ for (GrantedAuthority authority : authorities) {
+ reachableRoles.add(authority);
+
+ Collection<GrantedAuthority> impliedAuthorities = roleHierarchy.get(authority.getAuthority());
+ if (impliedAuthorities != null) {
+ reachableRoles.addAll(impliedAuthorities);
+ }
+ }
+
+ return reachableRoles;
+ }
+
+ public static final class Builder {
+
+ private final Map<String, Set<GrantedAuthority>> hierarchy;
+
+ private Builder() {
+ this.hierarchy = new HashMap<>();
+ }
+
+ public Builder.ImpliedRoles role(String role) {
+ if (!StringUtils.hasText(role)) {
+ throw new IllegalArgumentException("role must not be null or empty");
+ }
+
+ return new Builder.ImpliedRoles(role);
+ }
+
+ public RoleHierarchyImpl build() {
+ return new RoleHierarchyImpl(this.hierarchy);
+ }
+
+ private RoleHierarchyImpl.Builder addHierarchy(String role, String... impliedRoles) {
+ Set<GrantedAuthority> grantedAuthorities = new HashSet<>();
+
+ for (String impliedRole : impliedRoles) {
+ grantedAuthorities.add(new SimpleGrantedAuthority(impliedRole));
+ }
+
+ this.hierarchy.put(role, grantedAuthorities);
+ return this;
+ }
+
+ public final class ImpliedRoles {
+
+ private final String role;
+
+ private ImpliedRoles(String role) {
+ this.role = role;
+ }
+
+ public Builder addImplies(String... impliedRoles) {
+ if (impliedRoles == null) {
+ throw new IllegalArgumentException("at least one implied role must be provided");
+ }
+
+ for (String impliedRole : impliedRoles) {
+ if (!StringUtils.hasText(impliedRole)) {
+ throw new IllegalArgumentException("at least one implied role must be provided");
+ }
+ }
+
+ return Builder.this.addHierarchy(this.role, impliedRoles);
+ }
+ }
+
+ }
+}
|
Java
|
`RoleHierarchyImpl`์ ๋ํ ํ
์คํธ๋ ์ถ๊ฐํด๋ณด๋ฉด ์ด๋จ๊น์? ๊ธฐ๋ฅ์ด ๋ณต์กํ ๊ฐ์ฒด์ด๋ ์ด๋ฅผ ๋ฌธ์ํํ๋ค๋ ๋๋์ผ๋ก ํ
์คํธ๋ฅผ ์ง๋ณด์
๋ ์ข์ ๊ฒฝํ์ด ๋ ๊ฒ ๊ฐ์์ :)
|
@@ -0,0 +1,7 @@
+package nextstep.security.role;
+
+import java.util.Collection;
+
+public interface RoleHierarchy {
+ Collection<GrantedAuthority> getReachableRoles(Collection<GrantedAuthority> authorities);
+}
|
Java
|
์ ๊ฐ ์๋ชป ์ง๋ฌธ์ ๋๋ ธ๋ค์. ์ฃ์กํฉ๋๋ค.
getReachableRoles๋ ๋ฏธ์
์ฝ๋์ ๋ถ๋ถ์ด์๋ค์. ๐
๊ทธ๋๋ Role ์ด๋ฆ์ ์ํ๋ฆฌํฐ์ RoleHierarchy์ ๊ตฌํ์ฒด ์ฝ๋์๋ ์ข
์ข
์ฌ์ฉ๋๋ ๊ฒ ๊ฐ์์
์๋ฅผ ๋ค์ด์ getReachableGrantedAuthorities ์ ๊ตฌํ ๋ฉ์๋ ์ค
``` java
Set<GrantedAuthority> lowerRoles = this.rolesReachableInOneOrMoreStepsMap.get(authority.getAuthority());
if (lowerRoles == null) {
continue; // No hierarchy for the role
}
for (GrantedAuthority role : lowerRoles) {
if (processedNames.add(role.getAuthority())) {
reachableRoles.add(role);
}
}
```
์ ๋ถ๋ถ๋ค ๋ณด๋ฉด Authority ์ Role์ ๊ฐ์ด ์ฌ์ฉํ๋ ๋ฏํด์ RolePrefix์ ๊ด๋ จ์๋๊ฑด๊ฐ? ํ์ต๋๋ค ใ
ใ
https://github.com/spring-projects/spring-security/blob/main/core/src/main/java/org/springframework/security/access/hierarchicalroles/RoleHierarchyImpl.java
|
@@ -0,0 +1,10 @@
+package nextstep.security.role;
+
+import java.util.Collection;
+
+public class NullRoleHierarchy implements RoleHierarchy {
+ @Override
+ public Collection<GrantedAuthority> getReachableRoles(Collection<GrantedAuthority> authorities) {
+ return authorities;
+ }
+}
|
Java
|
์ํ ์ ๋ NULL์ ์ ์ฐ์ง ๋ผ๋ ์๋ฌธ์ด ์์๋๋ฐ , ๋น ๊ถํ์ ์ฃผ๋ ๊ฒ์ด ์๋๋ผ ๋ง ๊ทธ๋๋ก RoleHierarchy ๊ฐ ์๋ค๋ผ๋ ์๋ฏธ๊ตฐ์!
|
@@ -0,0 +1,96 @@
+package nextstep.security.role;
+
+import org.springframework.util.StringUtils;
+
+import java.util.*;
+
+public class RoleHierarchyImpl implements RoleHierarchy {
+
+ private static final List<GrantedAuthority> EMPTY_AUTHORITIES = Collections.emptyList();
+
+ private final Map<String, Set<GrantedAuthority>> roleHierarchy;
+
+
+ public RoleHierarchyImpl(Map<String, Set<GrantedAuthority>> roleHierarchy) {
+ this.roleHierarchy = new HashMap<>(roleHierarchy);
+ }
+
+ public static Builder builder() {
+ return new RoleHierarchyImpl.Builder();
+ }
+
+ @Override
+ public Collection<GrantedAuthority> getReachableRoles(Collection<GrantedAuthority> authorities) {
+ if (authorities == null || authorities.isEmpty()) {
+ return EMPTY_AUTHORITIES;
+ }
+
+ Set<GrantedAuthority> reachableRoles = new HashSet<>();
+ for (GrantedAuthority authority : authorities) {
+ reachableRoles.add(authority);
+
+ Collection<GrantedAuthority> impliedAuthorities = roleHierarchy.get(authority.getAuthority());
+ if (impliedAuthorities != null) {
+ reachableRoles.addAll(impliedAuthorities);
+ }
+ }
+
+ return reachableRoles;
+ }
+
+ public static final class Builder {
+
+ private final Map<String, Set<GrantedAuthority>> hierarchy;
+
+ private Builder() {
+ this.hierarchy = new HashMap<>();
+ }
+
+ public Builder.ImpliedRoles role(String role) {
+ if (!StringUtils.hasText(role)) {
+ throw new IllegalArgumentException("role must not be null or empty");
+ }
+
+ return new Builder.ImpliedRoles(role);
+ }
+
+ public RoleHierarchyImpl build() {
+ return new RoleHierarchyImpl(this.hierarchy);
+ }
+
+ private RoleHierarchyImpl.Builder addHierarchy(String role, String... impliedRoles) {
+ Set<GrantedAuthority> grantedAuthorities = new HashSet<>();
+
+ for (String impliedRole : impliedRoles) {
+ grantedAuthorities.add(new SimpleGrantedAuthority(impliedRole));
+ }
+
+ this.hierarchy.put(role, grantedAuthorities);
+ return this;
+ }
+
+ public final class ImpliedRoles {
+
+ private final String role;
+
+ private ImpliedRoles(String role) {
+ this.role = role;
+ }
+
+ public Builder addImplies(String... impliedRoles) {
+ if (impliedRoles == null) {
+ throw new IllegalArgumentException("at least one implied role must be provided");
+ }
+
+ for (String impliedRole : impliedRoles) {
+ if (!StringUtils.hasText(impliedRole)) {
+ throw new IllegalArgumentException("at least one implied role must be provided");
+ }
+ }
+
+ return Builder.this.addHierarchy(this.role, impliedRoles);
+ }
+ }
+
+ }
+}
|
Java
|
์์ ํ๊ฒ ์ต๋๋ค!
|
@@ -0,0 +1,7 @@
+package nextstep.security.role;
+
+import java.util.Collection;
+
+public interface RoleHierarchy {
+ Collection<GrantedAuthority> getReachableRoles(Collection<GrantedAuthority> authorities);
+}
|
Java
|
๋ค spring security์์๋ ์ธ๊ฐ์ฒ๋ฆฌ ๊ถํ(Authority)๊ฐ ์์ง๋ง, ๊ทธ ๊ถํ์ ์ญํ ๋ณ๋ก ๊ณ์ธต์ผ๋ก ๋ถ๋ฆฌํ๋ คํ๊ณ ๊ทธ๋ ๊ฒ ๋์จ ๊ฒ์ด `RoleHierarchy`๋ผ๊ณ ๋ณด์๋ฉด ๋ ๊ฒ ๊ฐ์์.
๋ ์ ๋ณด๊ฐ ๋์ผํ ์๋ ์๋๋ฐ ์ฐ์์ ์์ฒด๊ฐ ๊ถํ, ๊ถํ๋ณ ์ญํ ๋ก ํ๋ฒ ๋ ์ชผ๊ฐ์ง๋ค๊ณ ๋ณด์๋ฉด ๋ ๊ฒ ๊ฐ์ต๋๋ค.
https://docs.spring.io/spring-security/reference/servlet/authorization/architecture.html?utm_source=chatgpt.com#authz-hierarchical-roles
|
@@ -0,0 +1,101 @@
+package nextstep.security.role;
+
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.DisplayName;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.NullAndEmptySource;
+import org.junit.jupiter.params.provider.ValueSource;
+
+import java.util.Collection;
+import java.util.List;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
+
+class RoleHierarchyImplTest {
+
+ RoleHierarchyImpl.Builder builder;
+
+ @BeforeEach
+ void setUp() {
+ builder = RoleHierarchyImpl.builder()
+ .role("ADMIN").addImplies("MEMBER");
+ }
+
+ @ParameterizedTest
+ @ValueSource(strings = {"ADMIN", "MEMBER", "UNKNOWN"})
+ @DisplayName("์ญํ ๊ณ์ธต์ Authority ๋ก ๊ฐ์ ธ์ฌ ์ ์๋ค")
+ void getRoleHierarchyTest(String roleName) {
+ // given
+ RoleHierarchyImpl roleHierarchy = builder.build();
+
+ // when
+ SimpleGrantedAuthority authority = new SimpleGrantedAuthority(roleName);
+ Collection<GrantedAuthority> reachableRoles = roleHierarchy.getReachableRoles(List.of(authority));
+
+ // then
+ List<GrantedAuthority> expect = switch (roleName) {
+ case "ADMIN" -> List.of(
+ new SimpleGrantedAuthority("ADMIN"),
+ new SimpleGrantedAuthority("MEMBER")
+ );
+ case "MEMBER", "UNKNOWN" -> List.of(
+ new SimpleGrantedAuthority(roleName)
+ );
+ default -> throw new IllegalStateException("Unexpected roleName: " + roleName);
+ };
+
+ assertThat(reachableRoles)
+ .containsExactlyInAnyOrderElementsOf(expect);
+ }
+
+ @Test
+ @DisplayName("์๋ก์ด ์ญํ ๊ณ์ธต์ ์ถ๊ฐํ ์ ์๋ค.")
+ void addRoleHierarchyTest() {
+ // given
+ String target = "ISRAEL";
+ String nothing = "NOTHING";
+ String everything = "EVERYTHING";
+ RoleHierarchyImpl roleHierarchy = builder.role(target).addImplies(nothing, everything)
+ .build();
+
+ // when
+ SimpleGrantedAuthority authority = new SimpleGrantedAuthority(target);
+ Collection<GrantedAuthority> reachableRoles = roleHierarchy.getReachableRoles(List.of(authority));
+
+ // then
+ var expect = List.of(
+ authority,
+ new SimpleGrantedAuthority(nothing),
+ new SimpleGrantedAuthority(everything)
+ );
+ assertThat(reachableRoles).hasSize(3)
+ .containsExactlyInAnyOrderElementsOf(expect);
+ }
+
+ @ParameterizedTest
+ @NullAndEmptySource
+ @DisplayName("์ญํ ์ ์ด๋ฆ์ ๋น์ด์์์ ์๋ค")
+ void addRoleHierarchyFailTest1(String roleName) {
+ assertThatThrownBy(
+ () -> builder.role(roleName)
+ ).isInstanceOf(IllegalArgumentException.class)
+ .hasMessageContaining("role must not be null or empty");
+ }
+
+ @ParameterizedTest
+ @NullAndEmptySource
+ @DisplayName("ํฌํจ๋ ์ญํ ๋ค๋ ๋น์ด์์ ์ ์๋ค.")
+ void addRoleHierarchyFailTest2(String roleName) {
+ // given
+ String target = "NEW_ROLE";
+ RoleHierarchyImpl.Builder.ImpliedRoles impliedRoles = builder.role(target);
+
+ // when
+ assertThatThrownBy(
+ () -> impliedRoles.addImplies(roleName)
+ ).isInstanceOf(IllegalArgumentException.class)
+ .hasMessageContaining("at least one implied role must be provided");
+ }
+}
|
Java
|
junit5์์๋ ์ด๊ธฐํ ๋จ์๊ฐ ๋ฉ์๋ ๋จ์์ด๊ธฐ ๋๋ฌธ์ ๋ฐ๋ก setup์ผ๋ก ์ด๊ธฐํํด์ฃผ์ ์์ผ์
๋ ๋ฉ๋๋ค.
https://junit.org/junit5/docs/current/user-guide/#writing-tests-test-instance-lifecycle
|
@@ -0,0 +1,101 @@
+package nextstep.security.role;
+
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.DisplayName;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.NullAndEmptySource;
+import org.junit.jupiter.params.provider.ValueSource;
+
+import java.util.Collection;
+import java.util.List;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
+
+class RoleHierarchyImplTest {
+
+ RoleHierarchyImpl.Builder builder;
+
+ @BeforeEach
+ void setUp() {
+ builder = RoleHierarchyImpl.builder()
+ .role("ADMIN").addImplies("MEMBER");
+ }
+
+ @ParameterizedTest
+ @ValueSource(strings = {"ADMIN", "MEMBER", "UNKNOWN"})
+ @DisplayName("์ญํ ๊ณ์ธต์ Authority ๋ก ๊ฐ์ ธ์ฌ ์ ์๋ค")
+ void getRoleHierarchyTest(String roleName) {
+ // given
+ RoleHierarchyImpl roleHierarchy = builder.build();
+
+ // when
+ SimpleGrantedAuthority authority = new SimpleGrantedAuthority(roleName);
+ Collection<GrantedAuthority> reachableRoles = roleHierarchy.getReachableRoles(List.of(authority));
+
+ // then
+ List<GrantedAuthority> expect = switch (roleName) {
+ case "ADMIN" -> List.of(
+ new SimpleGrantedAuthority("ADMIN"),
+ new SimpleGrantedAuthority("MEMBER")
+ );
+ case "MEMBER", "UNKNOWN" -> List.of(
+ new SimpleGrantedAuthority(roleName)
+ );
+ default -> throw new IllegalStateException("Unexpected roleName: " + roleName);
+ };
+
+ assertThat(reachableRoles)
+ .containsExactlyInAnyOrderElementsOf(expect);
+ }
+
+ @Test
+ @DisplayName("์๋ก์ด ์ญํ ๊ณ์ธต์ ์ถ๊ฐํ ์ ์๋ค.")
+ void addRoleHierarchyTest() {
+ // given
+ String target = "ISRAEL";
+ String nothing = "NOTHING";
+ String everything = "EVERYTHING";
+ RoleHierarchyImpl roleHierarchy = builder.role(target).addImplies(nothing, everything)
+ .build();
+
+ // when
+ SimpleGrantedAuthority authority = new SimpleGrantedAuthority(target);
+ Collection<GrantedAuthority> reachableRoles = roleHierarchy.getReachableRoles(List.of(authority));
+
+ // then
+ var expect = List.of(
+ authority,
+ new SimpleGrantedAuthority(nothing),
+ new SimpleGrantedAuthority(everything)
+ );
+ assertThat(reachableRoles).hasSize(3)
+ .containsExactlyInAnyOrderElementsOf(expect);
+ }
+
+ @ParameterizedTest
+ @NullAndEmptySource
+ @DisplayName("์ญํ ์ ์ด๋ฆ์ ๋น์ด์์์ ์๋ค")
+ void addRoleHierarchyFailTest1(String roleName) {
+ assertThatThrownBy(
+ () -> builder.role(roleName)
+ ).isInstanceOf(IllegalArgumentException.class)
+ .hasMessageContaining("role must not be null or empty");
+ }
+
+ @ParameterizedTest
+ @NullAndEmptySource
+ @DisplayName("ํฌํจ๋ ์ญํ ๋ค๋ ๋น์ด์์ ์ ์๋ค.")
+ void addRoleHierarchyFailTest2(String roleName) {
+ // given
+ String target = "NEW_ROLE";
+ RoleHierarchyImpl.Builder.ImpliedRoles impliedRoles = builder.role(target);
+
+ // when
+ assertThatThrownBy(
+ () -> impliedRoles.addImplies(roleName)
+ ).isInstanceOf(IllegalArgumentException.class)
+ .hasMessageContaining("at least one implied role must be provided");
+ }
+}
|
Java
|
1. ์ถ๊ฐํ๋ค๊ธฐ๋ณด๋ค๋ ๊ณ์ธต์ ๊ฐ์ ธ์จ๋ค์ ๋ ๊ฐ๊น์ด ํ
์คํธ๋ก ๋ณด์ด๋ค์.
2. `SimpleGrantedAuthority authority = new SimpleGrantedAuthority(target);`๋ ๊ทธ๋์ ๋ฐ์ง๊ณ ๋ณด๋ฉด ์ฃผ์ด์ง ๋ฐ์ดํฐ์ธ given์ ๋ ๊ฐ๊น์ต๋๋ค. when์๋ ํ
์คํธ๋ฅผ ์ฆ๋ช
ํ๊ณ ์ํ๋ ๋์์ ์คํ ๊ทธ์์ฒด๋ง์ ๋ฃ์ด์ฃผ์๋ฉด ์ข์ ๊ฒ ๊ฐ์์.
3. expected ๋ํ given์ ๋ค์ด๊ฐ๋ ๊ฒ์ด ๋ง๊ฒ ์ฃ . 74๋ฒ๋ผ์ธ์ ๊ฐ์ ๊ทธ๋๋ก ๋ฃ๋ ๊ฒฝ์ฐ๋ ์๊ด์ด ์์ง๋ง ๊ธฐ๋๊ฐ ๋ํ ์ฃผ์ด์ง ๋ฐ์ดํฐ๋ผ๊ณ ๋ณด๋ ํธ์
๋๋ค.
|
@@ -0,0 +1,101 @@
+package nextstep.security.role;
+
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.DisplayName;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.NullAndEmptySource;
+import org.junit.jupiter.params.provider.ValueSource;
+
+import java.util.Collection;
+import java.util.List;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
+
+class RoleHierarchyImplTest {
+
+ RoleHierarchyImpl.Builder builder;
+
+ @BeforeEach
+ void setUp() {
+ builder = RoleHierarchyImpl.builder()
+ .role("ADMIN").addImplies("MEMBER");
+ }
+
+ @ParameterizedTest
+ @ValueSource(strings = {"ADMIN", "MEMBER", "UNKNOWN"})
+ @DisplayName("์ญํ ๊ณ์ธต์ Authority ๋ก ๊ฐ์ ธ์ฌ ์ ์๋ค")
+ void getRoleHierarchyTest(String roleName) {
+ // given
+ RoleHierarchyImpl roleHierarchy = builder.build();
+
+ // when
+ SimpleGrantedAuthority authority = new SimpleGrantedAuthority(roleName);
+ Collection<GrantedAuthority> reachableRoles = roleHierarchy.getReachableRoles(List.of(authority));
+
+ // then
+ List<GrantedAuthority> expect = switch (roleName) {
+ case "ADMIN" -> List.of(
+ new SimpleGrantedAuthority("ADMIN"),
+ new SimpleGrantedAuthority("MEMBER")
+ );
+ case "MEMBER", "UNKNOWN" -> List.of(
+ new SimpleGrantedAuthority(roleName)
+ );
+ default -> throw new IllegalStateException("Unexpected roleName: " + roleName);
+ };
+
+ assertThat(reachableRoles)
+ .containsExactlyInAnyOrderElementsOf(expect);
+ }
+
+ @Test
+ @DisplayName("์๋ก์ด ์ญํ ๊ณ์ธต์ ์ถ๊ฐํ ์ ์๋ค.")
+ void addRoleHierarchyTest() {
+ // given
+ String target = "ISRAEL";
+ String nothing = "NOTHING";
+ String everything = "EVERYTHING";
+ RoleHierarchyImpl roleHierarchy = builder.role(target).addImplies(nothing, everything)
+ .build();
+
+ // when
+ SimpleGrantedAuthority authority = new SimpleGrantedAuthority(target);
+ Collection<GrantedAuthority> reachableRoles = roleHierarchy.getReachableRoles(List.of(authority));
+
+ // then
+ var expect = List.of(
+ authority,
+ new SimpleGrantedAuthority(nothing),
+ new SimpleGrantedAuthority(everything)
+ );
+ assertThat(reachableRoles).hasSize(3)
+ .containsExactlyInAnyOrderElementsOf(expect);
+ }
+
+ @ParameterizedTest
+ @NullAndEmptySource
+ @DisplayName("์ญํ ์ ์ด๋ฆ์ ๋น์ด์์์ ์๋ค")
+ void addRoleHierarchyFailTest1(String roleName) {
+ assertThatThrownBy(
+ () -> builder.role(roleName)
+ ).isInstanceOf(IllegalArgumentException.class)
+ .hasMessageContaining("role must not be null or empty");
+ }
+
+ @ParameterizedTest
+ @NullAndEmptySource
+ @DisplayName("ํฌํจ๋ ์ญํ ๋ค๋ ๋น์ด์์ ์ ์๋ค.")
+ void addRoleHierarchyFailTest2(String roleName) {
+ // given
+ String target = "NEW_ROLE";
+ RoleHierarchyImpl.Builder.ImpliedRoles impliedRoles = builder.role(target);
+
+ // when
+ assertThatThrownBy(
+ () -> impliedRoles.addImplies(roleName)
+ ).isInstanceOf(IllegalArgumentException.class)
+ .hasMessageContaining("at least one implied role must be provided");
+ }
+}
|
Java
|
๊ทธ๋์ ์ถ๊ฐํจ(`addImplies`)๋ฅผ ํ
์คํธํ๊ณ ์ถ๋ค๋ฉด ์ ๋ง ๊ฐ์ด ์ถ๊ฐ๋์๋์ง ๊ทธ ์์ฒด๋ง์ ํ
์คํธํ๋ ๊ฒ์ด ๋์ ์๋ ์์ด์. `private final Map<String, Set<GrantedAuthority>> rolesReachableInOneOrMoreStepsMap;`์ ์ํ๋ ๊ฐ์ด ์๋์ง ํ์ธํ๋ ๊ฒ์ผ๋ก์.
|
@@ -0,0 +1,101 @@
+package nextstep.security.role;
+
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.DisplayName;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.NullAndEmptySource;
+import org.junit.jupiter.params.provider.ValueSource;
+
+import java.util.Collection;
+import java.util.List;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
+
+class RoleHierarchyImplTest {
+
+ RoleHierarchyImpl.Builder builder;
+
+ @BeforeEach
+ void setUp() {
+ builder = RoleHierarchyImpl.builder()
+ .role("ADMIN").addImplies("MEMBER");
+ }
+
+ @ParameterizedTest
+ @ValueSource(strings = {"ADMIN", "MEMBER", "UNKNOWN"})
+ @DisplayName("์ญํ ๊ณ์ธต์ Authority ๋ก ๊ฐ์ ธ์ฌ ์ ์๋ค")
+ void getRoleHierarchyTest(String roleName) {
+ // given
+ RoleHierarchyImpl roleHierarchy = builder.build();
+
+ // when
+ SimpleGrantedAuthority authority = new SimpleGrantedAuthority(roleName);
+ Collection<GrantedAuthority> reachableRoles = roleHierarchy.getReachableRoles(List.of(authority));
+
+ // then
+ List<GrantedAuthority> expect = switch (roleName) {
+ case "ADMIN" -> List.of(
+ new SimpleGrantedAuthority("ADMIN"),
+ new SimpleGrantedAuthority("MEMBER")
+ );
+ case "MEMBER", "UNKNOWN" -> List.of(
+ new SimpleGrantedAuthority(roleName)
+ );
+ default -> throw new IllegalStateException("Unexpected roleName: " + roleName);
+ };
+
+ assertThat(reachableRoles)
+ .containsExactlyInAnyOrderElementsOf(expect);
+ }
+
+ @Test
+ @DisplayName("์๋ก์ด ์ญํ ๊ณ์ธต์ ์ถ๊ฐํ ์ ์๋ค.")
+ void addRoleHierarchyTest() {
+ // given
+ String target = "ISRAEL";
+ String nothing = "NOTHING";
+ String everything = "EVERYTHING";
+ RoleHierarchyImpl roleHierarchy = builder.role(target).addImplies(nothing, everything)
+ .build();
+
+ // when
+ SimpleGrantedAuthority authority = new SimpleGrantedAuthority(target);
+ Collection<GrantedAuthority> reachableRoles = roleHierarchy.getReachableRoles(List.of(authority));
+
+ // then
+ var expect = List.of(
+ authority,
+ new SimpleGrantedAuthority(nothing),
+ new SimpleGrantedAuthority(everything)
+ );
+ assertThat(reachableRoles).hasSize(3)
+ .containsExactlyInAnyOrderElementsOf(expect);
+ }
+
+ @ParameterizedTest
+ @NullAndEmptySource
+ @DisplayName("์ญํ ์ ์ด๋ฆ์ ๋น์ด์์์ ์๋ค")
+ void addRoleHierarchyFailTest1(String roleName) {
+ assertThatThrownBy(
+ () -> builder.role(roleName)
+ ).isInstanceOf(IllegalArgumentException.class)
+ .hasMessageContaining("role must not be null or empty");
+ }
+
+ @ParameterizedTest
+ @NullAndEmptySource
+ @DisplayName("ํฌํจ๋ ์ญํ ๋ค๋ ๋น์ด์์ ์ ์๋ค.")
+ void addRoleHierarchyFailTest2(String roleName) {
+ // given
+ String target = "NEW_ROLE";
+ RoleHierarchyImpl.Builder.ImpliedRoles impliedRoles = builder.role(target);
+
+ // when
+ assertThatThrownBy(
+ () -> impliedRoles.addImplies(roleName)
+ ).isInstanceOf(IllegalArgumentException.class)
+ .hasMessageContaining("at least one implied role must be provided");
+ }
+}
|
Java
|
`@CsvSource`๋ฅผ ํ์ฉํ๋ฉด ๊ธฐ๋๊ฐ์ ๋ํ ๋ถ๊ธฐ์ฒ๋ฆฌ๋ฅผ ํ
์คํธ์์ ํ์ง ์์๋ ๋ ๊ฒ ๊ฐ์์.
|
@@ -0,0 +1,101 @@
+package nextstep.security.role;
+
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.DisplayName;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.NullAndEmptySource;
+import org.junit.jupiter.params.provider.ValueSource;
+
+import java.util.Collection;
+import java.util.List;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
+
+class RoleHierarchyImplTest {
+
+ RoleHierarchyImpl.Builder builder;
+
+ @BeforeEach
+ void setUp() {
+ builder = RoleHierarchyImpl.builder()
+ .role("ADMIN").addImplies("MEMBER");
+ }
+
+ @ParameterizedTest
+ @ValueSource(strings = {"ADMIN", "MEMBER", "UNKNOWN"})
+ @DisplayName("์ญํ ๊ณ์ธต์ Authority ๋ก ๊ฐ์ ธ์ฌ ์ ์๋ค")
+ void getRoleHierarchyTest(String roleName) {
+ // given
+ RoleHierarchyImpl roleHierarchy = builder.build();
+
+ // when
+ SimpleGrantedAuthority authority = new SimpleGrantedAuthority(roleName);
+ Collection<GrantedAuthority> reachableRoles = roleHierarchy.getReachableRoles(List.of(authority));
+
+ // then
+ List<GrantedAuthority> expect = switch (roleName) {
+ case "ADMIN" -> List.of(
+ new SimpleGrantedAuthority("ADMIN"),
+ new SimpleGrantedAuthority("MEMBER")
+ );
+ case "MEMBER", "UNKNOWN" -> List.of(
+ new SimpleGrantedAuthority(roleName)
+ );
+ default -> throw new IllegalStateException("Unexpected roleName: " + roleName);
+ };
+
+ assertThat(reachableRoles)
+ .containsExactlyInAnyOrderElementsOf(expect);
+ }
+
+ @Test
+ @DisplayName("์๋ก์ด ์ญํ ๊ณ์ธต์ ์ถ๊ฐํ ์ ์๋ค.")
+ void addRoleHierarchyTest() {
+ // given
+ String target = "ISRAEL";
+ String nothing = "NOTHING";
+ String everything = "EVERYTHING";
+ RoleHierarchyImpl roleHierarchy = builder.role(target).addImplies(nothing, everything)
+ .build();
+
+ // when
+ SimpleGrantedAuthority authority = new SimpleGrantedAuthority(target);
+ Collection<GrantedAuthority> reachableRoles = roleHierarchy.getReachableRoles(List.of(authority));
+
+ // then
+ var expect = List.of(
+ authority,
+ new SimpleGrantedAuthority(nothing),
+ new SimpleGrantedAuthority(everything)
+ );
+ assertThat(reachableRoles).hasSize(3)
+ .containsExactlyInAnyOrderElementsOf(expect);
+ }
+
+ @ParameterizedTest
+ @NullAndEmptySource
+ @DisplayName("์ญํ ์ ์ด๋ฆ์ ๋น์ด์์์ ์๋ค")
+ void addRoleHierarchyFailTest1(String roleName) {
+ assertThatThrownBy(
+ () -> builder.role(roleName)
+ ).isInstanceOf(IllegalArgumentException.class)
+ .hasMessageContaining("role must not be null or empty");
+ }
+
+ @ParameterizedTest
+ @NullAndEmptySource
+ @DisplayName("ํฌํจ๋ ์ญํ ๋ค๋ ๋น์ด์์ ์ ์๋ค.")
+ void addRoleHierarchyFailTest2(String roleName) {
+ // given
+ String target = "NEW_ROLE";
+ RoleHierarchyImpl.Builder.ImpliedRoles impliedRoles = builder.role(target);
+
+ // when
+ assertThatThrownBy(
+ () -> impliedRoles.addImplies(roleName)
+ ).isInstanceOf(IllegalArgumentException.class)
+ .hasMessageContaining("at least one implied role must be provided");
+ }
+}
|
Java
|
ํ
์คํธ๋ก ์ด๋ค ๊ธฐ๋ฅ์ด ์๋์ง ์ ๋ณด์ด๋ค์ ๐
|
@@ -0,0 +1,101 @@
+package nextstep.security.role;
+
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.DisplayName;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.NullAndEmptySource;
+import org.junit.jupiter.params.provider.ValueSource;
+
+import java.util.Collection;
+import java.util.List;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
+
+class RoleHierarchyImplTest {
+
+ RoleHierarchyImpl.Builder builder;
+
+ @BeforeEach
+ void setUp() {
+ builder = RoleHierarchyImpl.builder()
+ .role("ADMIN").addImplies("MEMBER");
+ }
+
+ @ParameterizedTest
+ @ValueSource(strings = {"ADMIN", "MEMBER", "UNKNOWN"})
+ @DisplayName("์ญํ ๊ณ์ธต์ Authority ๋ก ๊ฐ์ ธ์ฌ ์ ์๋ค")
+ void getRoleHierarchyTest(String roleName) {
+ // given
+ RoleHierarchyImpl roleHierarchy = builder.build();
+
+ // when
+ SimpleGrantedAuthority authority = new SimpleGrantedAuthority(roleName);
+ Collection<GrantedAuthority> reachableRoles = roleHierarchy.getReachableRoles(List.of(authority));
+
+ // then
+ List<GrantedAuthority> expect = switch (roleName) {
+ case "ADMIN" -> List.of(
+ new SimpleGrantedAuthority("ADMIN"),
+ new SimpleGrantedAuthority("MEMBER")
+ );
+ case "MEMBER", "UNKNOWN" -> List.of(
+ new SimpleGrantedAuthority(roleName)
+ );
+ default -> throw new IllegalStateException("Unexpected roleName: " + roleName);
+ };
+
+ assertThat(reachableRoles)
+ .containsExactlyInAnyOrderElementsOf(expect);
+ }
+
+ @Test
+ @DisplayName("์๋ก์ด ์ญํ ๊ณ์ธต์ ์ถ๊ฐํ ์ ์๋ค.")
+ void addRoleHierarchyTest() {
+ // given
+ String target = "ISRAEL";
+ String nothing = "NOTHING";
+ String everything = "EVERYTHING";
+ RoleHierarchyImpl roleHierarchy = builder.role(target).addImplies(nothing, everything)
+ .build();
+
+ // when
+ SimpleGrantedAuthority authority = new SimpleGrantedAuthority(target);
+ Collection<GrantedAuthority> reachableRoles = roleHierarchy.getReachableRoles(List.of(authority));
+
+ // then
+ var expect = List.of(
+ authority,
+ new SimpleGrantedAuthority(nothing),
+ new SimpleGrantedAuthority(everything)
+ );
+ assertThat(reachableRoles).hasSize(3)
+ .containsExactlyInAnyOrderElementsOf(expect);
+ }
+
+ @ParameterizedTest
+ @NullAndEmptySource
+ @DisplayName("์ญํ ์ ์ด๋ฆ์ ๋น์ด์์์ ์๋ค")
+ void addRoleHierarchyFailTest1(String roleName) {
+ assertThatThrownBy(
+ () -> builder.role(roleName)
+ ).isInstanceOf(IllegalArgumentException.class)
+ .hasMessageContaining("role must not be null or empty");
+ }
+
+ @ParameterizedTest
+ @NullAndEmptySource
+ @DisplayName("ํฌํจ๋ ์ญํ ๋ค๋ ๋น์ด์์ ์ ์๋ค.")
+ void addRoleHierarchyFailTest2(String roleName) {
+ // given
+ String target = "NEW_ROLE";
+ RoleHierarchyImpl.Builder.ImpliedRoles impliedRoles = builder.role(target);
+
+ // when
+ assertThatThrownBy(
+ () -> impliedRoles.addImplies(roleName)
+ ).isInstanceOf(IllegalArgumentException.class)
+ .hasMessageContaining("at least one implied role must be provided");
+ }
+}
|
Java
|
์ ์ฒด ๋์์ด ์๋ rolesReachableInOneOrMoreStepsMap ์์ฒด์ ๊ฐ์ด ์ ์ฅ๋์ด์๋์ง ํ์ธํ๋๊ฒ ์ถ๊ฐ๋์๋๊ฐ ์ ๋ํ ํ
์คํธ๋ก ๋ ์ขํ์ง๊ฒ ๋ค์!
|
@@ -0,0 +1,77 @@
+import React, { useState } from "react";
+import styled from "styled-components";
+import { Star as StarIcon } from "lucide-react";
+
+interface StarRatingProps {
+ totalStars?: number;
+ initialRating?: number;
+ onRatingChange?: (rating: number) => void;
+}
+
+const BackgroundContainer = styled.div`
+ background-color: #f7f7f7;
+ width: 807.73px;
+ height: 251.63px;
+ display: flex;
+ align-items: center;
+ justify-content: center;
+`;
+
+const StarContainer = styled.div`
+ display: flex;
+ gap: 4px;
+`;
+
+const StyledStar = styled.div<{ filled: boolean }>`
+ cursor: pointer;
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ svg {
+ width: 94.96px;
+ height: 99.25px;
+ color: ${(props) => (props.filled ? "#facc15" : "#d1d5db")};
+ }
+`;
+
+const StarRating: React.FC<StarRatingProps> = ({
+ totalStars = 5,
+ initialRating = 0,
+ onRatingChange,
+}) => {
+ const [rating, setRating] = useState(initialRating);
+
+ const handleRating = (index: number) => {
+ let newRating = rating;
+ if (index + 1 === rating) {
+ newRating = index;
+ } else if (index < rating) {
+ newRating = index;
+ } else {
+ newRating = index + 1;
+ }
+
+ setRating(newRating);
+ if (onRatingChange) {
+ onRatingChange(newRating);
+ }
+ };
+
+ return (
+ <BackgroundContainer>
+ <StarContainer>
+ {Array.from({ length: totalStars }, (_, index) => (
+ <StyledStar
+ key={index}
+ filled={index < rating}
+ onClick={() => handleRating(index)}
+ >
+ <StarIcon fill={index < rating ? "#facc15" : "none"} stroke="#facc15" />
+ </StyledStar>
+ ))}
+ </StarContainer>
+ </BackgroundContainer>
+ );
+};
+
+export default StarRating;
|
Unknown
|
filled ์์ชฝ์ String์ผ๋ก ๊ฐ์ธ์ฃผ์ธ์
|
@@ -0,0 +1,77 @@
+import React, { useState } from "react";
+import styled from "styled-components";
+import { Star as StarIcon } from "lucide-react";
+
+interface StarRatingProps {
+ totalStars?: number;
+ initialRating?: number;
+ onRatingChange?: (rating: number) => void;
+}
+
+const BackgroundContainer = styled.div`
+ background-color: #f7f7f7;
+ width: 807.73px;
+ height: 251.63px;
+ display: flex;
+ align-items: center;
+ justify-content: center;
+`;
+
+const StarContainer = styled.div`
+ display: flex;
+ gap: 4px;
+`;
+
+const StyledStar = styled.div<{ filled: boolean }>`
+ cursor: pointer;
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ svg {
+ width: 94.96px;
+ height: 99.25px;
+ color: ${(props) => (props.filled ? "#facc15" : "#d1d5db")};
+ }
+`;
+
+const StarRating: React.FC<StarRatingProps> = ({
+ totalStars = 5,
+ initialRating = 0,
+ onRatingChange,
+}) => {
+ const [rating, setRating] = useState(initialRating);
+
+ const handleRating = (index: number) => {
+ let newRating = rating;
+ if (index + 1 === rating) {
+ newRating = index;
+ } else if (index < rating) {
+ newRating = index;
+ } else {
+ newRating = index + 1;
+ }
+
+ setRating(newRating);
+ if (onRatingChange) {
+ onRatingChange(newRating);
+ }
+ };
+
+ return (
+ <BackgroundContainer>
+ <StarContainer>
+ {Array.from({ length: totalStars }, (_, index) => (
+ <StyledStar
+ key={index}
+ filled={index < rating}
+ onClick={() => handleRating(index)}
+ >
+ <StarIcon fill={index < rating ? "#facc15" : "none"} stroke="#facc15" />
+ </StyledStar>
+ ))}
+ </StarContainer>
+ </BackgroundContainer>
+ );
+};
+
+export default StarRating;
|
Unknown
|
์ ๊ฐ ํ๊ธฐ ํ์ด์ง ๋ง๋ค๋ฉด์ ์ด ๋ถ๋ถ ์์ ํด์ ํ๊บผ๋ฒ์ PR ์ฌ๋ฆฌ๊ฒ ์ต๋๋ค
|
@@ -1,23 +1,20 @@
<template>
- <button
- @click="
- () => {
- if (!props.disabled) props.onClick();
- }
- "
- :class="getNextButtonStyle()"
- >
- <slot></slot>
+ <button @click="handleNextButtonClick" :class="getNextButtonStyle()">
+ <slot />
</button>
</template>
<script setup lang="ts">
const props = defineProps<{
- isPrimary?: boolean;
+ isPrimary?: boolean | undefined;
onClick: () => void;
- disabled?: boolean;
+ disabled?: boolean | undefined;
}>();
+const handleNextButtonClick = () => {
+ if (!props.disabled) props.onClick();
+};
+
const getNextButtonStyle = () => ({
'h-fit w-[340px] rounded-2xl border-0 p-6 text-large font-bold mb-6': true,
'bg-primary-light dark:bg-primary-dark': props.isPrimary,
|
Unknown
|
๋จ์ ๊ถ๊ธ์ฆ์ผ๋ก ์ง๋ฌธ๋๋ฆฝ๋๋ค.
undefined๋ฅผ ํ์
์ผ๋ก ์ง์ ํ์ ์ด์ ๊ฐ ์์๊น์?
NextButton.vue์ ๋ถ๋ชจ ์ปดํฌ๋ํธ์์ isPrimary ๊ฐ์ ๋ถ์ฌํ์ง ์์ ๋๊ฐ ์์ด undefined๋ฅผ ํฌํจํ ๊ฒ์ผ๋ก ๋ณด์ด๋๋ฐ,
์ด ๊ฒฝ์ฐ๋ ? ๋ง์ผ๋ก๋ ์ถฉ๋ถํ ํํ์ด ๋ ๊ฒ ๊ฐ์ต๋๋ค.
ํนํ boolean์ด๊ธฐ๋๋ฌธ์ undefined์ผ ๋ falsyํ๊ฒ ์ธ์์ด ๋ ๊ฒ ๊ฐ์๋ฐ
์ถ๊ฐํ์ ์ด์ ๊ฐ ๊ถ๊ธํฉ๋๋ค~
|
@@ -3,8 +3,8 @@
<p class="text-medium font-semi_bold">{{ title }}</p>
<div class="flex gap-x-3">
<button
- v-for="size in sizes"
- :key="size.id"
+ v-for="(size, index) in sizes"
+ :key="getButtonKey(size, index)"
class="flex flex-col items-center justify-between gap-y-[10px]"
@click="handleSizeClick(size)"
>
@@ -23,9 +23,10 @@
</template>
<script setup lang="ts">
-import { Size } from '@interface/goods';
+import { Size } from '@interface/sizes';
import { useUserSelectStore } from '@store/storeUserSelect';
import { PLACE_HOLD_IMAGE_URL } from '@constants';
+import { storeToRefs } from 'pinia';
defineProps<{
title: string;
@@ -38,11 +39,12 @@ const getImageWidth = (size: Size) => {
return 74;
};
-const { userSelect, setUserSelectSizeId, setUserSelectSizeValue } =
- useUserSelectStore();
+const store = useUserSelectStore();
+const { userSelect } = storeToRefs(store);
+const { setUserSelectSizeId, setUserSelectSizeValue } = store;
const handleSizeClick = (size: Size) => {
- if (userSelect.sizeId === size.id) {
+ if (userSelect.value.sizeId === size.id) {
setUserSelectSizeId(0);
setUserSelectSizeValue(0);
return;
@@ -51,11 +53,13 @@ const handleSizeClick = (size: Size) => {
setUserSelectSizeValue(size.value);
};
+const getButtonKey = (size: Size, index: number) => `size-${size.id}-${index}`;
+
const getUserSelectStyle = (size: Size) => ({
'flex h-[74px] w-[74px] items-center justify-center rounded-2xl border-[3px] bg-gray_01-light dark:bg-gray_01-dark':
true,
- 'border-secondary-light': userSelect.sizeId === size.id,
+ 'border-secondary-light': userSelect.value.sizeId === size.id,
'border-gray_01-light dark:border-gray_01-dark':
- userSelect.sizeId !== size.id,
+ userSelect.value.sizeId !== size.id,
});
</script>
|
Unknown
|
storeToRefs ๋ฅผ ์ฌ์ฉํด์ ๋ฐ์์ฑ์ ์ด๋ฆฌ์
จ๋ค์ ๐
|
@@ -3,16 +3,12 @@
<section
class="mx-auto flex h-full flex-col items-center justify-between bg-gray_00-light text-gray_05-light dark:bg-gray_00-dark dark:text-gray_05-dark sm:w-screen md:w-96"
>
- <ProgressNavBar prevPage="/size" pageName="ingredient" />
- <div v-if="isLoading">๋ก๋ฉ์ค์
๋๋ค.</div>
+ <ProgressNavBar prevPage="size" pageName="ingredient" />
+ <Loading v-if="isLoading" />
<IngredientBoard :ingredients="data?.ingredients ?? []" v-else />
<div v-if="!isAbleToRecommend">์ฌ๋ฃ๋ฅผ ์กฐ๊ธ ๋ ๊ณจ๋ผ๋ณผ๊น์?</div>
<NextButton
- :onClick="
- () => {
- mutation.mutate(userItem);
- }
- "
+ :onClick="postUserItem"
isPrimary
:disabled="!isAbleToRecommend || !userSelect.sizeValue"
>
@@ -29,6 +25,7 @@ import { storeToRefs } from 'pinia';
import ProgressNavBar from '@containers/ProgressNavBar.vue';
import IngredientBoard from '@containers/IngredientBoard.vue';
import NextButton from '@components/NextButton.vue';
+import Loading from '@src/components/Loading.vue';
import { useUserSelectStore } from '@store/storeUserSelect';
import { useGetIngredients } from '@apis/ingredients';
import { usePostRecipe } from '@apis/recipes';
@@ -38,6 +35,9 @@ const { userSelect, userItem } = storeToRefs(store);
const { data, isLoading } = useGetIngredients();
const mutation = usePostRecipe();
+const postUserItem = () => {
+ mutation.mutate(userItem.value);
+};
const allFlavorIdList = computed(
() =>
|
Unknown
|
์๋ฒ ์ํ๊ด๋ฆฌ์ ํด๋ผ์ด์ธํธ ์ํ๊ด๋ฆฌ๋ฅผ ๋ถ๋ฆฌํ์ฌ ๊ด๋ฆฌํ์
จ๊ตฐ์ ๐
|
@@ -1,23 +1,20 @@
<template>
- <button
- @click="
- () => {
- if (!props.disabled) props.onClick();
- }
- "
- :class="getNextButtonStyle()"
- >
- <slot></slot>
+ <button @click="handleNextButtonClick" :class="getNextButtonStyle()">
+ <slot />
</button>
</template>
<script setup lang="ts">
const props = defineProps<{
- isPrimary?: boolean;
+ isPrimary?: boolean | undefined;
onClick: () => void;
- disabled?: boolean;
+ disabled?: boolean | undefined;
}>();
+const handleNextButtonClick = () => {
+ if (!props.disabled) props.onClick();
+};
+
const getNextButtonStyle = () => ({
'h-fit w-[340px] rounded-2xl border-0 p-6 text-large font-bold mb-6': true,
'bg-primary-light dark:bg-primary-dark': props.isPrimary,
|
Unknown
|
์ฌ์ค ์ ๋ ์ถ๊ฐํ์ง ์์๋ค๊ฐ, ์ข๋ ๊ฐ์์ ์ผ๋ก ํํํ๋ ค๊ณ ์์ฑ์ ํ์ด์! ์, ๋ฉ์ด๋ธ๋ ๋ง์๋ฃ๊ณ ๋ค์ ์๊ฐํด๋ณด๋ ๊ฐ์์ฑ๋ง์ผ๋ก ์ถ๊ฐํ๋ ๊ฑด ์ข ์๋ฏธ๊ฐ ์๋ ๊ฒ ๊ฐ๊ธดํ๋ค์!!
|
@@ -3,20 +3,18 @@
class="text-gray_05-light dark:text-gray_05-dark w-6 h-6"
@click="goBack"
>
- <slot></slot>
+ <slot />
</button>
</template>
<script setup lang="ts">
-import { useRouter } from 'vue-router';
+import { pushPage } from '@router/route.helper';
const props = defineProps<{
prevPage: string;
}>();
-const router = useRouter();
-
function goBack() {
- router.push(props.prevPage);
+ pushPage(props.prevPage);
}
</script>
|
Unknown
|
ํ์ดํ ํจ์๋ก ํด์ฃผ์ธ์~
|
@@ -1,5 +1,7 @@
package com.chone.server.domains.review.domain;
+import static org.springframework.util.StringUtils.hasText;
+
import com.chone.server.commons.jpa.BaseEntity;
import com.chone.server.domains.order.domain.Order;
import com.chone.server.domains.store.domain.Store;
@@ -80,4 +82,12 @@ public static ReviewBuilder builder(
.rating(rating)
.isPublic(isPublic);
}
+
+ public void update(String content, BigDecimal rating, String imageUrl, Boolean isPublic) {
+
+ if (hasText(content)) this.content = content;
+ if (rating != null) this.rating = rating;
+ if (hasText(imageUrl)) this.imageUrl = imageUrl;
+ if (isPublic != null) this.isPublic = isPublic;
+ }
}
|
Java
|
ํด๋น update ๋ฉ์๋์ ๊ฒฝ์ฐ์ not null์ด๋ not blank ์ ํจ์ฑ ๊ฒ์ฆ์ ์ ํ๊ณ ์์ต๋๋ค.
๋ฐ๋ก ์ด์ ๊ฐ ์์๊น์?
๋ง์ผ ์ด๋ด ๊ฒฝ์ฐ request์์ null์ด ์๋ ๊ฐ์ด ์๋ค๋ฉด ์ํฐํฐ์ ํ๋ ๊ฐ์ด null๋ก ๋ณ๊ฒฝ๋๊ณ , ์ด๊ฒ์ด ๋ณ๊ฒฝ๊ฐ์ง๊ฐ ๋์ด์
๋ฐ์ดํฐ๋ฒ ์ด์ค์ ๋ฐ์ดํฐ๊ฐ null ๊ฐ์ผ๋ก ์
๋ฐ์ดํธ๋ ๊ฐ๋ฅ์ฑ์ด ์์ต๋๋ค!(์๋ฅผ ๋ค์ด, `update(null, null, null, null)`์ ํธ์ถํ๋ฉด ํด๋น ํ๋๊ฐ null๋ก ๋ฎ์ด์์์ง๋๋ค)
```java
import static org.springframework.util.StringUtils.hasText;
public void update(String content, BigDecimal rating, String imageUrl, Boolean isPublic) {
if (hasText(content)) this.content = content;
if (rating != null) this.rating = rating;
if (hasText(imageUrl)) this.imageUrl = imageUrl;
if (isPublic != null) this.isPublic = isPublic
```
์ด๋ฐ์์ผ๋ก ์์ ํด๋ณด๋ฉด ์ด๋จ๊น์? ์ฐธ๊ณ ๋ก String์ white space๊น์ง ๊ฒ์ฌํ๋ ๊ฒ์ด hasText ์ ํธ ๋ฉ์๋์
๋๋ค.
|
@@ -8,9 +8,11 @@
import com.chone.server.domains.review.domain.Review;
import com.chone.server.domains.review.dto.request.CreateRequestDto;
import com.chone.server.domains.review.dto.request.ReviewListRequestDto;
+import com.chone.server.domains.review.dto.request.UpdateRequestDto;
import com.chone.server.domains.review.dto.response.ReviewDetailResponseDto;
import com.chone.server.domains.review.dto.response.ReviewListResponseDto;
import com.chone.server.domains.review.dto.response.ReviewResponseDto;
+import com.chone.server.domains.review.dto.response.ReviewUpdateResponseDto;
import com.chone.server.domains.review.exception.ReviewExceptionCode;
import com.chone.server.domains.review.repository.ReviewRepository;
import com.chone.server.domains.review.repository.ReviewSearchRepository;
@@ -19,6 +21,8 @@
import com.chone.server.domains.user.domain.User;
import jakarta.transaction.Transactional;
import java.math.BigDecimal;
+import java.time.LocalDateTime;
+import java.time.temporal.ChronoUnit;
import java.util.UUID;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
@@ -106,7 +110,33 @@ public ReviewDetailResponseDto getReviewById(UUID reviewId, CustomUserDetails pr
private void validateAccess(User user, Review review) {
if (!review.getIsPublic() && !review.getUser().getId().equals(user.getId())) {
- throw new ApiBusinessException(ReviewExceptionCode.REVIEW_ACCESS_DENIED);
+ throw new ApiBusinessException(ReviewExceptionCode.REVIEW_FORBIDDEN_ACTION);
}
}
+
+ @Transactional
+ public ReviewUpdateResponseDto updateReview(
+ UUID reviewId, UpdateRequestDto request, CustomUserDetails principal) {
+ if (principal == null || principal.getUser() == null) {
+ throw new ApiBusinessException(ReviewExceptionCode.REVIEW_UNAUTHORIZED);
+ }
+
+ Review review =
+ reviewRepository
+ .findById(reviewId)
+ .orElseThrow(() -> new ApiBusinessException(ReviewExceptionCode.REVIEW_NOT_FOUND));
+
+ if (!review.getUser().getId().equals(principal.getUser().getId())) {
+ throw new ApiBusinessException(ReviewExceptionCode.REVIEW_FORBIDDEN_ACTION);
+ }
+
+ if (ChronoUnit.HOURS.between(review.getCreatedAt(), LocalDateTime.now()) > 72) {
+ throw new ApiBusinessException(ReviewExceptionCode.REVIEW_UPDATE_EXPIRED);
+ }
+
+ review.update(
+ request.getContent(), request.getRating(), request.getImageUrl(), request.getIsPublic());
+
+ return new ReviewUpdateResponseDto(review.getId(), review.getUpdatedAt());
+ }
}
|
Java
|
์ ๋ ์ด๋ฒ์ ์ฃผ๋ฌธ ์ญ์ ๊ธฐ๋ฅ์ ๊ตฌํํ๋ฉด์ ๊ฐ์๊ธฐ ๊นจ๋ฌ์ ๊ฑด๋ฐ,
์ ํฌ๊ฐ soft delete๋ฅผ ํ๊ณ ์์ด์ findById๋ฅผ ํ ๋ ์กฐ๊ฑด์ผ๋ก deletedAt null ์กฐ๊ฑด์ ๊ฑธ์ด์ผ ์ญ์ ๋ ๊ฒ์ ์ ์ธํ ์ ์๊ฒ ๋ฉ๋๋ค.
๊ทธ๋์ ์กฐํ ์ ํด๋น ์กฐ๊ฑด์ ํฌํจํ์ฌ ์์ ํ๋ ๊ฒ์ด ์ข์ ๊ฒ ๊ฐ์์! ์๋๋ฉด ๋ธ๋์น๋ฅผ ์๋ก ํ์ ํด๋น ๊ด๋ จ ์กฐํ๋ค์ ์์ ํด๋ณด๋ฉด ์ข์ ๊ฒ ๊ฐ์ต๋๋ค!
|
@@ -1,5 +1,7 @@
package com.chone.server.domains.review.domain;
+import static org.springframework.util.StringUtils.hasText;
+
import com.chone.server.commons.jpa.BaseEntity;
import com.chone.server.domains.order.domain.Order;
import com.chone.server.domains.store.domain.Store;
@@ -80,4 +82,12 @@ public static ReviewBuilder builder(
.rating(rating)
.isPublic(isPublic);
}
+
+ public void update(String content, BigDecimal rating, String imageUrl, Boolean isPublic) {
+
+ if (hasText(content)) this.content = content;
+ if (rating != null) this.rating = rating;
+ if (hasText(imageUrl)) this.imageUrl = imageUrl;
+ if (isPublic != null) this.isPublic = isPublic;
+ }
}
|
Java
|
์๋น์ค ๋ ์ด์ด์์ ์ ํจ์ฑ ๊ฒ์ฌ๋ฅผ ์ํํ๊ณ ์๊ธฐ ๋๋ฌธ์ ์ด๋ ๊ฒ ๋๋ฉด ํด๋น ํ๋์์ null ๋ก DB ๋ฐ์๋๋ค๋ ๊ฑธ ๋์ณค์ต๋๋ค! ์๋ ค์ฃผ์ ๋ฐฉ๋ฒ์ผ๋ก ์์ ํ๋๋ก ํ๊ฒ ์ต๋๋ค :)
|
@@ -8,9 +8,11 @@
import com.chone.server.domains.review.domain.Review;
import com.chone.server.domains.review.dto.request.CreateRequestDto;
import com.chone.server.domains.review.dto.request.ReviewListRequestDto;
+import com.chone.server.domains.review.dto.request.UpdateRequestDto;
import com.chone.server.domains.review.dto.response.ReviewDetailResponseDto;
import com.chone.server.domains.review.dto.response.ReviewListResponseDto;
import com.chone.server.domains.review.dto.response.ReviewResponseDto;
+import com.chone.server.domains.review.dto.response.ReviewUpdateResponseDto;
import com.chone.server.domains.review.exception.ReviewExceptionCode;
import com.chone.server.domains.review.repository.ReviewRepository;
import com.chone.server.domains.review.repository.ReviewSearchRepository;
@@ -19,6 +21,8 @@
import com.chone.server.domains.user.domain.User;
import jakarta.transaction.Transactional;
import java.math.BigDecimal;
+import java.time.LocalDateTime;
+import java.time.temporal.ChronoUnit;
import java.util.UUID;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
@@ -106,7 +110,33 @@ public ReviewDetailResponseDto getReviewById(UUID reviewId, CustomUserDetails pr
private void validateAccess(User user, Review review) {
if (!review.getIsPublic() && !review.getUser().getId().equals(user.getId())) {
- throw new ApiBusinessException(ReviewExceptionCode.REVIEW_ACCESS_DENIED);
+ throw new ApiBusinessException(ReviewExceptionCode.REVIEW_FORBIDDEN_ACTION);
}
}
+
+ @Transactional
+ public ReviewUpdateResponseDto updateReview(
+ UUID reviewId, UpdateRequestDto request, CustomUserDetails principal) {
+ if (principal == null || principal.getUser() == null) {
+ throw new ApiBusinessException(ReviewExceptionCode.REVIEW_UNAUTHORIZED);
+ }
+
+ Review review =
+ reviewRepository
+ .findById(reviewId)
+ .orElseThrow(() -> new ApiBusinessException(ReviewExceptionCode.REVIEW_NOT_FOUND));
+
+ if (!review.getUser().getId().equals(principal.getUser().getId())) {
+ throw new ApiBusinessException(ReviewExceptionCode.REVIEW_FORBIDDEN_ACTION);
+ }
+
+ if (ChronoUnit.HOURS.between(review.getCreatedAt(), LocalDateTime.now()) > 72) {
+ throw new ApiBusinessException(ReviewExceptionCode.REVIEW_UPDATE_EXPIRED);
+ }
+
+ review.update(
+ request.getContent(), request.getRating(), request.getImageUrl(), request.getIsPublic());
+
+ return new ReviewUpdateResponseDto(review.getId(), review.getUpdatedAt());
+ }
}
|
Java
|
์กฐํ ์ ์ญ์ ๋ ๋ฆฌ๋ทฐ ์กฐํ๋์ง ์๋๋ก ์์ ํ๊ฒ ์ต๋๋ค~
|
@@ -0,0 +1,48 @@
+package com.ioteam.order_management_platform.review.entity;
+
+import com.ioteam.order_management_platform.global.entity.BaseEntity;
+import com.ioteam.order_management_platform.review.dto.CreateReviewRequestDto;
+import com.ioteam.order_management_platform.review.dto.ReviewResponseDto;
+import jakarta.persistence.*;
+import lombok.*;
+
+import java.time.LocalDateTime;
+import java.util.UUID;
+
+@Builder
+@NoArgsConstructor(access = AccessLevel.PROTECTED)
+@AllArgsConstructor(access = AccessLevel.PROTECTED)
+@Entity
+public class Review extends BaseEntity {
+
+ @Id
+ @GeneratedValue(strategy = GenerationType.UUID)
+ private UUID reviewId;
+ private int reviewScore;
+ @Column(length = 1000)
+ private String reviewContent;
+ @Column(length = 100)
+ private String reviewImageUrl;
+ private Boolean isPublic;
+ private LocalDateTime deletedAt;
+ private UUID deletedBy;
+
+ public Review(CreateReviewRequestDto requestDto) {
+ this.reviewScore = requestDto.getReviewScore();
+ this.reviewContent = requestDto.getReviewContent();
+ this.reviewImageUrl = requestDto.getReviewImageUrl();
+ this.isPublic = requestDto.getIsPublic();
+ }
+
+ public ReviewResponseDto toResponseDto() {
+ return ReviewResponseDto
+ .builder()
+ .reviewId(this.reviewId)
+ .reviewScore(this.reviewScore)
+ .reviewContent(this.reviewContent)
+ .reviewImageUrl(this.reviewImageUrl)
+ //.reviewOrderId(this.)
+ .isPublic(this.isPublic)
+ .build();
+ }
+}
|
Java
|
P5: ๋จ์ ๊ถ๊ธ์ฆ์
๋๋ค! ๊ธฐ๋ณธ ์ง์์ด ๋ถ์กฑํ์ฌ Boolean์ default ๊ฐ์ด null์ด๊ณ , boolean์ false์ธ ๊ฒ์ด ์ฐจ์ด์ ์ด๋ผ๋ ๊ฒ๋ง ์๊ณ ์ฌ์ญค๋ณด๋ ์ .. ์ํด๋ถํ๋๋ฆฝ๋๋ค..! ๐
Boolean์ ์ฌ์ฉํ ์ด์ ๊ฐ ๊ถ๊ธํฉ๋๋ค.
P4: ๊ณต๊ฐ ์ฌ๋ถ ๊ธฐ๋ณธ๊ฐ์ด true ์ด๋ฏ๋ก @ColumnDefault ๋ก ๊ธฐ๋ณธ๊ฐ ์ค์ ์ด ํ์ํ์ง ์์๊น์?? ๐
|
@@ -0,0 +1,48 @@
+package com.ioteam.order_management_platform.review.entity;
+
+import com.ioteam.order_management_platform.global.entity.BaseEntity;
+import com.ioteam.order_management_platform.review.dto.CreateReviewRequestDto;
+import com.ioteam.order_management_platform.review.dto.ReviewResponseDto;
+import jakarta.persistence.*;
+import lombok.*;
+
+import java.time.LocalDateTime;
+import java.util.UUID;
+
+@Builder
+@NoArgsConstructor(access = AccessLevel.PROTECTED)
+@AllArgsConstructor(access = AccessLevel.PROTECTED)
+@Entity
+public class Review extends BaseEntity {
+
+ @Id
+ @GeneratedValue(strategy = GenerationType.UUID)
+ private UUID reviewId;
+ private int reviewScore;
+ @Column(length = 1000)
+ private String reviewContent;
+ @Column(length = 100)
+ private String reviewImageUrl;
+ private Boolean isPublic;
+ private LocalDateTime deletedAt;
+ private UUID deletedBy;
+
+ public Review(CreateReviewRequestDto requestDto) {
+ this.reviewScore = requestDto.getReviewScore();
+ this.reviewContent = requestDto.getReviewContent();
+ this.reviewImageUrl = requestDto.getReviewImageUrl();
+ this.isPublic = requestDto.getIsPublic();
+ }
+
+ public ReviewResponseDto toResponseDto() {
+ return ReviewResponseDto
+ .builder()
+ .reviewId(this.reviewId)
+ .reviewScore(this.reviewScore)
+ .reviewContent(this.reviewContent)
+ .reviewImageUrl(this.reviewImageUrl)
+ //.reviewOrderId(this.)
+ .isPublic(this.isPublic)
+ .build();
+ }
+}
|
Java
|
@Ryujy ๋, ์๊ฒฌ ๊ฐ์ฌํฉ๋๋ค! @ColumnDefault ๋ก ๊ธฐ๋ณธ๊ฐ ์ค์ ํ๋ ๋ถ๋ถ์ ๋์ณค๋ค์. ์ถ๊ฐํ๊ฒ ์ต๋๋ค.
Boolean์ ์ฌ์ฉํ๋ ์ด์ ๋ ํน๋ณํ๋ ์์ต๋๋ค.
|
@@ -0,0 +1,48 @@
+package com.ioteam.order_management_platform.review.entity;
+
+import com.ioteam.order_management_platform.global.entity.BaseEntity;
+import com.ioteam.order_management_platform.review.dto.CreateReviewRequestDto;
+import com.ioteam.order_management_platform.review.dto.ReviewResponseDto;
+import jakarta.persistence.*;
+import lombok.*;
+
+import java.time.LocalDateTime;
+import java.util.UUID;
+
+@Builder
+@NoArgsConstructor(access = AccessLevel.PROTECTED)
+@AllArgsConstructor(access = AccessLevel.PROTECTED)
+@Entity
+public class Review extends BaseEntity {
+
+ @Id
+ @GeneratedValue(strategy = GenerationType.UUID)
+ private UUID reviewId;
+ private int reviewScore;
+ @Column(length = 1000)
+ private String reviewContent;
+ @Column(length = 100)
+ private String reviewImageUrl;
+ private Boolean isPublic;
+ private LocalDateTime deletedAt;
+ private UUID deletedBy;
+
+ public Review(CreateReviewRequestDto requestDto) {
+ this.reviewScore = requestDto.getReviewScore();
+ this.reviewContent = requestDto.getReviewContent();
+ this.reviewImageUrl = requestDto.getReviewImageUrl();
+ this.isPublic = requestDto.getIsPublic();
+ }
+
+ public ReviewResponseDto toResponseDto() {
+ return ReviewResponseDto
+ .builder()
+ .reviewId(this.reviewId)
+ .reviewScore(this.reviewScore)
+ .reviewContent(this.reviewContent)
+ .reviewImageUrl(this.reviewImageUrl)
+ //.reviewOrderId(this.)
+ .isPublic(this.isPublic)
+ .build();
+ }
+}
|
Java
|
@Ryujy ๋ Boolean ์ฌ์ฉํ ์ด์ ๊ณต๋ถํด๋๊ณ ๊น๋จน๊ณ ์์๋ค์.
- boolean์ผ๋ก ์ฌ์ฉํ๋ ๊ฒฝ์ฐ ์๋ฐ ๋น ๊ท์ฝ์ ๋ฐ๋ฅด๋ฉด getter ๋ฉ์๋๊ฐ isXXX() ํํ๋ก ์์ฑ๋์ด์ผ ํฉ๋๋ค.
- ๊ทธ๋์ getter ๋ฉ์๋ ์๋์์ฑ(๋กฌ๋ณต, ์ธํ
๋ฆฌ์ ์ด ํ์ฉ)ํ๋ ๊ฒฝ์ฐ์ ๊ฐ์ฒด ํ๋กํผํฐ์ ๋ค์ด๋ฐ์์ ๋ฌธ์ (isXXX ์ด ์๋ XXX ํํ๋ก ๋ค์ด๋ฐ์ด ๋๋ ๋ฌธ์ )๊ฐ ๋ฐ์ํ๊ฒ ๋ฉ๋๋ค.
- ํด๊ฒฐ ๋ฐฉ์์ผ๋ก ๋ช ๊ฐ์ง๊ฐ ์กด์ฌํ๋๋ฐ( [์ ๋ธ๋ก๊ทธ์ ๊ฐ๋จํ ์ ๋ฆฌํด๋์ด์.](https://ichmww2.tistory.com/87)) ์ ๋ wrapper ํด๋์ค๋ก ์ฌ์ฉํ๋ ๊ฒ์ ์ ํธํด์ Boolean ํ์ฉํ์ต๋๋ค.
|
@@ -1,8 +1,79 @@
import React, { Component } from 'react';
+import { Link } from 'react-router-dom';
+
+import './Login.scss';
class Login extends Component {
+ constructor() {
+ super();
+ this.state = {
+ id: '',
+ pw: '',
+ };
+ }
+
+ handleInput = event => {
+ const { name, value } = event.target;
+ this.setState({
+ [name]: value,
+ });
+ };
+
+ goToMain = () => {
+ this.props.history.push('/main-Soojeong#');
+ };
+
render() {
- return <div>๋ก๊ทธ์ธ</div>;
+ const isValid =
+ this.state.id.includes('@') &&
+ this.state.id.length >= 5 &&
+ this.state.pw.length >= 8;
+
+ return (
+ <div className="Login">
+ <main>
+ <header>
+ <h1>Westagram</h1>
+ </header>
+
+ <section className="loginInputBox">
+ <h2 className="sr-only">login page</h2>
+ <form>
+ <input
+ name="id"
+ autoComplete="off"
+ onChange={this.handleInput}
+ type="text"
+ id="loginId"
+ value={this.state.id}
+ placeholder="์ ํ๋ฒํธ, ์ฌ์ฉ์ ์ด๋ฆ ๋๋ ์ด๋ฉ์ผ"
+ />
+ <input
+ name="pw"
+ onChange={this.handleInput}
+ type="password"
+ value={this.state.pw}
+ placeholder="๋น๋ฐ๋ฒํธ"
+ />
+ <button
+ onClick={this.goToMain}
+ type="button"
+ className="loginBtn"
+ disabled={!isValid}
+ >
+ ๋ก๊ทธ์ธ
+ </button>
+ </form>
+ </section>
+
+ <footer>
+ <Link to="" className="findPassword">
+ ๋น๋ฐ๋ฒํธ๋ฅผ ์์ผ์
จ๋์?
+ </Link>
+ </footer>
+ </main>
+ </div>
+ );
}
}
|
JavaScript
|
์ค ๊ตฌ์กฐ๋ถํด ํ ๋น~
|
@@ -1,8 +1,79 @@
import React, { Component } from 'react';
+import { Link } from 'react-router-dom';
+
+import './Login.scss';
class Login extends Component {
+ constructor() {
+ super();
+ this.state = {
+ id: '',
+ pw: '',
+ };
+ }
+
+ handleInput = event => {
+ const { name, value } = event.target;
+ this.setState({
+ [name]: value,
+ });
+ };
+
+ goToMain = () => {
+ this.props.history.push('/main-Soojeong#');
+ };
+
render() {
- return <div>๋ก๊ทธ์ธ</div>;
+ const isValid =
+ this.state.id.includes('@') &&
+ this.state.id.length >= 5 &&
+ this.state.pw.length >= 8;
+
+ return (
+ <div className="Login">
+ <main>
+ <header>
+ <h1>Westagram</h1>
+ </header>
+
+ <section className="loginInputBox">
+ <h2 className="sr-only">login page</h2>
+ <form>
+ <input
+ name="id"
+ autoComplete="off"
+ onChange={this.handleInput}
+ type="text"
+ id="loginId"
+ value={this.state.id}
+ placeholder="์ ํ๋ฒํธ, ์ฌ์ฉ์ ์ด๋ฆ ๋๋ ์ด๋ฉ์ผ"
+ />
+ <input
+ name="pw"
+ onChange={this.handleInput}
+ type="password"
+ value={this.state.pw}
+ placeholder="๋น๋ฐ๋ฒํธ"
+ />
+ <button
+ onClick={this.goToMain}
+ type="button"
+ className="loginBtn"
+ disabled={!isValid}
+ >
+ ๋ก๊ทธ์ธ
+ </button>
+ </form>
+ </section>
+
+ <footer>
+ <Link to="" className="findPassword">
+ ๋น๋ฐ๋ฒํธ๋ฅผ ์์ผ์
จ๋์?
+ </Link>
+ </footer>
+ </main>
+ </div>
+ );
}
}
|
JavaScript
|
this.state.id.includes('@') &&
this.state.id.length >= 5 &&
this.state.pw.length >= 8 ์ด๊ฑธ true/false Boolean?? ์ด๊ฐ์ ์ฌ์ฉํด์ ์ผํญ์ฐ์ฐ์๋ก ํด๋ ๋์ง ์์๊น์ ์์ ๋์ ์ํ์๋ ์๋ง๊ฐ๋ฅํ์ค๋ฏ!
|
@@ -0,0 +1,61 @@
+.Login {
+ display: flex;
+ justify-content: center;
+ align-items: center;
+ height: 100vh;
+
+ main {
+ display: flex;
+ flex-direction: column;
+ justify-content: space-around;
+ width: 350px;
+ height: 380px;
+ padding: 40px;
+ border: 1px solid #ccc;
+
+ header {
+ h1 {
+ font-family: 'Lobster', cursive;
+ text-align: center;
+ }
+ }
+
+ .loginInputBox {
+ form {
+ display: flex;
+ flex-direction: column;
+ justify-content: center;
+
+ input {
+ margin-bottom: 5px;
+ padding: 9px 8px 7px;
+ background-color: rgb(250, 250, 250);
+ border: 1px solid rgb(38, 38, 38);
+ border-radius: 3px;
+ }
+
+ .loginBtn {
+ margin-top: 10px;
+ padding: 9px 8px 7px;
+ border: none;
+ border-radius: 3px;
+ color: #fff;
+ background-color: #0096f6;
+ &:disabled {
+ background-color: #c0dffd;
+ }
+ }
+ }
+ }
+
+ footer {
+ .findPassword {
+ display: block;
+ margin-top: 50px;
+ text-align: center;
+ color: #00376b;
+ font-size: 14px;
+ }
+ }
+ }
+}
|
Unknown
|
์ด๊ฑด ์ ์ฃผ์์ผ๋ก ๋์๋์???
|
@@ -0,0 +1,134 @@
+[
+ {
+ "id": 1,
+ "userName": "eessoo__",
+ "src": "../images/soojeongLee/user2.jpg",
+ "feedText": "๐",
+ "commentData": [
+ {
+ "id": 1,
+ "userName": "wecode",
+ "content": "Welcome to world best coding bootcamp!",
+ "commnetLike": false
+ },
+ {
+ "id": 2,
+ "userName": "soojeonglee",
+ "content": "Hi there.",
+ "commnetLike": false
+ },
+ {
+ "id": 3,
+ "userName": "jaehyunlee",
+ "content": "Hey.",
+ "commnetLike": false
+ },
+ {
+ "id": 4,
+ "userName": "gyeongminlee",
+ "content": "Hi.",
+ "commnetLike": true
+ }
+ ],
+ "isLike": false
+ },
+ {
+ "id": 2,
+ "userName": "zz_ing94",
+ "src": "../../images/soojeongLee/user3.jpg",
+ "feedText": "Toy story ๐",
+ "commentData": [
+ {
+ "id": 1,
+ "userName": "wecode",
+ "content": "Welcome to world best coding bootcamp!",
+ "commnetLike": false
+ },
+ {
+ "id": 2,
+ "userName": "jisuoh",
+ "content": "โจ",
+ "commnetLike": true
+ },
+ {
+ "id": 3,
+ "userName": "jungjunsung",
+ "content": "coffee",
+ "commnetLike": false
+ },
+ {
+ "id": 4,
+ "userName": "somihwang",
+ "content": "ํฌํค",
+ "commnetLike": true
+ }
+ ],
+ "isLike": false
+ },
+ {
+ "id": 3,
+ "userName": "hwayoonci",
+ "src": "../../images/soojeongLee/user4.jpg",
+ "feedText": "์ค๋์ ์ผ๊ธฐ",
+ "commentData": [
+ {
+ "id": 1,
+ "userName": "wecode",
+ "content": "Welcome to world best coding bootcamp!",
+ "commnetLike": false
+ },
+ {
+ "id": 2,
+ "userName": "yunkyunglee",
+ "content": "๊ท์ฌ์ด ์คํฐ์ปค",
+ "commnetLike": true
+ },
+ {
+ "id": 3,
+ "userName": "summer",
+ "content": "๐ถ",
+ "commnetLike": false
+ },
+ {
+ "id": 4,
+ "userName": "uiyeonlee",
+ "content": "๐๐ป",
+ "commnetLike": true
+ }
+ ],
+ "isLike": true
+ },
+ {
+ "id": 4,
+ "userName": "cosz_zy",
+ "src": "../../images/soojeongLee/user5.jpg",
+ "feedText": "1์ผ ํ๊ฐ ๐จ ",
+ "commentData": [
+ {
+ "id": 1,
+ "userName": "wecode",
+ "content": "Welcome to world best coding bootcamp!",
+ "commnetLike": false
+ },
+ {
+ "id": 2,
+ "userName": "soojeonglee",
+ "content": "Hi there.",
+ "commnetLike": false
+ },
+ {
+ "id": 3,
+ "userName": "jaehyunlee",
+ "content": "Hey.",
+ "commnetLike": true
+ },
+ {
+ "id": 4,
+ "userName": "gyeongminlee",
+ "content": "Hi.",
+ "commnetLike": true
+ }
+ ],
+ "isLike": false
+ }
+]
|
Unknown
|
์ ์ด์จ ํ์ผ๋ ์์๊ตฐ์!
|
@@ -0,0 +1,175 @@
+import React, { Component } from 'react';
+import { Link } from 'react-router-dom';
+
+import Comment from './Comment/Comment';
+
+import '../Feed/Feed.scss';
+
+export class Feed extends Component {
+ constructor() {
+ super();
+ this.state = {
+ comment: '',
+ // commentList: [],
+ // isLike: false,
+ };
+ }
+
+ // componentDidMount() {
+ // this.setState({
+ // commentList: this.props.commentData,
+ // isLike: this.props.isLike,
+ // });
+ // }
+
+ hadComment = event => {
+ this.setState({
+ comment: event.target.value,
+ });
+ };
+
+ // ํด๋ฆญํจ์
+ submitComent = () => {
+ // this.setState({
+ // commentList: this.state.commentList.concat([
+ // {
+ // id: this.state.commentList.length + 1,
+ // userName: 'eessoo__',
+ // content: this.state.comment,
+ // commentLike: false,
+ // },
+ // ]),
+ // comment: '',
+ // });
+ };
+
+ handleKeyPress = event => {
+ if (event.key === 'Enter') {
+ event.preventDefault();
+ this.submitComent();
+ }
+ };
+
+ handleLike = () => {
+ this.setState({
+ isLike: !this.state.isLike,
+ });
+ };
+
+ // ์ถ๊ฐ ๊ธฐ๋ฅ ๊ตฌํ ์ค
+ // handleCommnetDelete = id => {
+ // const newCommentList = this.state.commentList.filter(comment => {
+ // return comment.id !== id;
+ // });
+
+ // this.setState({
+ // commentList: newCommentList,
+ // });
+ // };
+
+ render() {
+ return (
+ <article>
+ <header>
+ <h1>
+ <Link className="contentHeader"></Link>
+ <Link className="userName">{this.props.userName}</Link>
+ </h1>
+ <button className="ellipsis" type="button">
+ <i className="fas fa-ellipsis-h ellipsisIcon"></i>
+ </button>
+ </header>
+ <section className="feedContent">
+ <img alt="feedImage" src={this.props.src} />
+ <ul className="reactionsBox">
+ <li className="reactionsLeft">
+ <button
+ className="leftButton"
+ type="button"
+ onClick={this.handleLike}
+ >
+ {this.state.isLike ? (
+ <i className="fas fa-heart" />
+ ) : (
+ <i className="far fa-heart" />
+ )}
+ </button>
+ <button className="leftButton" type="button">
+ <i className="far fa-comment" />
+ </button>
+ <button className="leftButton" type="button">
+ <i className="fas fa-external-link-alt" />
+ </button>
+ </li>
+ <li className="reactionsRight">
+ <button className="rightButton">
+ <i className="far fa-bookmark" />
+ </button>
+ </li>
+ </ul>
+ <h2>
+ <Link className="userProfile feedConUser"></Link>
+ <b>eessoo__</b>๋ ์ธ
+ <button className="likeCount">
+ <b> 7๋ช
</b>
+ </button>
+ ์ด ์ข์ํฉ๋๋ค.
+ </h2>
+ <p className="feedText">
+ {this.props.feedText}
+ <span className="postTime">54๋ถ ์ </span>
+ </p>
+ <ul id="commnetBox">
+ {/* {this.state.commentList.map(comment => {
+ return (
+ <Comment
+ key={comment.id}
+ userName={comment.userName}
+ content={comment.content}
+ commnetLike={comment.commnetLike}
+ // ์ถ๊ฐ ๊ธฐ๋ฅ ๊ตฌํ ์ค
+ // handleCommnetDelete={this.handleCommnetDelete}
+ // id={comment.id}
+ />
+ );
+ })} */}
+ {this.props.commentData.map(comment => {
+ return (
+ <Comment
+ key={comment.id}
+ userName={comment.userName}
+ content={comment.content}
+ commnetLike={comment.commnetLike}
+ // ์ถ๊ฐ ๊ธฐ๋ฅ ๊ตฌํ ์ค
+ // handleCommnetDelete={this.handleCommnetDelete}
+ // id={comment.id}
+ />
+ );
+ })}
+ </ul>
+ </section>
+ <footer className="feedFooter">
+ <form className="inputBox" onKeyPress={this.handleKeyPress}>
+ <input
+ autoComplete="off"
+ onChange={this.hadComment}
+ className="comment"
+ value={this.state.comment}
+ type="text"
+ placeholder="๋๊ธ ๋ฌ๊ธฐ..."
+ />
+ <button
+ onClick={this.submitComent}
+ className="commentSubmit"
+ type="button"
+ >
+ ๊ฒ์
+ </button>
+ </form>
+ </footer>
+ </article>
+ );
+ }
+}
+
+export default Feed;
|
JavaScript
|
์ค ์ด๋ ๊ฒ ๋ค์ ๋ณผ ์ ์๋ ๋ฐฉ๋ฒ๋ ๋์์ง ์์ ๋ฏ ?
๋์ค์ ๊ฐ์๋ ์ง์์ผ ๋ ์๋ ์์ง๋ง...?
|
@@ -0,0 +1,175 @@
+import React, { Component } from 'react';
+import { Link } from 'react-router-dom';
+
+import Comment from './Comment/Comment';
+
+import '../Feed/Feed.scss';
+
+export class Feed extends Component {
+ constructor() {
+ super();
+ this.state = {
+ comment: '',
+ // commentList: [],
+ // isLike: false,
+ };
+ }
+
+ // componentDidMount() {
+ // this.setState({
+ // commentList: this.props.commentData,
+ // isLike: this.props.isLike,
+ // });
+ // }
+
+ hadComment = event => {
+ this.setState({
+ comment: event.target.value,
+ });
+ };
+
+ // ํด๋ฆญํจ์
+ submitComent = () => {
+ // this.setState({
+ // commentList: this.state.commentList.concat([
+ // {
+ // id: this.state.commentList.length + 1,
+ // userName: 'eessoo__',
+ // content: this.state.comment,
+ // commentLike: false,
+ // },
+ // ]),
+ // comment: '',
+ // });
+ };
+
+ handleKeyPress = event => {
+ if (event.key === 'Enter') {
+ event.preventDefault();
+ this.submitComent();
+ }
+ };
+
+ handleLike = () => {
+ this.setState({
+ isLike: !this.state.isLike,
+ });
+ };
+
+ // ์ถ๊ฐ ๊ธฐ๋ฅ ๊ตฌํ ์ค
+ // handleCommnetDelete = id => {
+ // const newCommentList = this.state.commentList.filter(comment => {
+ // return comment.id !== id;
+ // });
+
+ // this.setState({
+ // commentList: newCommentList,
+ // });
+ // };
+
+ render() {
+ return (
+ <article>
+ <header>
+ <h1>
+ <Link className="contentHeader"></Link>
+ <Link className="userName">{this.props.userName}</Link>
+ </h1>
+ <button className="ellipsis" type="button">
+ <i className="fas fa-ellipsis-h ellipsisIcon"></i>
+ </button>
+ </header>
+ <section className="feedContent">
+ <img alt="feedImage" src={this.props.src} />
+ <ul className="reactionsBox">
+ <li className="reactionsLeft">
+ <button
+ className="leftButton"
+ type="button"
+ onClick={this.handleLike}
+ >
+ {this.state.isLike ? (
+ <i className="fas fa-heart" />
+ ) : (
+ <i className="far fa-heart" />
+ )}
+ </button>
+ <button className="leftButton" type="button">
+ <i className="far fa-comment" />
+ </button>
+ <button className="leftButton" type="button">
+ <i className="fas fa-external-link-alt" />
+ </button>
+ </li>
+ <li className="reactionsRight">
+ <button className="rightButton">
+ <i className="far fa-bookmark" />
+ </button>
+ </li>
+ </ul>
+ <h2>
+ <Link className="userProfile feedConUser"></Link>
+ <b>eessoo__</b>๋ ์ธ
+ <button className="likeCount">
+ <b> 7๋ช
</b>
+ </button>
+ ์ด ์ข์ํฉ๋๋ค.
+ </h2>
+ <p className="feedText">
+ {this.props.feedText}
+ <span className="postTime">54๋ถ ์ </span>
+ </p>
+ <ul id="commnetBox">
+ {/* {this.state.commentList.map(comment => {
+ return (
+ <Comment
+ key={comment.id}
+ userName={comment.userName}
+ content={comment.content}
+ commnetLike={comment.commnetLike}
+ // ์ถ๊ฐ ๊ธฐ๋ฅ ๊ตฌํ ์ค
+ // handleCommnetDelete={this.handleCommnetDelete}
+ // id={comment.id}
+ />
+ );
+ })} */}
+ {this.props.commentData.map(comment => {
+ return (
+ <Comment
+ key={comment.id}
+ userName={comment.userName}
+ content={comment.content}
+ commnetLike={comment.commnetLike}
+ // ์ถ๊ฐ ๊ธฐ๋ฅ ๊ตฌํ ์ค
+ // handleCommnetDelete={this.handleCommnetDelete}
+ // id={comment.id}
+ />
+ );
+ })}
+ </ul>
+ </section>
+ <footer className="feedFooter">
+ <form className="inputBox" onKeyPress={this.handleKeyPress}>
+ <input
+ autoComplete="off"
+ onChange={this.hadComment}
+ className="comment"
+ value={this.state.comment}
+ type="text"
+ placeholder="๋๊ธ ๋ฌ๊ธฐ..."
+ />
+ <button
+ onClick={this.submitComent}
+ className="commentSubmit"
+ type="button"
+ >
+ ๊ฒ์
+ </button>
+ </form>
+ </footer>
+ </article>
+ );
+ }
+}
+
+export default Feed;
|
JavaScript
|
๋ฒํผ์ผ๋ก ํ ์ด์ ๊ฐ ์๋์? ๊ถ๊ธ
|
@@ -0,0 +1,175 @@
+import React, { Component } from 'react';
+import { Link } from 'react-router-dom';
+
+import Comment from './Comment/Comment';
+
+import '../Feed/Feed.scss';
+
+export class Feed extends Component {
+ constructor() {
+ super();
+ this.state = {
+ comment: '',
+ // commentList: [],
+ // isLike: false,
+ };
+ }
+
+ // componentDidMount() {
+ // this.setState({
+ // commentList: this.props.commentData,
+ // isLike: this.props.isLike,
+ // });
+ // }
+
+ hadComment = event => {
+ this.setState({
+ comment: event.target.value,
+ });
+ };
+
+ // ํด๋ฆญํจ์
+ submitComent = () => {
+ // this.setState({
+ // commentList: this.state.commentList.concat([
+ // {
+ // id: this.state.commentList.length + 1,
+ // userName: 'eessoo__',
+ // content: this.state.comment,
+ // commentLike: false,
+ // },
+ // ]),
+ // comment: '',
+ // });
+ };
+
+ handleKeyPress = event => {
+ if (event.key === 'Enter') {
+ event.preventDefault();
+ this.submitComent();
+ }
+ };
+
+ handleLike = () => {
+ this.setState({
+ isLike: !this.state.isLike,
+ });
+ };
+
+ // ์ถ๊ฐ ๊ธฐ๋ฅ ๊ตฌํ ์ค
+ // handleCommnetDelete = id => {
+ // const newCommentList = this.state.commentList.filter(comment => {
+ // return comment.id !== id;
+ // });
+
+ // this.setState({
+ // commentList: newCommentList,
+ // });
+ // };
+
+ render() {
+ return (
+ <article>
+ <header>
+ <h1>
+ <Link className="contentHeader"></Link>
+ <Link className="userName">{this.props.userName}</Link>
+ </h1>
+ <button className="ellipsis" type="button">
+ <i className="fas fa-ellipsis-h ellipsisIcon"></i>
+ </button>
+ </header>
+ <section className="feedContent">
+ <img alt="feedImage" src={this.props.src} />
+ <ul className="reactionsBox">
+ <li className="reactionsLeft">
+ <button
+ className="leftButton"
+ type="button"
+ onClick={this.handleLike}
+ >
+ {this.state.isLike ? (
+ <i className="fas fa-heart" />
+ ) : (
+ <i className="far fa-heart" />
+ )}
+ </button>
+ <button className="leftButton" type="button">
+ <i className="far fa-comment" />
+ </button>
+ <button className="leftButton" type="button">
+ <i className="fas fa-external-link-alt" />
+ </button>
+ </li>
+ <li className="reactionsRight">
+ <button className="rightButton">
+ <i className="far fa-bookmark" />
+ </button>
+ </li>
+ </ul>
+ <h2>
+ <Link className="userProfile feedConUser"></Link>
+ <b>eessoo__</b>๋ ์ธ
+ <button className="likeCount">
+ <b> 7๋ช
</b>
+ </button>
+ ์ด ์ข์ํฉ๋๋ค.
+ </h2>
+ <p className="feedText">
+ {this.props.feedText}
+ <span className="postTime">54๋ถ ์ </span>
+ </p>
+ <ul id="commnetBox">
+ {/* {this.state.commentList.map(comment => {
+ return (
+ <Comment
+ key={comment.id}
+ userName={comment.userName}
+ content={comment.content}
+ commnetLike={comment.commnetLike}
+ // ์ถ๊ฐ ๊ธฐ๋ฅ ๊ตฌํ ์ค
+ // handleCommnetDelete={this.handleCommnetDelete}
+ // id={comment.id}
+ />
+ );
+ })} */}
+ {this.props.commentData.map(comment => {
+ return (
+ <Comment
+ key={comment.id}
+ userName={comment.userName}
+ content={comment.content}
+ commnetLike={comment.commnetLike}
+ // ์ถ๊ฐ ๊ธฐ๋ฅ ๊ตฌํ ์ค
+ // handleCommnetDelete={this.handleCommnetDelete}
+ // id={comment.id}
+ />
+ );
+ })}
+ </ul>
+ </section>
+ <footer className="feedFooter">
+ <form className="inputBox" onKeyPress={this.handleKeyPress}>
+ <input
+ autoComplete="off"
+ onChange={this.hadComment}
+ className="comment"
+ value={this.state.comment}
+ type="text"
+ placeholder="๋๊ธ ๋ฌ๊ธฐ..."
+ />
+ <button
+ onClick={this.submitComent}
+ className="commentSubmit"
+ type="button"
+ >
+ ๊ฒ์
+ </button>
+ </form>
+ </footer>
+ </article>
+ );
+ }
+}
+
+export default Feed;
|
JavaScript
|
autoComplete ์ด๊ฑฐ๋ ๋ญ๊ฐ์? ๊ถ๊ธ~
|
@@ -0,0 +1,128 @@
+@import '../../../../styles/variables.scss';
+
+article {
+ margin-bottom: 20px;
+ background-color: #fff;
+ border-radius: 3px;
+ border: 1px solid $border-color;
+
+ header {
+ @include flex-center;
+ justify-content: space-between;
+ align-content: center;
+ padding: 10px;
+
+ h1 {
+ @include flex-center;
+
+ .contentHeader {
+ @include userProfile;
+ margin-right: 10px;
+ background-image: url('http://localhost:3000/images/soojeongLee/userImage.jpg');
+ background-size: cover;
+ }
+ .userName {
+ font-size: 16px;
+ font-weight: 600;
+ }
+ }
+
+ .ellipsis {
+ @include button;
+ font-size: 22px;
+ .ellipsisIcon {
+ font-weight: 400;
+ }
+ }
+ }
+
+ .feedContent {
+ img {
+ width: 100%;
+ }
+
+ .reactionsBox {
+ @include flex-center;
+ justify-content: space-between;
+ padding: 5px 10px;
+
+ .reactionsLeft {
+ display: flex;
+
+ .leftButton {
+ @include button;
+ font-size: 22px;
+ margin-right: 10px;
+
+ .fa-external-link-alt {
+ font-size: 20px;
+ }
+ }
+ }
+
+ .reactionsRight {
+ .rightButton {
+ @include button;
+ font-size: 22px;
+ }
+ }
+ }
+
+ h2 {
+ display: flex;
+ align-items: center;
+ padding: 0 10px 10px;
+ font-size: 16px;
+ font-weight: normal;
+
+ .feedConUser {
+ @include userProfile;
+ margin-right: 5px;
+ background-image: url('http://localhost:3000/images/soojeongLee/user7.jpg');
+ background-size: cover;
+ }
+
+ .likeCount {
+ @include button;
+ margin-left: 4px;
+ font-size: 16px;
+ }
+ }
+
+ .feedText {
+ margin-bottom: 10px;
+ padding: 0 10px;
+
+ .postTime {
+ @include postTime;
+ margin-top: 5px;
+ font-size: 14px;
+ font-weight: bold;
+ }
+ }
+ }
+
+ .feedFooter {
+ background-color: #fff;
+ border-top: 1px solid $border-color;
+
+ .inputBox {
+ display: flex;
+ padding: 10px;
+
+ .comment {
+ flex: 9;
+ border: none;
+ outline: none;
+ }
+
+ .commentSubmit {
+ @include button;
+ flex: 1;
+ &:hover {
+ color: $summit-color;
+ }
+ }
+ }
+ }
+}
|
Unknown
|
์ด๋ฐ scss ๊ธฐ๋ฅ ์ ๋ ํท๊ฐ๋ ค์ ์ ๋ชปํ๊ฒ ๋๋ฐ ์ํ์๋ค์..
|
@@ -0,0 +1,23 @@
+//๋ผ์ด๋ธ๋ฌ๋ฆฌ
+import React, { Component } from 'react';
+import { Link } from 'react-router-dom';
+
+//์ปดํฌ๋ํธ
+import { FOOTLIST } from '../FootLists/footData';
+
+// css
+import './FootLists.scss';
+
+export class FootLists extends Component {
+ render() {
+ return FOOTLIST.map(footlists => {
+ return (
+ <Link to="" className="listDot" key={footlists.id}>
+ {footlists.footlist}
+ </Link>
+ );
+ });
+ }
+}
+
+export default FootLists;
|
JavaScript
|
๋๊ธ ํ๋์ค!
|
@@ -0,0 +1,46 @@
+export const FOOTLIST = [
+ {
+ id: 1,
+ footlist: '์๊ฐ',
+ },
+ {
+ id: 2,
+ footlist: '๋์๋ง',
+ },
+ {
+ id: 3,
+ footlist: 'ํ๋ณด ์ผํฐ',
+ },
+ {
+ id: 4,
+ footlist: 'API',
+ },
+ {
+ id: 5,
+ footlist: '์ฑ์ฉ ์ ๋ณด',
+ },
+ {
+ id: 6,
+ footlist: '๊ฐ์ธ์ ๋ณด์ฒ๋ฆฌ๋ฐฉ์นจ',
+ },
+ {
+ id: 7,
+ footlist: '์ฝ๊ด',
+ },
+ {
+ id: 8,
+ footlist: '์์น',
+ },
+ {
+ id: 9,
+ footlist: '์ธ๊ธฐ ๊ณ์ ',
+ },
+ {
+ id: 10,
+ footlist: 'ํด์ํ๊ทธ',
+ },
+ {
+ id: 11,
+ footlist: '์ธ์ด',
+ },
+];
|
JavaScript
|
ํ์ดํ
ํธํฐ ๋ง๋ค์ด์ ๊ฐ์ ๋ถํ๋๋ ค์
|
@@ -1,14 +1,148 @@
-// ํ์
import React from 'react';
+import { Link } from 'react-router-dom';
-// ์ปดํฌ๋ํธ
import Nav from '../../../components/Nav/Nav';
+import Feed from '../Main/Feed/Feed';
+import OtherUserPro from './OtherUserPro/OtherUserPro';
+import FootLists from '../Main/Feed/FootLists/FootLists';
+
+import './Main.scss';
class Main extends React.Component {
+ constructor() {
+ super();
+ this.state = {
+ feedList: [],
+ };
+ }
+
+ componentDidMount() {
+ fetch('/data/soojeonglee/feedData.json')
+ .then(res => res.json())
+ .then(data => {
+ this.setState({
+ feedList: data,
+ });
+ });
+ }
+
render() {
+ // console.log(this.state.feedList); // ๋ฐ์ดํฐ ํ์ธ์ ์ํ ์ฝ์
+ const { feedList } = this.state;
return (
- <div>
+ <div className="Main">
<Nav />
+ <main>
+ <div className="feeds">
+ {feedList.map(feed => {
+ return (
+ <Feed
+ key={feed.id}
+ userName={feed.userName}
+ src={feed.src}
+ feedText={feed.feedText}
+ commentData={feed.commentData}
+ isLike={feed.isLike}
+ />
+ );
+ })}
+ </div>
+ <div className="main-right">
+ <header className="userAccount">
+ <h1>
+ <Link to="" className="userProfile mainRightProfile"></Link>
+ <Link to="">
+ <strong>wecode_bootcamp</strong>
+ <span className="accountDec">WeCode - ์์ฝ๋</span>
+ </Link>
+ </h1>
+ </header>
+ <aside className="asideBox storyAside">
+ <header>
+ <h2>์คํ ๋ฆฌ</h2>
+ <button className="btnTextColor" type="button">
+ ๋ชจ๋ ๋ณด๊ธฐ
+ </button>
+ </header>
+ <ul className="storyUser">
+ <OtherUserPro />
+ </ul>
+ </aside>
+
+ <aside className="asideBox recommandAside">
+ <header>
+ <h2>ํ์๋์ ์ํ ์ถ์ฒ</h2>
+ <button className="btnTextColor" type="button">
+ ๋ชจ๋ ๋ณด๊ธฐ
+ </button>
+ </header>
+
+ <ul className="recommandUser">
+ <li className="otherUserProfile">
+ <span className="profileBox">
+ <Link to="" className="otherUserImg">
+ <img
+ alt="User Profile"
+ src="images/soojeongLee/user5.jpg"
+ />
+ </Link>
+ <Link to="">
+ limpack_official
+ <span className="followReco">ํ์๋์ ์ํ ์ถ์ฒ</span>
+ </Link>
+ </span>
+ <button className="follow" type="button">
+ ํ๋ก์ฐ
+ </button>
+ </li>
+ <li className="otherUserProfile">
+ <span className="profileBox">
+ <Link to="" className="otherUserImg">
+ <img
+ alt="User Profile"
+ src="images/soojeongLee/user6.jpg"
+ />
+ </Link>
+ <Link to="">
+ les_photos_de_cat
+ <span className="followReco">
+ geee____nie๋ ์ธ 1๋ช
์ด ํ๋ก์ฐํฉ๋๋ค.
+ </span>
+ </Link>
+ </span>
+ <button className="follow" type="button">
+ ํ๋ก์ฐ
+ </button>
+ </li>
+ <li className="otherUserProfile">
+ <span className="profileBox">
+ <Link to="" className="otherUserImg">
+ <img
+ alt="User Profile"
+ src="images/soojeongLee/user7.jpg"
+ />
+ </Link>
+ <Link to="">
+ mornstar_nail
+ <span className="followReco">
+ effie_yxz๋ ์ธ 3๋ช
์ด ํ๋ก์ฐํฉ๋๋ค
+ </span>
+ </Link>
+ </span>
+ <button className="follow" type="button">
+ ํ๋ก์ฐ
+ </button>
+ </li>
+ </ul>
+ </aside>
+ <footer className="main-right-footer">
+ <ul className="footList">
+ <FootLists />
+ </ul>
+ <span className="copyright">ยฉ 2021 INSTAGRAM FROM FACEBOOK</span>
+ </footer>
+ </div>
+ </main>
</div>
);
}
|
JavaScript
|
๋ฐ์ดํฐ ํ์ธ ๋ค ํ์
จ๋์~~?
|
@@ -1,14 +1,148 @@
-// ํ์
import React from 'react';
+import { Link } from 'react-router-dom';
-// ์ปดํฌ๋ํธ
import Nav from '../../../components/Nav/Nav';
+import Feed from '../Main/Feed/Feed';
+import OtherUserPro from './OtherUserPro/OtherUserPro';
+import FootLists from '../Main/Feed/FootLists/FootLists';
+
+import './Main.scss';
class Main extends React.Component {
+ constructor() {
+ super();
+ this.state = {
+ feedList: [],
+ };
+ }
+
+ componentDidMount() {
+ fetch('/data/soojeonglee/feedData.json')
+ .then(res => res.json())
+ .then(data => {
+ this.setState({
+ feedList: data,
+ });
+ });
+ }
+
render() {
+ // console.log(this.state.feedList); // ๋ฐ์ดํฐ ํ์ธ์ ์ํ ์ฝ์
+ const { feedList } = this.state;
return (
- <div>
+ <div className="Main">
<Nav />
+ <main>
+ <div className="feeds">
+ {feedList.map(feed => {
+ return (
+ <Feed
+ key={feed.id}
+ userName={feed.userName}
+ src={feed.src}
+ feedText={feed.feedText}
+ commentData={feed.commentData}
+ isLike={feed.isLike}
+ />
+ );
+ })}
+ </div>
+ <div className="main-right">
+ <header className="userAccount">
+ <h1>
+ <Link to="" className="userProfile mainRightProfile"></Link>
+ <Link to="">
+ <strong>wecode_bootcamp</strong>
+ <span className="accountDec">WeCode - ์์ฝ๋</span>
+ </Link>
+ </h1>
+ </header>
+ <aside className="asideBox storyAside">
+ <header>
+ <h2>์คํ ๋ฆฌ</h2>
+ <button className="btnTextColor" type="button">
+ ๋ชจ๋ ๋ณด๊ธฐ
+ </button>
+ </header>
+ <ul className="storyUser">
+ <OtherUserPro />
+ </ul>
+ </aside>
+
+ <aside className="asideBox recommandAside">
+ <header>
+ <h2>ํ์๋์ ์ํ ์ถ์ฒ</h2>
+ <button className="btnTextColor" type="button">
+ ๋ชจ๋ ๋ณด๊ธฐ
+ </button>
+ </header>
+
+ <ul className="recommandUser">
+ <li className="otherUserProfile">
+ <span className="profileBox">
+ <Link to="" className="otherUserImg">
+ <img
+ alt="User Profile"
+ src="images/soojeongLee/user5.jpg"
+ />
+ </Link>
+ <Link to="">
+ limpack_official
+ <span className="followReco">ํ์๋์ ์ํ ์ถ์ฒ</span>
+ </Link>
+ </span>
+ <button className="follow" type="button">
+ ํ๋ก์ฐ
+ </button>
+ </li>
+ <li className="otherUserProfile">
+ <span className="profileBox">
+ <Link to="" className="otherUserImg">
+ <img
+ alt="User Profile"
+ src="images/soojeongLee/user6.jpg"
+ />
+ </Link>
+ <Link to="">
+ les_photos_de_cat
+ <span className="followReco">
+ geee____nie๋ ์ธ 1๋ช
์ด ํ๋ก์ฐํฉ๋๋ค.
+ </span>
+ </Link>
+ </span>
+ <button className="follow" type="button">
+ ํ๋ก์ฐ
+ </button>
+ </li>
+ <li className="otherUserProfile">
+ <span className="profileBox">
+ <Link to="" className="otherUserImg">
+ <img
+ alt="User Profile"
+ src="images/soojeongLee/user7.jpg"
+ />
+ </Link>
+ <Link to="">
+ mornstar_nail
+ <span className="followReco">
+ effie_yxz๋ ์ธ 3๋ช
์ด ํ๋ก์ฐํฉ๋๋ค
+ </span>
+ </Link>
+ </span>
+ <button className="follow" type="button">
+ ํ๋ก์ฐ
+ </button>
+ </li>
+ </ul>
+ </aside>
+ <footer className="main-right-footer">
+ <ul className="footList">
+ <FootLists />
+ </ul>
+ <span className="copyright">ยฉ 2021 INSTAGRAM FROM FACEBOOK</span>
+ </footer>
+ </div>
+ </main>
</div>
);
}
|
JavaScript
|
ํผ์ด ๋ฆฌ๋ทฐ ์ค Return์ ๋น๋ฐ์? ๊ฐ์ฌํฉ๋๋ค.
|
@@ -1,8 +1,79 @@
import React, { Component } from 'react';
+import { Link } from 'react-router-dom';
+
+import './Login.scss';
class Login extends Component {
+ constructor() {
+ super();
+ this.state = {
+ id: '',
+ pw: '',
+ };
+ }
+
+ handleInput = event => {
+ const { name, value } = event.target;
+ this.setState({
+ [name]: value,
+ });
+ };
+
+ goToMain = () => {
+ this.props.history.push('/main-Soojeong#');
+ };
+
render() {
- return <div>๋ก๊ทธ์ธ</div>;
+ const isValid =
+ this.state.id.includes('@') &&
+ this.state.id.length >= 5 &&
+ this.state.pw.length >= 8;
+
+ return (
+ <div className="Login">
+ <main>
+ <header>
+ <h1>Westagram</h1>
+ </header>
+
+ <section className="loginInputBox">
+ <h2 className="sr-only">login page</h2>
+ <form>
+ <input
+ name="id"
+ autoComplete="off"
+ onChange={this.handleInput}
+ type="text"
+ id="loginId"
+ value={this.state.id}
+ placeholder="์ ํ๋ฒํธ, ์ฌ์ฉ์ ์ด๋ฆ ๋๋ ์ด๋ฉ์ผ"
+ />
+ <input
+ name="pw"
+ onChange={this.handleInput}
+ type="password"
+ value={this.state.pw}
+ placeholder="๋น๋ฐ๋ฒํธ"
+ />
+ <button
+ onClick={this.goToMain}
+ type="button"
+ className="loginBtn"
+ disabled={!isValid}
+ >
+ ๋ก๊ทธ์ธ
+ </button>
+ </form>
+ </section>
+
+ <footer>
+ <Link to="" className="findPassword">
+ ๋น๋ฐ๋ฒํธ๋ฅผ ์์ผ์
จ๋์?
+ </Link>
+ </footer>
+ </main>
+ </div>
+ );
}
}
|
JavaScript
|
Boolean ๋ฐ์ดํฐ ํ์
์ ์ฉ์์ผ๋ณด์์์. ์ ์ธ์ ๋ ์ฝ๋๊ฐ ์๋๋์ง ์์๊น ์๋ํ๊ธฐ ์ด๋ ค์ ๋๋ฐ ๊ฒฉ๋ ค ๊ฐ์ฌํฉ๋๋น~
|
@@ -0,0 +1,61 @@
+.Login {
+ display: flex;
+ justify-content: center;
+ align-items: center;
+ height: 100vh;
+
+ main {
+ display: flex;
+ flex-direction: column;
+ justify-content: space-around;
+ width: 350px;
+ height: 380px;
+ padding: 40px;
+ border: 1px solid #ccc;
+
+ header {
+ h1 {
+ font-family: 'Lobster', cursive;
+ text-align: center;
+ }
+ }
+
+ .loginInputBox {
+ form {
+ display: flex;
+ flex-direction: column;
+ justify-content: center;
+
+ input {
+ margin-bottom: 5px;
+ padding: 9px 8px 7px;
+ background-color: rgb(250, 250, 250);
+ border: 1px solid rgb(38, 38, 38);
+ border-radius: 3px;
+ }
+
+ .loginBtn {
+ margin-top: 10px;
+ padding: 9px 8px 7px;
+ border: none;
+ border-radius: 3px;
+ color: #fff;
+ background-color: #0096f6;
+ &:disabled {
+ background-color: #c0dffd;
+ }
+ }
+ }
+ }
+
+ footer {
+ .findPassword {
+ display: block;
+ margin-top: 50px;
+ text-align: center;
+ color: #00376b;
+ font-size: 14px;
+ }
+ }
+ }
+}
|
Unknown
|
๊ธฐ์กด html ์ฝ๋๋ฅผ ์ฎ๊ธฐ๋ค ๋ณด๋ ๋ฐ์ํ ๋ฌธ์ ์์ด์ :) ํด๊ฒฐ๋์๋ต๋๋น !!
|
@@ -0,0 +1,134 @@
+[
+ {
+ "id": 1,
+ "userName": "eessoo__",
+ "src": "../images/soojeongLee/user2.jpg",
+ "feedText": "๐",
+ "commentData": [
+ {
+ "id": 1,
+ "userName": "wecode",
+ "content": "Welcome to world best coding bootcamp!",
+ "commnetLike": false
+ },
+ {
+ "id": 2,
+ "userName": "soojeonglee",
+ "content": "Hi there.",
+ "commnetLike": false
+ },
+ {
+ "id": 3,
+ "userName": "jaehyunlee",
+ "content": "Hey.",
+ "commnetLike": false
+ },
+ {
+ "id": 4,
+ "userName": "gyeongminlee",
+ "content": "Hi.",
+ "commnetLike": true
+ }
+ ],
+ "isLike": false
+ },
+ {
+ "id": 2,
+ "userName": "zz_ing94",
+ "src": "../../images/soojeongLee/user3.jpg",
+ "feedText": "Toy story ๐",
+ "commentData": [
+ {
+ "id": 1,
+ "userName": "wecode",
+ "content": "Welcome to world best coding bootcamp!",
+ "commnetLike": false
+ },
+ {
+ "id": 2,
+ "userName": "jisuoh",
+ "content": "โจ",
+ "commnetLike": true
+ },
+ {
+ "id": 3,
+ "userName": "jungjunsung",
+ "content": "coffee",
+ "commnetLike": false
+ },
+ {
+ "id": 4,
+ "userName": "somihwang",
+ "content": "ํฌํค",
+ "commnetLike": true
+ }
+ ],
+ "isLike": false
+ },
+ {
+ "id": 3,
+ "userName": "hwayoonci",
+ "src": "../../images/soojeongLee/user4.jpg",
+ "feedText": "์ค๋์ ์ผ๊ธฐ",
+ "commentData": [
+ {
+ "id": 1,
+ "userName": "wecode",
+ "content": "Welcome to world best coding bootcamp!",
+ "commnetLike": false
+ },
+ {
+ "id": 2,
+ "userName": "yunkyunglee",
+ "content": "๊ท์ฌ์ด ์คํฐ์ปค",
+ "commnetLike": true
+ },
+ {
+ "id": 3,
+ "userName": "summer",
+ "content": "๐ถ",
+ "commnetLike": false
+ },
+ {
+ "id": 4,
+ "userName": "uiyeonlee",
+ "content": "๐๐ป",
+ "commnetLike": true
+ }
+ ],
+ "isLike": true
+ },
+ {
+ "id": 4,
+ "userName": "cosz_zy",
+ "src": "../../images/soojeongLee/user5.jpg",
+ "feedText": "1์ผ ํ๊ฐ ๐จ ",
+ "commentData": [
+ {
+ "id": 1,
+ "userName": "wecode",
+ "content": "Welcome to world best coding bootcamp!",
+ "commnetLike": false
+ },
+ {
+ "id": 2,
+ "userName": "soojeonglee",
+ "content": "Hi there.",
+ "commnetLike": false
+ },
+ {
+ "id": 3,
+ "userName": "jaehyunlee",
+ "content": "Hey.",
+ "commnetLike": true
+ },
+ {
+ "id": 4,
+ "userName": "gyeongminlee",
+ "content": "Hi.",
+ "commnetLike": true
+ }
+ ],
+ "isLike": false
+ }
+]
|
Unknown
|
fetching ์ ์ฐ์ตํด๋ณด๋ ค๊ณ ๋ง๋ค์ด๋ณด์์ด์
|
@@ -0,0 +1,175 @@
+import React, { Component } from 'react';
+import { Link } from 'react-router-dom';
+
+import Comment from './Comment/Comment';
+
+import '../Feed/Feed.scss';
+
+export class Feed extends Component {
+ constructor() {
+ super();
+ this.state = {
+ comment: '',
+ // commentList: [],
+ // isLike: false,
+ };
+ }
+
+ // componentDidMount() {
+ // this.setState({
+ // commentList: this.props.commentData,
+ // isLike: this.props.isLike,
+ // });
+ // }
+
+ hadComment = event => {
+ this.setState({
+ comment: event.target.value,
+ });
+ };
+
+ // ํด๋ฆญํจ์
+ submitComent = () => {
+ // this.setState({
+ // commentList: this.state.commentList.concat([
+ // {
+ // id: this.state.commentList.length + 1,
+ // userName: 'eessoo__',
+ // content: this.state.comment,
+ // commentLike: false,
+ // },
+ // ]),
+ // comment: '',
+ // });
+ };
+
+ handleKeyPress = event => {
+ if (event.key === 'Enter') {
+ event.preventDefault();
+ this.submitComent();
+ }
+ };
+
+ handleLike = () => {
+ this.setState({
+ isLike: !this.state.isLike,
+ });
+ };
+
+ // ์ถ๊ฐ ๊ธฐ๋ฅ ๊ตฌํ ์ค
+ // handleCommnetDelete = id => {
+ // const newCommentList = this.state.commentList.filter(comment => {
+ // return comment.id !== id;
+ // });
+
+ // this.setState({
+ // commentList: newCommentList,
+ // });
+ // };
+
+ render() {
+ return (
+ <article>
+ <header>
+ <h1>
+ <Link className="contentHeader"></Link>
+ <Link className="userName">{this.props.userName}</Link>
+ </h1>
+ <button className="ellipsis" type="button">
+ <i className="fas fa-ellipsis-h ellipsisIcon"></i>
+ </button>
+ </header>
+ <section className="feedContent">
+ <img alt="feedImage" src={this.props.src} />
+ <ul className="reactionsBox">
+ <li className="reactionsLeft">
+ <button
+ className="leftButton"
+ type="button"
+ onClick={this.handleLike}
+ >
+ {this.state.isLike ? (
+ <i className="fas fa-heart" />
+ ) : (
+ <i className="far fa-heart" />
+ )}
+ </button>
+ <button className="leftButton" type="button">
+ <i className="far fa-comment" />
+ </button>
+ <button className="leftButton" type="button">
+ <i className="fas fa-external-link-alt" />
+ </button>
+ </li>
+ <li className="reactionsRight">
+ <button className="rightButton">
+ <i className="far fa-bookmark" />
+ </button>
+ </li>
+ </ul>
+ <h2>
+ <Link className="userProfile feedConUser"></Link>
+ <b>eessoo__</b>๋ ์ธ
+ <button className="likeCount">
+ <b> 7๋ช
</b>
+ </button>
+ ์ด ์ข์ํฉ๋๋ค.
+ </h2>
+ <p className="feedText">
+ {this.props.feedText}
+ <span className="postTime">54๋ถ ์ </span>
+ </p>
+ <ul id="commnetBox">
+ {/* {this.state.commentList.map(comment => {
+ return (
+ <Comment
+ key={comment.id}
+ userName={comment.userName}
+ content={comment.content}
+ commnetLike={comment.commnetLike}
+ // ์ถ๊ฐ ๊ธฐ๋ฅ ๊ตฌํ ์ค
+ // handleCommnetDelete={this.handleCommnetDelete}
+ // id={comment.id}
+ />
+ );
+ })} */}
+ {this.props.commentData.map(comment => {
+ return (
+ <Comment
+ key={comment.id}
+ userName={comment.userName}
+ content={comment.content}
+ commnetLike={comment.commnetLike}
+ // ์ถ๊ฐ ๊ธฐ๋ฅ ๊ตฌํ ์ค
+ // handleCommnetDelete={this.handleCommnetDelete}
+ // id={comment.id}
+ />
+ );
+ })}
+ </ul>
+ </section>
+ <footer className="feedFooter">
+ <form className="inputBox" onKeyPress={this.handleKeyPress}>
+ <input
+ autoComplete="off"
+ onChange={this.hadComment}
+ className="comment"
+ value={this.state.comment}
+ type="text"
+ placeholder="๋๊ธ ๋ฌ๊ธฐ..."
+ />
+ <button
+ onClick={this.submitComent}
+ className="commentSubmit"
+ type="button"
+ >
+ ๊ฒ์
+ </button>
+ </form>
+ </footer>
+ </article>
+ );
+ }
+}
+
+export default Feed;
|
JavaScript
|
์ธ์คํ๊ทธ๋จ์์ ์ค์ ์ข์์๋ฅผ ์ข์ํ ์ซ์์ ์ ๊ทผํ๊ฒ ๋๋ฉด ๋๊ฐ ์ข์์๋ฅผ ๋๋ ๋์ง ๋ชฉ๋ก์ ๋ณผ ์ ์์ด์, ์ถํ์ ๊ธฐ๋ฅ์ ๋ฃ๊ฒ ๋๋ค๋ฉด button์ ๋ฃ์ด์ผ ํ์ง ์์๊น ์๊ฐ์ด ๋ค์ด์ ๋ฃ์ด๋ดค์ต๋๋ค.
|
@@ -0,0 +1,23 @@
+//๋ผ์ด๋ธ๋ฌ๋ฆฌ
+import React, { Component } from 'react';
+import { Link } from 'react-router-dom';
+
+//์ปดํฌ๋ํธ
+import { FOOTLIST } from '../FootLists/footData';
+
+// css
+import './FootLists.scss';
+
+export class FootLists extends Component {
+ render() {
+ return FOOTLIST.map(footlists => {
+ return (
+ <Link to="" className="listDot" key={footlists.id}>
+ {footlists.footlist}
+ </Link>
+ );
+ });
+ }
+}
+
+export default FootLists;
|
JavaScript
|
๊ผญ ํ ๋ฆฌ์คํธ๋ฅผ... ์ปดํฌ๋ํธํํด๋ณด๊ฒ ์ด์...!!!!
|
@@ -1,14 +1,148 @@
-// ํ์
import React from 'react';
+import { Link } from 'react-router-dom';
-// ์ปดํฌ๋ํธ
import Nav from '../../../components/Nav/Nav';
+import Feed from '../Main/Feed/Feed';
+import OtherUserPro from './OtherUserPro/OtherUserPro';
+import FootLists from '../Main/Feed/FootLists/FootLists';
+
+import './Main.scss';
class Main extends React.Component {
+ constructor() {
+ super();
+ this.state = {
+ feedList: [],
+ };
+ }
+
+ componentDidMount() {
+ fetch('/data/soojeonglee/feedData.json')
+ .then(res => res.json())
+ .then(data => {
+ this.setState({
+ feedList: data,
+ });
+ });
+ }
+
render() {
+ // console.log(this.state.feedList); // ๋ฐ์ดํฐ ํ์ธ์ ์ํ ์ฝ์
+ const { feedList } = this.state;
return (
- <div>
+ <div className="Main">
<Nav />
+ <main>
+ <div className="feeds">
+ {feedList.map(feed => {
+ return (
+ <Feed
+ key={feed.id}
+ userName={feed.userName}
+ src={feed.src}
+ feedText={feed.feedText}
+ commentData={feed.commentData}
+ isLike={feed.isLike}
+ />
+ );
+ })}
+ </div>
+ <div className="main-right">
+ <header className="userAccount">
+ <h1>
+ <Link to="" className="userProfile mainRightProfile"></Link>
+ <Link to="">
+ <strong>wecode_bootcamp</strong>
+ <span className="accountDec">WeCode - ์์ฝ๋</span>
+ </Link>
+ </h1>
+ </header>
+ <aside className="asideBox storyAside">
+ <header>
+ <h2>์คํ ๋ฆฌ</h2>
+ <button className="btnTextColor" type="button">
+ ๋ชจ๋ ๋ณด๊ธฐ
+ </button>
+ </header>
+ <ul className="storyUser">
+ <OtherUserPro />
+ </ul>
+ </aside>
+
+ <aside className="asideBox recommandAside">
+ <header>
+ <h2>ํ์๋์ ์ํ ์ถ์ฒ</h2>
+ <button className="btnTextColor" type="button">
+ ๋ชจ๋ ๋ณด๊ธฐ
+ </button>
+ </header>
+
+ <ul className="recommandUser">
+ <li className="otherUserProfile">
+ <span className="profileBox">
+ <Link to="" className="otherUserImg">
+ <img
+ alt="User Profile"
+ src="images/soojeongLee/user5.jpg"
+ />
+ </Link>
+ <Link to="">
+ limpack_official
+ <span className="followReco">ํ์๋์ ์ํ ์ถ์ฒ</span>
+ </Link>
+ </span>
+ <button className="follow" type="button">
+ ํ๋ก์ฐ
+ </button>
+ </li>
+ <li className="otherUserProfile">
+ <span className="profileBox">
+ <Link to="" className="otherUserImg">
+ <img
+ alt="User Profile"
+ src="images/soojeongLee/user6.jpg"
+ />
+ </Link>
+ <Link to="">
+ les_photos_de_cat
+ <span className="followReco">
+ geee____nie๋ ์ธ 1๋ช
์ด ํ๋ก์ฐํฉ๋๋ค.
+ </span>
+ </Link>
+ </span>
+ <button className="follow" type="button">
+ ํ๋ก์ฐ
+ </button>
+ </li>
+ <li className="otherUserProfile">
+ <span className="profileBox">
+ <Link to="" className="otherUserImg">
+ <img
+ alt="User Profile"
+ src="images/soojeongLee/user7.jpg"
+ />
+ </Link>
+ <Link to="">
+ mornstar_nail
+ <span className="followReco">
+ effie_yxz๋ ์ธ 3๋ช
์ด ํ๋ก์ฐํฉ๋๋ค
+ </span>
+ </Link>
+ </span>
+ <button className="follow" type="button">
+ ํ๋ก์ฐ
+ </button>
+ </li>
+ </ul>
+ </aside>
+ <footer className="main-right-footer">
+ <ul className="footList">
+ <FootLists />
+ </ul>
+ <span className="copyright">ยฉ 2021 INSTAGRAM FROM FACEBOOK</span>
+ </footer>
+ </div>
+ </main>
</div>
);
}
|
JavaScript
|
๋ค..! ๋ฌด์์ด ์ด๋์ ์ ๋ฌ๋์๋์ง ํ์ธํ๊ธฐ๊ฐ ์ด๋ ค์์ ๋ฃ์ด๋์ด์ ...!
|
@@ -1,14 +1,148 @@
-// ํ์
import React from 'react';
+import { Link } from 'react-router-dom';
-// ์ปดํฌ๋ํธ
import Nav from '../../../components/Nav/Nav';
+import Feed from '../Main/Feed/Feed';
+import OtherUserPro from './OtherUserPro/OtherUserPro';
+import FootLists from '../Main/Feed/FootLists/FootLists';
+
+import './Main.scss';
class Main extends React.Component {
+ constructor() {
+ super();
+ this.state = {
+ feedList: [],
+ };
+ }
+
+ componentDidMount() {
+ fetch('/data/soojeonglee/feedData.json')
+ .then(res => res.json())
+ .then(data => {
+ this.setState({
+ feedList: data,
+ });
+ });
+ }
+
render() {
+ // console.log(this.state.feedList); // ๋ฐ์ดํฐ ํ์ธ์ ์ํ ์ฝ์
+ const { feedList } = this.state;
return (
- <div>
+ <div className="Main">
<Nav />
+ <main>
+ <div className="feeds">
+ {feedList.map(feed => {
+ return (
+ <Feed
+ key={feed.id}
+ userName={feed.userName}
+ src={feed.src}
+ feedText={feed.feedText}
+ commentData={feed.commentData}
+ isLike={feed.isLike}
+ />
+ );
+ })}
+ </div>
+ <div className="main-right">
+ <header className="userAccount">
+ <h1>
+ <Link to="" className="userProfile mainRightProfile"></Link>
+ <Link to="">
+ <strong>wecode_bootcamp</strong>
+ <span className="accountDec">WeCode - ์์ฝ๋</span>
+ </Link>
+ </h1>
+ </header>
+ <aside className="asideBox storyAside">
+ <header>
+ <h2>์คํ ๋ฆฌ</h2>
+ <button className="btnTextColor" type="button">
+ ๋ชจ๋ ๋ณด๊ธฐ
+ </button>
+ </header>
+ <ul className="storyUser">
+ <OtherUserPro />
+ </ul>
+ </aside>
+
+ <aside className="asideBox recommandAside">
+ <header>
+ <h2>ํ์๋์ ์ํ ์ถ์ฒ</h2>
+ <button className="btnTextColor" type="button">
+ ๋ชจ๋ ๋ณด๊ธฐ
+ </button>
+ </header>
+
+ <ul className="recommandUser">
+ <li className="otherUserProfile">
+ <span className="profileBox">
+ <Link to="" className="otherUserImg">
+ <img
+ alt="User Profile"
+ src="images/soojeongLee/user5.jpg"
+ />
+ </Link>
+ <Link to="">
+ limpack_official
+ <span className="followReco">ํ์๋์ ์ํ ์ถ์ฒ</span>
+ </Link>
+ </span>
+ <button className="follow" type="button">
+ ํ๋ก์ฐ
+ </button>
+ </li>
+ <li className="otherUserProfile">
+ <span className="profileBox">
+ <Link to="" className="otherUserImg">
+ <img
+ alt="User Profile"
+ src="images/soojeongLee/user6.jpg"
+ />
+ </Link>
+ <Link to="">
+ les_photos_de_cat
+ <span className="followReco">
+ geee____nie๋ ์ธ 1๋ช
์ด ํ๋ก์ฐํฉ๋๋ค.
+ </span>
+ </Link>
+ </span>
+ <button className="follow" type="button">
+ ํ๋ก์ฐ
+ </button>
+ </li>
+ <li className="otherUserProfile">
+ <span className="profileBox">
+ <Link to="" className="otherUserImg">
+ <img
+ alt="User Profile"
+ src="images/soojeongLee/user7.jpg"
+ />
+ </Link>
+ <Link to="">
+ mornstar_nail
+ <span className="followReco">
+ effie_yxz๋ ์ธ 3๋ช
์ด ํ๋ก์ฐํฉ๋๋ค
+ </span>
+ </Link>
+ </span>
+ <button className="follow" type="button">
+ ํ๋ก์ฐ
+ </button>
+ </li>
+ </ul>
+ </aside>
+ <footer className="main-right-footer">
+ <ul className="footList">
+ <FootLists />
+ </ul>
+ <span className="copyright">ยฉ 2021 INSTAGRAM FROM FACEBOOK</span>
+ </footer>
+ </div>
+ </main>
</div>
);
}
|
JavaScript
|
ใ
ใ
ใ
Return ์ ์๋ต๋ ์ ์๋ค ~
|
@@ -1,8 +1,79 @@
import React, { Component } from 'react';
+import { Link } from 'react-router-dom';
+
+import './Login.scss';
class Login extends Component {
+ constructor() {
+ super();
+ this.state = {
+ id: '',
+ pw: '',
+ };
+ }
+
+ handleInput = event => {
+ const { name, value } = event.target;
+ this.setState({
+ [name]: value,
+ });
+ };
+
+ goToMain = () => {
+ this.props.history.push('/main-Soojeong#');
+ };
+
render() {
- return <div>๋ก๊ทธ์ธ</div>;
+ const isValid =
+ this.state.id.includes('@') &&
+ this.state.id.length >= 5 &&
+ this.state.pw.length >= 8;
+
+ return (
+ <div className="Login">
+ <main>
+ <header>
+ <h1>Westagram</h1>
+ </header>
+
+ <section className="loginInputBox">
+ <h2 className="sr-only">login page</h2>
+ <form>
+ <input
+ name="id"
+ autoComplete="off"
+ onChange={this.handleInput}
+ type="text"
+ id="loginId"
+ value={this.state.id}
+ placeholder="์ ํ๋ฒํธ, ์ฌ์ฉ์ ์ด๋ฆ ๋๋ ์ด๋ฉ์ผ"
+ />
+ <input
+ name="pw"
+ onChange={this.handleInput}
+ type="password"
+ value={this.state.pw}
+ placeholder="๋น๋ฐ๋ฒํธ"
+ />
+ <button
+ onClick={this.goToMain}
+ type="button"
+ className="loginBtn"
+ disabled={!isValid}
+ >
+ ๋ก๊ทธ์ธ
+ </button>
+ </form>
+ </section>
+
+ <footer>
+ <Link to="" className="findPassword">
+ ๋น๋ฐ๋ฒํธ๋ฅผ ์์ผ์
จ๋์?
+ </Link>
+ </footer>
+ </main>
+ </div>
+ );
}
}
|
JavaScript
|
๊ณ์ฐ๋์์ฑ๋ช
๊ตฟ
|
@@ -0,0 +1,175 @@
+import React, { Component } from 'react';
+import { Link } from 'react-router-dom';
+
+import Comment from './Comment/Comment';
+
+import '../Feed/Feed.scss';
+
+export class Feed extends Component {
+ constructor() {
+ super();
+ this.state = {
+ comment: '',
+ // commentList: [],
+ // isLike: false,
+ };
+ }
+
+ // componentDidMount() {
+ // this.setState({
+ // commentList: this.props.commentData,
+ // isLike: this.props.isLike,
+ // });
+ // }
+
+ hadComment = event => {
+ this.setState({
+ comment: event.target.value,
+ });
+ };
+
+ // ํด๋ฆญํจ์
+ submitComent = () => {
+ // this.setState({
+ // commentList: this.state.commentList.concat([
+ // {
+ // id: this.state.commentList.length + 1,
+ // userName: 'eessoo__',
+ // content: this.state.comment,
+ // commentLike: false,
+ // },
+ // ]),
+ // comment: '',
+ // });
+ };
+
+ handleKeyPress = event => {
+ if (event.key === 'Enter') {
+ event.preventDefault();
+ this.submitComent();
+ }
+ };
+
+ handleLike = () => {
+ this.setState({
+ isLike: !this.state.isLike,
+ });
+ };
+
+ // ์ถ๊ฐ ๊ธฐ๋ฅ ๊ตฌํ ์ค
+ // handleCommnetDelete = id => {
+ // const newCommentList = this.state.commentList.filter(comment => {
+ // return comment.id !== id;
+ // });
+
+ // this.setState({
+ // commentList: newCommentList,
+ // });
+ // };
+
+ render() {
+ return (
+ <article>
+ <header>
+ <h1>
+ <Link className="contentHeader"></Link>
+ <Link className="userName">{this.props.userName}</Link>
+ </h1>
+ <button className="ellipsis" type="button">
+ <i className="fas fa-ellipsis-h ellipsisIcon"></i>
+ </button>
+ </header>
+ <section className="feedContent">
+ <img alt="feedImage" src={this.props.src} />
+ <ul className="reactionsBox">
+ <li className="reactionsLeft">
+ <button
+ className="leftButton"
+ type="button"
+ onClick={this.handleLike}
+ >
+ {this.state.isLike ? (
+ <i className="fas fa-heart" />
+ ) : (
+ <i className="far fa-heart" />
+ )}
+ </button>
+ <button className="leftButton" type="button">
+ <i className="far fa-comment" />
+ </button>
+ <button className="leftButton" type="button">
+ <i className="fas fa-external-link-alt" />
+ </button>
+ </li>
+ <li className="reactionsRight">
+ <button className="rightButton">
+ <i className="far fa-bookmark" />
+ </button>
+ </li>
+ </ul>
+ <h2>
+ <Link className="userProfile feedConUser"></Link>
+ <b>eessoo__</b>๋ ์ธ
+ <button className="likeCount">
+ <b> 7๋ช
</b>
+ </button>
+ ์ด ์ข์ํฉ๋๋ค.
+ </h2>
+ <p className="feedText">
+ {this.props.feedText}
+ <span className="postTime">54๋ถ ์ </span>
+ </p>
+ <ul id="commnetBox">
+ {/* {this.state.commentList.map(comment => {
+ return (
+ <Comment
+ key={comment.id}
+ userName={comment.userName}
+ content={comment.content}
+ commnetLike={comment.commnetLike}
+ // ์ถ๊ฐ ๊ธฐ๋ฅ ๊ตฌํ ์ค
+ // handleCommnetDelete={this.handleCommnetDelete}
+ // id={comment.id}
+ />
+ );
+ })} */}
+ {this.props.commentData.map(comment => {
+ return (
+ <Comment
+ key={comment.id}
+ userName={comment.userName}
+ content={comment.content}
+ commnetLike={comment.commnetLike}
+ // ์ถ๊ฐ ๊ธฐ๋ฅ ๊ตฌํ ์ค
+ // handleCommnetDelete={this.handleCommnetDelete}
+ // id={comment.id}
+ />
+ );
+ })}
+ </ul>
+ </section>
+ <footer className="feedFooter">
+ <form className="inputBox" onKeyPress={this.handleKeyPress}>
+ <input
+ autoComplete="off"
+ onChange={this.hadComment}
+ className="comment"
+ value={this.state.comment}
+ type="text"
+ placeholder="๋๊ธ ๋ฌ๊ธฐ..."
+ />
+ <button
+ onClick={this.submitComent}
+ className="commentSubmit"
+ type="button"
+ >
+ ๊ฒ์
+ </button>
+ </form>
+ </footer>
+ </article>
+ );
+ }
+}
+
+export default Feed;
|
JavaScript
|
์ค....
|
@@ -0,0 +1,175 @@
+import React, { Component } from 'react';
+import { Link } from 'react-router-dom';
+
+import Comment from './Comment/Comment';
+
+import '../Feed/Feed.scss';
+
+export class Feed extends Component {
+ constructor() {
+ super();
+ this.state = {
+ comment: '',
+ // commentList: [],
+ // isLike: false,
+ };
+ }
+
+ // componentDidMount() {
+ // this.setState({
+ // commentList: this.props.commentData,
+ // isLike: this.props.isLike,
+ // });
+ // }
+
+ hadComment = event => {
+ this.setState({
+ comment: event.target.value,
+ });
+ };
+
+ // ํด๋ฆญํจ์
+ submitComent = () => {
+ // this.setState({
+ // commentList: this.state.commentList.concat([
+ // {
+ // id: this.state.commentList.length + 1,
+ // userName: 'eessoo__',
+ // content: this.state.comment,
+ // commentLike: false,
+ // },
+ // ]),
+ // comment: '',
+ // });
+ };
+
+ handleKeyPress = event => {
+ if (event.key === 'Enter') {
+ event.preventDefault();
+ this.submitComent();
+ }
+ };
+
+ handleLike = () => {
+ this.setState({
+ isLike: !this.state.isLike,
+ });
+ };
+
+ // ์ถ๊ฐ ๊ธฐ๋ฅ ๊ตฌํ ์ค
+ // handleCommnetDelete = id => {
+ // const newCommentList = this.state.commentList.filter(comment => {
+ // return comment.id !== id;
+ // });
+
+ // this.setState({
+ // commentList: newCommentList,
+ // });
+ // };
+
+ render() {
+ return (
+ <article>
+ <header>
+ <h1>
+ <Link className="contentHeader"></Link>
+ <Link className="userName">{this.props.userName}</Link>
+ </h1>
+ <button className="ellipsis" type="button">
+ <i className="fas fa-ellipsis-h ellipsisIcon"></i>
+ </button>
+ </header>
+ <section className="feedContent">
+ <img alt="feedImage" src={this.props.src} />
+ <ul className="reactionsBox">
+ <li className="reactionsLeft">
+ <button
+ className="leftButton"
+ type="button"
+ onClick={this.handleLike}
+ >
+ {this.state.isLike ? (
+ <i className="fas fa-heart" />
+ ) : (
+ <i className="far fa-heart" />
+ )}
+ </button>
+ <button className="leftButton" type="button">
+ <i className="far fa-comment" />
+ </button>
+ <button className="leftButton" type="button">
+ <i className="fas fa-external-link-alt" />
+ </button>
+ </li>
+ <li className="reactionsRight">
+ <button className="rightButton">
+ <i className="far fa-bookmark" />
+ </button>
+ </li>
+ </ul>
+ <h2>
+ <Link className="userProfile feedConUser"></Link>
+ <b>eessoo__</b>๋ ์ธ
+ <button className="likeCount">
+ <b> 7๋ช
</b>
+ </button>
+ ์ด ์ข์ํฉ๋๋ค.
+ </h2>
+ <p className="feedText">
+ {this.props.feedText}
+ <span className="postTime">54๋ถ ์ </span>
+ </p>
+ <ul id="commnetBox">
+ {/* {this.state.commentList.map(comment => {
+ return (
+ <Comment
+ key={comment.id}
+ userName={comment.userName}
+ content={comment.content}
+ commnetLike={comment.commnetLike}
+ // ์ถ๊ฐ ๊ธฐ๋ฅ ๊ตฌํ ์ค
+ // handleCommnetDelete={this.handleCommnetDelete}
+ // id={comment.id}
+ />
+ );
+ })} */}
+ {this.props.commentData.map(comment => {
+ return (
+ <Comment
+ key={comment.id}
+ userName={comment.userName}
+ content={comment.content}
+ commnetLike={comment.commnetLike}
+ // ์ถ๊ฐ ๊ธฐ๋ฅ ๊ตฌํ ์ค
+ // handleCommnetDelete={this.handleCommnetDelete}
+ // id={comment.id}
+ />
+ );
+ })}
+ </ul>
+ </section>
+ <footer className="feedFooter">
+ <form className="inputBox" onKeyPress={this.handleKeyPress}>
+ <input
+ autoComplete="off"
+ onChange={this.hadComment}
+ className="comment"
+ value={this.state.comment}
+ type="text"
+ placeholder="๋๊ธ ๋ฌ๊ธฐ..."
+ />
+ <button
+ onClick={this.submitComent}
+ className="commentSubmit"
+ type="button"
+ >
+ ๊ฒ์
+ </button>
+ </form>
+ </footer>
+ </article>
+ );
+ }
+}
+
+export default Feed;
|
JavaScript
|
์ด๋ฐ๋ฐฉ๋ฒ์ด.. ํผ๋๋ง๋ค ๋๊ธ ๋ฐ์ดํฐ๋ฅผ ์คํ
์ดํธ๋ก ํฌํจํ๊ฒ ํด์ฃผ๋ ๋ณด๊ธฐ ์ฝ๊ณ ์ข๋ค์
|
@@ -1,8 +1,79 @@
import React, { Component } from 'react';
+import { Link } from 'react-router-dom';
+
+import './Login.scss';
class Login extends Component {
+ constructor() {
+ super();
+ this.state = {
+ id: '',
+ pw: '',
+ };
+ }
+
+ handleInput = event => {
+ const { name, value } = event.target;
+ this.setState({
+ [name]: value,
+ });
+ };
+
+ goToMain = () => {
+ this.props.history.push('/main-Soojeong#');
+ };
+
render() {
- return <div>๋ก๊ทธ์ธ</div>;
+ const isValid =
+ this.state.id.includes('@') &&
+ this.state.id.length >= 5 &&
+ this.state.pw.length >= 8;
+
+ return (
+ <div className="Login">
+ <main>
+ <header>
+ <h1>Westagram</h1>
+ </header>
+
+ <section className="loginInputBox">
+ <h2 className="sr-only">login page</h2>
+ <form>
+ <input
+ name="id"
+ autoComplete="off"
+ onChange={this.handleInput}
+ type="text"
+ id="loginId"
+ value={this.state.id}
+ placeholder="์ ํ๋ฒํธ, ์ฌ์ฉ์ ์ด๋ฆ ๋๋ ์ด๋ฉ์ผ"
+ />
+ <input
+ name="pw"
+ onChange={this.handleInput}
+ type="password"
+ value={this.state.pw}
+ placeholder="๋น๋ฐ๋ฒํธ"
+ />
+ <button
+ onClick={this.goToMain}
+ type="button"
+ className="loginBtn"
+ disabled={!isValid}
+ >
+ ๋ก๊ทธ์ธ
+ </button>
+ </form>
+ </section>
+
+ <footer>
+ <Link to="" className="findPassword">
+ ๋น๋ฐ๋ฒํธ๋ฅผ ์์ผ์
จ๋์?
+ </Link>
+ </footer>
+ </main>
+ </div>
+ );
}
}
|
JavaScript
|
์ด๋ฐ ์ฃผ์๋ค์ ๋ถํ์ํ๋๊น ์ญ์ ํด์ฃผ์๋๊ฒ ์ข์๋ณด์
๋๋ค!
|
@@ -1,8 +1,79 @@
import React, { Component } from 'react';
+import { Link } from 'react-router-dom';
+
+import './Login.scss';
class Login extends Component {
+ constructor() {
+ super();
+ this.state = {
+ id: '',
+ pw: '',
+ };
+ }
+
+ handleInput = event => {
+ const { name, value } = event.target;
+ this.setState({
+ [name]: value,
+ });
+ };
+
+ goToMain = () => {
+ this.props.history.push('/main-Soojeong#');
+ };
+
render() {
- return <div>๋ก๊ทธ์ธ</div>;
+ const isValid =
+ this.state.id.includes('@') &&
+ this.state.id.length >= 5 &&
+ this.state.pw.length >= 8;
+
+ return (
+ <div className="Login">
+ <main>
+ <header>
+ <h1>Westagram</h1>
+ </header>
+
+ <section className="loginInputBox">
+ <h2 className="sr-only">login page</h2>
+ <form>
+ <input
+ name="id"
+ autoComplete="off"
+ onChange={this.handleInput}
+ type="text"
+ id="loginId"
+ value={this.state.id}
+ placeholder="์ ํ๋ฒํธ, ์ฌ์ฉ์ ์ด๋ฆ ๋๋ ์ด๋ฉ์ผ"
+ />
+ <input
+ name="pw"
+ onChange={this.handleInput}
+ type="password"
+ value={this.state.pw}
+ placeholder="๋น๋ฐ๋ฒํธ"
+ />
+ <button
+ onClick={this.goToMain}
+ type="button"
+ className="loginBtn"
+ disabled={!isValid}
+ >
+ ๋ก๊ทธ์ธ
+ </button>
+ </form>
+ </section>
+
+ <footer>
+ <Link to="" className="findPassword">
+ ๋น๋ฐ๋ฒํธ๋ฅผ ์์ผ์
จ๋์?
+ </Link>
+ </footer>
+ </main>
+ </div>
+ );
}
}
|
JavaScript
|
event.target ๋ฐ๋ณต๋๊ณ ์๋๋ฐ ๊ตฌ์กฐ๋ถํดํด์ ํ์ฉํด๋ณผ ์ ์๊ฒ ๋ค์!
```const {name,value} = event.target;```
|
@@ -0,0 +1,40 @@
+package nextstep.security.authentication;
+
+import jakarta.servlet.FilterChain;
+import jakarta.servlet.ServletException;
+import jakarta.servlet.http.HttpServletRequest;
+import jakarta.servlet.http.HttpServletResponse;
+import java.io.IOException;
+import nextstep.security.core.Authentication;
+import nextstep.security.core.context.SecurityContextHolder;
+import nextstep.security.exception.AuthenticationException;
+import nextstep.security.web.authentication.AuthenticationConverter;
+import nextstep.security.web.authentication.BasicAuthenticationConverter;
+import org.springframework.web.filter.OncePerRequestFilter;
+
+public class BasicAuthenticationFilter extends OncePerRequestFilter {
+
+ private final AuthenticationManager authenticationManager;
+ private final AuthenticationConverter authenticationConverter = new BasicAuthenticationConverter();
+
+ public BasicAuthenticationFilter(AuthenticationManager authenticationManager) {
+ this.authenticationManager = authenticationManager;
+ }
+
+ @Override
+ protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
+ throws IOException, ServletException {
+ try {
+ Authentication authRequest = authenticationConverter.convert(request);
+
+ if (authRequest != null) {
+ Authentication authResult = authenticationManager.authenticate(authRequest);
+ SecurityContextHolder.getContext().setAuthentication(authResult);
+ }
+
+ filterChain.doFilter(request, response);
+ } catch (AuthenticationException e) {
+ response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
+ }
+ }
+}
|
Java
|
BasicAuthenticationFilter ํํฐ๋ฅผ ์์ฑํ ๋ UserDetailsService ๋์ AuthenticationManager๋ฅผ ์ฃผ์
๋ฐ์ผ๋ฉด ์ด๋จ๊น์?
|
@@ -0,0 +1,35 @@
+package nextstep.security.authentication;
+
+import jakarta.servlet.ServletException;
+import jakarta.servlet.http.HttpServletRequest;
+import jakarta.servlet.http.HttpServletResponse;
+import java.io.IOException;
+import java.util.Map;
+import nextstep.security.core.Authentication;
+import nextstep.security.exception.AuthenticationException;
+import nextstep.security.exception.AuthenticationServiceException;
+import nextstep.security.web.authentication.AbstractAuthenticationProcessingFilter;
+
+public class UsernamePasswordAuthenticationFilter extends AbstractAuthenticationProcessingFilter {
+ private static final String DEFAULT_REQUEST_URI = "/login";
+
+ public UsernamePasswordAuthenticationFilter(AuthenticationManager authenticationManager) {
+ super(DEFAULT_REQUEST_URI, authenticationManager);
+ }
+
+ @Override
+ public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response)
+ throws AuthenticationException, IOException, ServletException {
+ if (!"POST".equalsIgnoreCase(request.getMethod())) {
+ throw new AuthenticationServiceException();
+ }
+ Map<String, String[]> parameterMap = request.getParameterMap();
+ String username = parameterMap.get("username")[0];
+ String password = parameterMap.get("password")[0];
+
+ UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(
+ username, password, false);
+
+ return this.getAuthenticationManager().authenticate(authRequest);
+ }
+}
|
Java
|
์ฌ๊ธฐ๋ ๋ง์ฐฌ๊ฐ์ง๋ก UserDetailsService ๋์ AuthenticationManager๋ฅผ ์ฃผ์
๋ฐ์ผ๋ฉด ์ด๋จ๊น์?
|
@@ -0,0 +1,40 @@
+package nextstep.security.authentication;
+
+import jakarta.servlet.FilterChain;
+import jakarta.servlet.ServletException;
+import jakarta.servlet.http.HttpServletRequest;
+import jakarta.servlet.http.HttpServletResponse;
+import java.io.IOException;
+import nextstep.security.core.Authentication;
+import nextstep.security.core.context.SecurityContextHolder;
+import nextstep.security.exception.AuthenticationException;
+import nextstep.security.web.authentication.AuthenticationConverter;
+import nextstep.security.web.authentication.BasicAuthenticationConverter;
+import org.springframework.web.filter.OncePerRequestFilter;
+
+public class BasicAuthenticationFilter extends OncePerRequestFilter {
+
+ private final AuthenticationManager authenticationManager;
+ private final AuthenticationConverter authenticationConverter = new BasicAuthenticationConverter();
+
+ public BasicAuthenticationFilter(AuthenticationManager authenticationManager) {
+ this.authenticationManager = authenticationManager;
+ }
+
+ @Override
+ protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
+ throws IOException, ServletException {
+ try {
+ Authentication authRequest = authenticationConverter.convert(request);
+
+ if (authRequest != null) {
+ Authentication authResult = authenticationManager.authenticate(authRequest);
+ SecurityContextHolder.getContext().setAuthentication(authResult);
+ }
+
+ filterChain.doFilter(request, response);
+ } catch (AuthenticationException e) {
+ response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
+ }
+ }
+}
|
Java
|
Authentication ์์ฑ์ ์ฑ
์์ ๋ณ๋์ ํด๋์ค๋ก ๋ถ๋ฆฌํด๋ณด๋ฉด ์ด๋จ๊น์?
|
@@ -0,0 +1,40 @@
+package nextstep.security.authentication;
+
+import jakarta.servlet.FilterChain;
+import jakarta.servlet.ServletException;
+import jakarta.servlet.http.HttpServletRequest;
+import jakarta.servlet.http.HttpServletResponse;
+import java.io.IOException;
+import nextstep.security.core.Authentication;
+import nextstep.security.core.context.SecurityContextHolder;
+import nextstep.security.exception.AuthenticationException;
+import nextstep.security.web.authentication.AuthenticationConverter;
+import nextstep.security.web.authentication.BasicAuthenticationConverter;
+import org.springframework.web.filter.OncePerRequestFilter;
+
+public class BasicAuthenticationFilter extends OncePerRequestFilter {
+
+ private final AuthenticationManager authenticationManager;
+ private final AuthenticationConverter authenticationConverter = new BasicAuthenticationConverter();
+
+ public BasicAuthenticationFilter(AuthenticationManager authenticationManager) {
+ this.authenticationManager = authenticationManager;
+ }
+
+ @Override
+ protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
+ throws IOException, ServletException {
+ try {
+ Authentication authRequest = authenticationConverter.convert(request);
+
+ if (authRequest != null) {
+ Authentication authResult = authenticationManager.authenticate(authRequest);
+ SecurityContextHolder.getContext().setAuthentication(authResult);
+ }
+
+ filterChain.doFilter(request, response);
+ } catch (AuthenticationException e) {
+ response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
+ }
+ }
+}
|
Java
|
convert ๋ฉ์๋๋ Token์ผ๋ก ๋ณํํด์ฃผ๋ ์ญํ ๋ง ํ๋ฉด ์ด๋จ๊น์?
|
@@ -0,0 +1,35 @@
+package nextstep.security.authentication;
+
+import jakarta.servlet.ServletException;
+import jakarta.servlet.http.HttpServletRequest;
+import jakarta.servlet.http.HttpServletResponse;
+import java.io.IOException;
+import java.util.Map;
+import nextstep.security.core.Authentication;
+import nextstep.security.exception.AuthenticationException;
+import nextstep.security.exception.AuthenticationServiceException;
+import nextstep.security.web.authentication.AbstractAuthenticationProcessingFilter;
+
+public class UsernamePasswordAuthenticationFilter extends AbstractAuthenticationProcessingFilter {
+ private static final String DEFAULT_REQUEST_URI = "/login";
+
+ public UsernamePasswordAuthenticationFilter(AuthenticationManager authenticationManager) {
+ super(DEFAULT_REQUEST_URI, authenticationManager);
+ }
+
+ @Override
+ public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response)
+ throws AuthenticationException, IOException, ServletException {
+ if (!"POST".equalsIgnoreCase(request.getMethod())) {
+ throw new AuthenticationServiceException();
+ }
+ Map<String, String[]> parameterMap = request.getParameterMap();
+ String username = parameterMap.get("username")[0];
+ String password = parameterMap.get("password")[0];
+
+ UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(
+ username, password, false);
+
+ return this.getAuthenticationManager().authenticate(authRequest);
+ }
+}
|
Java
|
์ํ๋ฆฌํฐ์ ์ค์ ์ฝ๋๋ฅผ ์ดํด๋ณด๋ฉด ์ธ์ฆ ํํฐ์์ ์ค๋ณต๋๋ ๋ถ๋ถ์ AbstractAuthenticationProcessingFilter๋ก ๋ถ๋ฆฌ๋์ด์์ต๋๋ค! UsernamePasswordAuthenticationFilter์์ ํด๋น ๋ถ๋ถ์ ๋ถ๋ฆฌํด๋ณด๋ ์๋๋ฅผ ํด๋ณด์๋ฉด ์ด๋จ๊น์?
ํ์ ์๊ตฌ์ฌํญ์ ์๋์ง๋ง ๋น ๋ฅด๊ฒ ๋ฏธ์
์ ์ ํด์ฃผ์
จ๊ณ ์ ํ ์๊ตฌ์ฌํญ์ผ๋ก 3์ฃผ์ฐจ ๋ฏธ์
์ํ์ ๋์์ด ๋ ๊ฒ ๊ฐ์์ ์ ์๋๋ ค์~
|
@@ -0,0 +1,40 @@
+package nextstep.security.authentication;
+
+import jakarta.servlet.FilterChain;
+import jakarta.servlet.ServletException;
+import jakarta.servlet.http.HttpServletRequest;
+import jakarta.servlet.http.HttpServletResponse;
+import java.io.IOException;
+import nextstep.security.core.Authentication;
+import nextstep.security.core.context.SecurityContextHolder;
+import nextstep.security.exception.AuthenticationException;
+import nextstep.security.web.authentication.AuthenticationConverter;
+import nextstep.security.web.authentication.BasicAuthenticationConverter;
+import org.springframework.web.filter.OncePerRequestFilter;
+
+public class BasicAuthenticationFilter extends OncePerRequestFilter {
+
+ private final AuthenticationManager authenticationManager;
+ private final AuthenticationConverter authenticationConverter = new BasicAuthenticationConverter();
+
+ public BasicAuthenticationFilter(AuthenticationManager authenticationManager) {
+ this.authenticationManager = authenticationManager;
+ }
+
+ @Override
+ protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
+ throws IOException, ServletException {
+ try {
+ Authentication authRequest = authenticationConverter.convert(request);
+
+ if (authRequest != null) {
+ Authentication authResult = authenticationManager.authenticate(authRequest);
+ SecurityContextHolder.getContext().setAuthentication(authResult);
+ }
+
+ filterChain.doFilter(request, response);
+ } catch (AuthenticationException e) {
+ response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
+ }
+ }
+}
|
Java
|
๊ธฐ์กด ๊ตฌ์กฐ์์ ๊ณ์ ๋ฐ์ ์์ผ ๋๊ฐ๋ค ๋ณด๋ ๋ฏธ์ฒ ์ ๊ฒฝ์ฐ์ง ๋ชปํ๊ฒ ๊ฐ์ต๋๋ค ๐
๊ตฌ์ฒด๊ฐ ์๋ ์ถ์์ ์์กดํด์ผ ํ๋ค๋๊ฑธ ์๊ธฐ์์ผ์ฃผ์
์ ๊ฐ์ฌํฉ๋๋ค ๐
|
@@ -0,0 +1,35 @@
+package nextstep.security.authentication;
+
+import jakarta.servlet.ServletException;
+import jakarta.servlet.http.HttpServletRequest;
+import jakarta.servlet.http.HttpServletResponse;
+import java.io.IOException;
+import java.util.Map;
+import nextstep.security.core.Authentication;
+import nextstep.security.exception.AuthenticationException;
+import nextstep.security.exception.AuthenticationServiceException;
+import nextstep.security.web.authentication.AbstractAuthenticationProcessingFilter;
+
+public class UsernamePasswordAuthenticationFilter extends AbstractAuthenticationProcessingFilter {
+ private static final String DEFAULT_REQUEST_URI = "/login";
+
+ public UsernamePasswordAuthenticationFilter(AuthenticationManager authenticationManager) {
+ super(DEFAULT_REQUEST_URI, authenticationManager);
+ }
+
+ @Override
+ public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response)
+ throws AuthenticationException, IOException, ServletException {
+ if (!"POST".equalsIgnoreCase(request.getMethod())) {
+ throw new AuthenticationServiceException();
+ }
+ Map<String, String[]> parameterMap = request.getParameterMap();
+ String username = parameterMap.get("username")[0];
+ String password = parameterMap.get("password")[0];
+
+ UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(
+ username, password, false);
+
+ return this.getAuthenticationManager().authenticate(authRequest);
+ }
+}
|
Java
|
๋ง์ฐฌ๊ฐ์ง๋ก [fa5f619](https://github.com/next-step/spring-security-authentication/pull/33/commits/fa5f61942bfba0e2f794bb43c5b86af416c679b8) ์ปค๋ฐ์ผ๋ก ๋ฐ์ํ์ต๋๋ค!
|
@@ -0,0 +1,40 @@
+package nextstep.security.authentication;
+
+import jakarta.servlet.FilterChain;
+import jakarta.servlet.ServletException;
+import jakarta.servlet.http.HttpServletRequest;
+import jakarta.servlet.http.HttpServletResponse;
+import java.io.IOException;
+import nextstep.security.core.Authentication;
+import nextstep.security.core.context.SecurityContextHolder;
+import nextstep.security.exception.AuthenticationException;
+import nextstep.security.web.authentication.AuthenticationConverter;
+import nextstep.security.web.authentication.BasicAuthenticationConverter;
+import org.springframework.web.filter.OncePerRequestFilter;
+
+public class BasicAuthenticationFilter extends OncePerRequestFilter {
+
+ private final AuthenticationManager authenticationManager;
+ private final AuthenticationConverter authenticationConverter = new BasicAuthenticationConverter();
+
+ public BasicAuthenticationFilter(AuthenticationManager authenticationManager) {
+ this.authenticationManager = authenticationManager;
+ }
+
+ @Override
+ protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
+ throws IOException, ServletException {
+ try {
+ Authentication authRequest = authenticationConverter.convert(request);
+
+ if (authRequest != null) {
+ Authentication authResult = authenticationManager.authenticate(authRequest);
+ SecurityContextHolder.getContext().setAuthentication(authResult);
+ }
+
+ filterChain.doFilter(request, response);
+ } catch (AuthenticationException e) {
+ response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
+ }
+ }
+}
|
Java
|
[81fa490](https://github.com/next-step/spring-security-authentication/pull/33/commits/81fa490d0c5ef702821a1b226a17c3363bb5131a)๋ก ๋ฐ์ํ์ต๋๋ค!
|
@@ -0,0 +1,40 @@
+package nextstep.security.authentication;
+
+import jakarta.servlet.FilterChain;
+import jakarta.servlet.ServletException;
+import jakarta.servlet.http.HttpServletRequest;
+import jakarta.servlet.http.HttpServletResponse;
+import java.io.IOException;
+import nextstep.security.core.Authentication;
+import nextstep.security.core.context.SecurityContextHolder;
+import nextstep.security.exception.AuthenticationException;
+import nextstep.security.web.authentication.AuthenticationConverter;
+import nextstep.security.web.authentication.BasicAuthenticationConverter;
+import org.springframework.web.filter.OncePerRequestFilter;
+
+public class BasicAuthenticationFilter extends OncePerRequestFilter {
+
+ private final AuthenticationManager authenticationManager;
+ private final AuthenticationConverter authenticationConverter = new BasicAuthenticationConverter();
+
+ public BasicAuthenticationFilter(AuthenticationManager authenticationManager) {
+ this.authenticationManager = authenticationManager;
+ }
+
+ @Override
+ protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
+ throws IOException, ServletException {
+ try {
+ Authentication authRequest = authenticationConverter.convert(request);
+
+ if (authRequest != null) {
+ Authentication authResult = authenticationManager.authenticate(authRequest);
+ SecurityContextHolder.getContext().setAuthentication(authResult);
+ }
+
+ filterChain.doFilter(request, response);
+ } catch (AuthenticationException e) {
+ response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
+ }
+ }
+}
|
Java
|
DRY ์๋ฐ๋ ๊ฒธํ๊ณ ์์๋ค์!
ํด๋์ค ๋ถ๋ฆฌํ๊ณ ๋ณด๋ ๊ธฐ์กด ๋ฉ์๋์ ์ฑ
์์ด ๊ณผ๋ํ๊ณ , ํ์์น ์์ ๋๋ธ์ฒดํฌ๊ฐ ๋ค์ด๊ฐ๋ค๋๊ฒ ๋ฐ๋ก ํ์ธ๋์ด์ ์ข์์ต๋๋ค!
|
@@ -0,0 +1,35 @@
+package nextstep.security.authentication;
+
+import jakarta.servlet.ServletException;
+import jakarta.servlet.http.HttpServletRequest;
+import jakarta.servlet.http.HttpServletResponse;
+import java.io.IOException;
+import java.util.Map;
+import nextstep.security.core.Authentication;
+import nextstep.security.exception.AuthenticationException;
+import nextstep.security.exception.AuthenticationServiceException;
+import nextstep.security.web.authentication.AbstractAuthenticationProcessingFilter;
+
+public class UsernamePasswordAuthenticationFilter extends AbstractAuthenticationProcessingFilter {
+ private static final String DEFAULT_REQUEST_URI = "/login";
+
+ public UsernamePasswordAuthenticationFilter(AuthenticationManager authenticationManager) {
+ super(DEFAULT_REQUEST_URI, authenticationManager);
+ }
+
+ @Override
+ public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response)
+ throws AuthenticationException, IOException, ServletException {
+ if (!"POST".equalsIgnoreCase(request.getMethod())) {
+ throw new AuthenticationServiceException();
+ }
+ Map<String, String[]> parameterMap = request.getParameterMap();
+ String username = parameterMap.get("username")[0];
+ String password = parameterMap.get("password")[0];
+
+ UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(
+ username, password, false);
+
+ return this.getAuthenticationManager().authenticate(authRequest);
+ }
+}
|
Java
|
[dbde31c](https://github.com/next-step/spring-security-authentication/pull/33/commits/dbde31cb10aee34fe4e1c767064389589b2fa2ba)๋ก ์๋ํด ๋ณด์์ต๋๋ค!
์ค์ ์ฝ๋๋ฅผ ๋ถ์ํ๋ฉด์ ํฅ๋ฏธ๋ก์ ๋์ ์
SecurityContextRepository.saveContext() ํธ์ถ์
SecurityContextHolderFilter๊ฐ ์๋ AbstractAuthenticationProcessingFilter์์ ํด์ฃผ๊ณ ์๋ค๋ ์ ์ด์๋๋ฐ์.

๊ทธ๋ ๊ฒ ๋๋ฉด ์์ ๊ทธ๋ฆผ์ 3๋ฒ ํ๋ก์ฐ๋ ์๋ง๋๊ฑฐ ์๋๊ฐ? ์ดํด๋ฅผ ๋๊ธฐ ์ํ ๊ทธ๋ฆผ์ผ๊น? ์ด๋ฐ ์ ๋ฐ ์๊ฐ๋ค์ ํ๋ฉด์ ๋๊ฒ ์ฌ๋ฏธ์๊ฒ ๋ณธ ๊ฒ ๊ฐ์ต๋๋ค ใ
ใ
ใ
..
์ ๊ฐ ์๋ชป ์ดํดํ๊ฑฐ๋ผ๋ฉด ์ง์ด์ฃผ์๋ฉด ๊ฐ์ฌํ๊ฒ ์ต๋๋ค!
๋ํ AbstractAuthenticationProcessingFilter ๊ตฌํํ๋ฉด์
RequestMatcher์ด๋, strategy ๋์์ธ ํจํด์ผ๋ก ๊ตฌํํด์ผ ํ๋ ๋ถ๋ถ์
ํ ์์ ์์๋ ์ค๋ฒ์์ง๋์ด๋ง์ด๋ผ๊ณ ํ๋จํด ๋ฃ์ง ์์์ต๋๋ค!
์๋ง ์ด๋ฐ ๋ถ๋ถ๊น์ง๋ ๋ฐ๋ผ์ง ์์ผ์
จ์..๊ฒ ๊ฐ์์์! ๐
|
@@ -0,0 +1,35 @@
+package nextstep.security.authentication;
+
+import jakarta.servlet.ServletException;
+import jakarta.servlet.http.HttpServletRequest;
+import jakarta.servlet.http.HttpServletResponse;
+import java.io.IOException;
+import java.util.Map;
+import nextstep.security.core.Authentication;
+import nextstep.security.exception.AuthenticationException;
+import nextstep.security.exception.AuthenticationServiceException;
+import nextstep.security.web.authentication.AbstractAuthenticationProcessingFilter;
+
+public class UsernamePasswordAuthenticationFilter extends AbstractAuthenticationProcessingFilter {
+ private static final String DEFAULT_REQUEST_URI = "/login";
+
+ public UsernamePasswordAuthenticationFilter(AuthenticationManager authenticationManager) {
+ super(DEFAULT_REQUEST_URI, authenticationManager);
+ }
+
+ @Override
+ public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response)
+ throws AuthenticationException, IOException, ServletException {
+ if (!"POST".equalsIgnoreCase(request.getMethod())) {
+ throw new AuthenticationServiceException();
+ }
+ Map<String, String[]> parameterMap = request.getParameterMap();
+ String username = parameterMap.get("username")[0];
+ String password = parameterMap.get("password")[0];
+
+ UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(
+ username, password, false);
+
+ return this.getAuthenticationManager().authenticate(authRequest);
+ }
+}
|
Java
|
์ฐ์ ์คํ๋๊ป์ ์ฝ๋๋ก ํ์ธํ ๋ถ๋ถ์ด ๋ง์ต๋๋ค!
์ ๊ฐ ๊ฐ์์์ SecurityContextPersistenceFilter์ SecurityContextHolderFilter๋ ๊ฐ๊ณ ๋ฒ์ ์ ์ฐจ์ด๋ผ๊ณ ๋ง ๋ง์๋๋ ธ๋๋ฐ
๊ฐ์ ์ญํ ์ ํ๋ค๋ ๊ด์ ์์ ๊ฐ๋ค๊ณ ๋ง์๋๋ ธ๊ณ ์ฌ์ค ๋ค๋ฅด๊ฒ ๋์ํ๋ ๋ถ๋ถ์ด ์์ต๋๋ค.
[SecurityContextPersistenceFilter](https://docs.spring.io/spring-security/reference/servlet/authentication/persistence.html#securitycontextpersistencefilter)์ ์ค๋ช
์ ๋ณด๋ฉด repository์ ์ ์ฅํ๋ ๋ถ๋ถ๊น์ง ํฌํจ์ด์ง๋ง [SecurityContextHolderFilter](https://docs.spring.io/spring-security/reference/servlet/authentication/persistence.html#securitycontextholderfilter)์ ์ค๋ช
์ ๋ณด๋ฉด ์ ์ฅํ๋ ๋ถ๋ถ์ ํฌํจํ๊ณ ์์ง ์์ต๋๋ค.
|
@@ -1,14 +1,77 @@
-import React from "react";
-import "./PostAdd.scss";
+import React, { useState } from 'react';
+import { useNavigate } from 'react-router-dom';
+import './PostAdd.scss';
+import { Button } from '../PostAdd/components/Post.jsx';
const PostAdd = () => {
+ const [comment, setComment] = useState('');
-return(
- <div className="postAdd">
- <div>๋ก๊ทธ์ธ</div>
- </div>
-);
+ const navigate = useNavigate();
-};
+ const handleText = value => {
+ setComment(value);
+ };
+ console.log(handleText);
+
+ const cancel = () => {
+ const confirmed = window.confirm(
+ '์ ์ผ์ ๊ธ์ ์ทจ์ํ๊ณ post-list๋ก ๋์ด๊ฐ๊ฒ ์ต๋๊น?',
+ );
+ if (confirmed) {
+ navigate('/post-list');
+ }
+ };
+
+ const posting = () => {
+ if (comment.length >= 1) {
+ navigate('/post-list');
-export default PostAdd;
\ No newline at end of file
+ fetch({
+ method: 'POST',
+ headers: {
+ 'Content-Type': 'application/json;charset=utf-8',
+ },
+ body: JSON.stringify({
+ content: '์ ์ ๊ฐ ์์ฑํ ๊ธ',
+ }),
+ })
+ .then(response => response.json)
+ .then(data => console.log(data));
+ } else {
+ alert('๋ด์ฉ์ ์์ฑ์ฃผ์ธ์.');
+ }
+ };
+
+ return (
+ <div className="userBox">
+ <div className="userWrap">
+ <img className="user" src="/images/user.png" alt="userPicture" />
+ <div className="contentBox">
+ <div className="userName">NAME</div>
+ <textarea
+ onChange={event => handleText(event.target.value)}
+ className="textArea"
+ cols="80"
+ rows="30"
+ type="text"
+ value={comment}
+ />
+
+ <div className="buttonWrap">
+ <Button
+ className="customButton cancelButton"
+ buttonName="์ทจ์"
+ active={cancel}
+ />
+ <Button
+ className="customButton addButton"
+ buttonName="๊ฒ์"
+ active={posting}
+ />
+ </div>
+ </div>
+ </div>
+ </div>
+ );
+};
+export default PostAdd;
|
JavaScript
|
import ์์์๋ ์ ์ง๋ณด์ ๋ฐ ๊ฐ๋
์ฑ์ ์ํ ์ปจ๋ฒค์
์ด ์์ต๋๋ค.
์์ฝ๋์ ์ปจ๋ฒค์
์ ๊ฐ๋ตํ๊ฒ ์๋์ ๊ฐ๊ณ , ์ฐธ๊ณ ํด์ ์์ ํด ์ฃผ์ธ์!
- ๋ผ์ด๋ธ๋ฌ๋ฆฌ
- React ๊ด๋ จ ํจํค์ง
- ์ธ๋ถ ๋ผ์ด๋ธ๋ฌ๋ฆฌ
- ์ปดํฌ๋ํธ
- ๊ณตํต ์ปดํฌ๋ํธ โ ๋จผ ์ปดํฌ๋ํธ โ ๊ฐ๊น์ด ์ปดํฌ๋ํธ
- ํจ์, ๋ณ์ ๋ฐ ์ค์ ํ์ผ
- ์ฌ์ง ๋ฑ ๋ฏธ๋์ด ํ์ผ(`.png`)
- css ํ์ผ (.`scss`)
|
@@ -1,14 +1,77 @@
-import React from "react";
-import "./PostAdd.scss";
+import React, { useState } from 'react';
+import { useNavigate } from 'react-router-dom';
+import './PostAdd.scss';
+import { Button } from '../PostAdd/components/Post.jsx';
const PostAdd = () => {
+ const [comment, setComment] = useState('');
-return(
- <div className="postAdd">
- <div>๋ก๊ทธ์ธ</div>
- </div>
-);
+ const navigate = useNavigate();
-};
+ const handleText = value => {
+ setComment(value);
+ };
+ console.log(handleText);
+
+ const cancel = () => {
+ const confirmed = window.confirm(
+ '์ ์ผ์ ๊ธ์ ์ทจ์ํ๊ณ post-list๋ก ๋์ด๊ฐ๊ฒ ์ต๋๊น?',
+ );
+ if (confirmed) {
+ navigate('/post-list');
+ }
+ };
+
+ const posting = () => {
+ if (comment.length >= 1) {
+ navigate('/post-list');
-export default PostAdd;
\ No newline at end of file
+ fetch({
+ method: 'POST',
+ headers: {
+ 'Content-Type': 'application/json;charset=utf-8',
+ },
+ body: JSON.stringify({
+ content: '์ ์ ๊ฐ ์์ฑํ ๊ธ',
+ }),
+ })
+ .then(response => response.json)
+ .then(data => console.log(data));
+ } else {
+ alert('๋ด์ฉ์ ์์ฑ์ฃผ์ธ์.');
+ }
+ };
+
+ return (
+ <div className="userBox">
+ <div className="userWrap">
+ <img className="user" src="/images/user.png" alt="userPicture" />
+ <div className="contentBox">
+ <div className="userName">NAME</div>
+ <textarea
+ onChange={event => handleText(event.target.value)}
+ className="textArea"
+ cols="80"
+ rows="30"
+ type="text"
+ value={comment}
+ />
+
+ <div className="buttonWrap">
+ <Button
+ className="customButton cancelButton"
+ buttonName="์ทจ์"
+ active={cancel}
+ />
+ <Button
+ className="customButton addButton"
+ buttonName="๊ฒ์"
+ active={posting}
+ />
+ </div>
+ </div>
+ </div>
+ </div>
+ );
+};
+export default PostAdd;
|
JavaScript
|
event ๊ฐ์ฒด์๋ ์ฌ๋ฌ ๋ฐ์ดํฐ๊ฐ ๋ด๊ฒจ์์ต๋๋ค.
๊ทธ ์ค์์ target์ value(input์ ์
๋ ฅํ ๊ฐ)๋ง์ ์ฌ์ฉํ๊ธฐ ๋๋ฌธ์, ํจ์๋ฅผ ํธ์ถํ ๋ ์ธ์๋ก ์์ event.target.value๋ง์ ์ธ์๋ก ๋๊ฒจ์ ์ฌ์ฉํ๋ฉด ์ด ํจ์์ ์ฌ์ฉ์ด ์ข ๋ ๋ช
ํํ๊ฒ ๋ค์!
|
@@ -1,14 +1,77 @@
-import React from "react";
-import "./PostAdd.scss";
+import React, { useState } from 'react';
+import { useNavigate } from 'react-router-dom';
+import './PostAdd.scss';
+import { Button } from '../PostAdd/components/Post.jsx';
const PostAdd = () => {
+ const [comment, setComment] = useState('');
-return(
- <div className="postAdd">
- <div>๋ก๊ทธ์ธ</div>
- </div>
-);
+ const navigate = useNavigate();
-};
+ const handleText = value => {
+ setComment(value);
+ };
+ console.log(handleText);
+
+ const cancel = () => {
+ const confirmed = window.confirm(
+ '์ ์ผ์ ๊ธ์ ์ทจ์ํ๊ณ post-list๋ก ๋์ด๊ฐ๊ฒ ์ต๋๊น?',
+ );
+ if (confirmed) {
+ navigate('/post-list');
+ }
+ };
+
+ const posting = () => {
+ if (comment.length >= 1) {
+ navigate('/post-list');
-export default PostAdd;
\ No newline at end of file
+ fetch({
+ method: 'POST',
+ headers: {
+ 'Content-Type': 'application/json;charset=utf-8',
+ },
+ body: JSON.stringify({
+ content: '์ ์ ๊ฐ ์์ฑํ ๊ธ',
+ }),
+ })
+ .then(response => response.json)
+ .then(data => console.log(data));
+ } else {
+ alert('๋ด์ฉ์ ์์ฑ์ฃผ์ธ์.');
+ }
+ };
+
+ return (
+ <div className="userBox">
+ <div className="userWrap">
+ <img className="user" src="/images/user.png" alt="userPicture" />
+ <div className="contentBox">
+ <div className="userName">NAME</div>
+ <textarea
+ onChange={event => handleText(event.target.value)}
+ className="textArea"
+ cols="80"
+ rows="30"
+ type="text"
+ value={comment}
+ />
+
+ <div className="buttonWrap">
+ <Button
+ className="customButton cancelButton"
+ buttonName="์ทจ์"
+ active={cancel}
+ />
+ <Button
+ className="customButton addButton"
+ buttonName="๊ฒ์"
+ active={posting}
+ />
+ </div>
+ </div>
+ </div>
+ </div>
+ );
+};
+export default PostAdd;
|
JavaScript
|
์ค์๋ก ๋๋ ์ ๊ฒฝ์ฐ์๋ ๋ฌด์กฐ๊ฑด list ํ์ด์ง๋ก ์ด๋ํ๊ฒ ๋ ํ
๋ฐ, ์ ํ๊ถ์ ์ค ์๋ ์๊ฒ ๋ค์.
`window.confirm` ํจ์์ ๋ํด ์ฐพ์๋ณด๊ณ ์ ์ฉํด๋ณด์
๋ ์ข์ ๊ฒ ๊ฐ์ต๋๋ค!
|
@@ -1,14 +1,77 @@
-import React from "react";
-import "./PostAdd.scss";
+import React, { useState } from 'react';
+import { useNavigate } from 'react-router-dom';
+import './PostAdd.scss';
+import { Button } from '../PostAdd/components/Post.jsx';
const PostAdd = () => {
+ const [comment, setComment] = useState('');
-return(
- <div className="postAdd">
- <div>๋ก๊ทธ์ธ</div>
- </div>
-);
+ const navigate = useNavigate();
-};
+ const handleText = value => {
+ setComment(value);
+ };
+ console.log(handleText);
+
+ const cancel = () => {
+ const confirmed = window.confirm(
+ '์ ์ผ์ ๊ธ์ ์ทจ์ํ๊ณ post-list๋ก ๋์ด๊ฐ๊ฒ ์ต๋๊น?',
+ );
+ if (confirmed) {
+ navigate('/post-list');
+ }
+ };
+
+ const posting = () => {
+ if (comment.length >= 1) {
+ navigate('/post-list');
-export default PostAdd;
\ No newline at end of file
+ fetch({
+ method: 'POST',
+ headers: {
+ 'Content-Type': 'application/json;charset=utf-8',
+ },
+ body: JSON.stringify({
+ content: '์ ์ ๊ฐ ์์ฑํ ๊ธ',
+ }),
+ })
+ .then(response => response.json)
+ .then(data => console.log(data));
+ } else {
+ alert('๋ด์ฉ์ ์์ฑ์ฃผ์ธ์.');
+ }
+ };
+
+ return (
+ <div className="userBox">
+ <div className="userWrap">
+ <img className="user" src="/images/user.png" alt="userPicture" />
+ <div className="contentBox">
+ <div className="userName">NAME</div>
+ <textarea
+ onChange={event => handleText(event.target.value)}
+ className="textArea"
+ cols="80"
+ rows="30"
+ type="text"
+ value={comment}
+ />
+
+ <div className="buttonWrap">
+ <Button
+ className="customButton cancelButton"
+ buttonName="์ทจ์"
+ active={cancel}
+ />
+ <Button
+ className="customButton addButton"
+ buttonName="๊ฒ์"
+ active={posting}
+ />
+ </div>
+ </div>
+ </div>
+ </div>
+ );
+};
+export default PostAdd;
|
JavaScript
|
fetch ํจ์์ ์ธ์๋ ๋ณดํต 2๊ฐ๊ฐ ๋ค์ด๊ฐ๋๋ฐ, ์ง๊ธ์ ์ต์
์ ๊ด๋ จ๋ ๋ ๋ฒ์งธ ์ธ์๋ง ์์ฑ๋์ด ์๋ค์!
์ค์ ๋ก ํต์ ํ์ค ๋์๋ ์ฒซ ๋ฒ์งธ ์ธ์์ธ `API` ๊ฐ๋ ์ ์ ๋ฌํด ์ฃผ์ธ์!
|
@@ -1,14 +1,77 @@
-import React from "react";
-import "./PostAdd.scss";
+import React, { useState } from 'react';
+import { useNavigate } from 'react-router-dom';
+import './PostAdd.scss';
+import { Button } from '../PostAdd/components/Post.jsx';
const PostAdd = () => {
+ const [comment, setComment] = useState('');
-return(
- <div className="postAdd">
- <div>๋ก๊ทธ์ธ</div>
- </div>
-);
+ const navigate = useNavigate();
-};
+ const handleText = value => {
+ setComment(value);
+ };
+ console.log(handleText);
+
+ const cancel = () => {
+ const confirmed = window.confirm(
+ '์ ์ผ์ ๊ธ์ ์ทจ์ํ๊ณ post-list๋ก ๋์ด๊ฐ๊ฒ ์ต๋๊น?',
+ );
+ if (confirmed) {
+ navigate('/post-list');
+ }
+ };
+
+ const posting = () => {
+ if (comment.length >= 1) {
+ navigate('/post-list');
-export default PostAdd;
\ No newline at end of file
+ fetch({
+ method: 'POST',
+ headers: {
+ 'Content-Type': 'application/json;charset=utf-8',
+ },
+ body: JSON.stringify({
+ content: '์ ์ ๊ฐ ์์ฑํ ๊ธ',
+ }),
+ })
+ .then(response => response.json)
+ .then(data => console.log(data));
+ } else {
+ alert('๋ด์ฉ์ ์์ฑ์ฃผ์ธ์.');
+ }
+ };
+
+ return (
+ <div className="userBox">
+ <div className="userWrap">
+ <img className="user" src="/images/user.png" alt="userPicture" />
+ <div className="contentBox">
+ <div className="userName">NAME</div>
+ <textarea
+ onChange={event => handleText(event.target.value)}
+ className="textArea"
+ cols="80"
+ rows="30"
+ type="text"
+ value={comment}
+ />
+
+ <div className="buttonWrap">
+ <Button
+ className="customButton cancelButton"
+ buttonName="์ทจ์"
+ active={cancel}
+ />
+ <Button
+ className="customButton addButton"
+ buttonName="๊ฒ์"
+ active={posting}
+ />
+ </div>
+ </div>
+ </div>
+ </div>
+ );
+};
+export default PostAdd;
|
JavaScript
|
๋ถํ์ํ๊ฒ 3์ค์ผ๋ก ๊ฐ์ธ๊ณ ์๋ ๊ฒ ๊ฐ์๋ฐ, ์ผ๋จ ์ต์์์ div๋ ๋ถํ์ํด ๋ณด์ด๋ค์!
์์๊ฐ ์ค์ฒฉ๋ ์๋ก, ํ๋ก์ ํธ์ ๊ท๋ชจ๊ฐ ์ปค์ง ์๋ก ๋ก๋ฉ๋๋ ์๊ฐ์ด ๊ธธ์ด์ง๊ธฐ ๋๋ฌธ์ ๋ถํ์ํ๊ฒ ์ค์ฒฉ๋ ์์๋ ์ง์์ฃผ์
์ผ ํฉ๋๋ค!
|
@@ -1,14 +1,77 @@
-import React from "react";
-import "./PostAdd.scss";
+import React, { useState } from 'react';
+import { useNavigate } from 'react-router-dom';
+import './PostAdd.scss';
+import { Button } from '../PostAdd/components/Post.jsx';
const PostAdd = () => {
+ const [comment, setComment] = useState('');
-return(
- <div className="postAdd">
- <div>๋ก๊ทธ์ธ</div>
- </div>
-);
+ const navigate = useNavigate();
-};
+ const handleText = value => {
+ setComment(value);
+ };
+ console.log(handleText);
+
+ const cancel = () => {
+ const confirmed = window.confirm(
+ '์ ์ผ์ ๊ธ์ ์ทจ์ํ๊ณ post-list๋ก ๋์ด๊ฐ๊ฒ ์ต๋๊น?',
+ );
+ if (confirmed) {
+ navigate('/post-list');
+ }
+ };
+
+ const posting = () => {
+ if (comment.length >= 1) {
+ navigate('/post-list');
-export default PostAdd;
\ No newline at end of file
+ fetch({
+ method: 'POST',
+ headers: {
+ 'Content-Type': 'application/json;charset=utf-8',
+ },
+ body: JSON.stringify({
+ content: '์ ์ ๊ฐ ์์ฑํ ๊ธ',
+ }),
+ })
+ .then(response => response.json)
+ .then(data => console.log(data));
+ } else {
+ alert('๋ด์ฉ์ ์์ฑ์ฃผ์ธ์.');
+ }
+ };
+
+ return (
+ <div className="userBox">
+ <div className="userWrap">
+ <img className="user" src="/images/user.png" alt="userPicture" />
+ <div className="contentBox">
+ <div className="userName">NAME</div>
+ <textarea
+ onChange={event => handleText(event.target.value)}
+ className="textArea"
+ cols="80"
+ rows="30"
+ type="text"
+ value={comment}
+ />
+
+ <div className="buttonWrap">
+ <Button
+ className="customButton cancelButton"
+ buttonName="์ทจ์"
+ active={cancel}
+ />
+ <Button
+ className="customButton addButton"
+ buttonName="๊ฒ์"
+ active={posting}
+ />
+ </div>
+ </div>
+ </div>
+ </div>
+ );
+};
+export default PostAdd;
|
JavaScript
|
img ํ๊ทธ์ alt ๊ฐ์ ์ด๋์ ํ์ฉ๋ ๊น์?
์ฐพ์๋ณด์๊ณ ์ฌ๋ฐ๋ฅด๊ฒ ์์ฑํด ์ฃผ์ธ์!
|
@@ -0,0 +1,79 @@
+.userBox {
+ margin: 20px;
+ gap: 0 24px;
+ display: flex;
+ justify-content: center;
+ flex-direction: column;
+
+ .userWrap {
+ display: flex;
+ flex-direction: row;
+ justify-content: center;
+
+ .user {
+ width: 50px;
+ height: 50px;
+ border-radius: 50%;
+ }
+
+ .contentBox {
+ display: flex;
+ flex-direction: column;
+ gap: 10px;
+ margin-left: 20px;
+
+ .userName {
+ font-size: 20px;
+ font-weight: 700;
+ }
+
+ .textArea {
+ padding: 10px;
+ border-radius: 6px;
+ border: 1px solid var(--grey-88, #e0e0e0);
+ background: var(--white, #fff);
+ resize: none;
+ transition: border-color 0.3s;
+ outline: none;
+ }
+ .textArea:hover {
+ border-color: var(--gray, #999999);
+ }
+
+ .buttonWrap {
+ justify-content: space-between;
+ display: flex;
+
+ .customButton {
+ width: 120px;
+ height: 50px;
+ border-radius: 6px;
+ }
+
+ .cancelButton {
+ border: 1px solid var(--blue, #2d71f7);
+ background: var(--white, #fff);
+ color: var(--blue, #2d71f7);
+ cursor: pointer;
+ }
+ .cancelButton:hover {
+ border: 1px solid var(--navy, #083e7f);
+ background: var(--white, #fff);
+ color: var(--navy, #083e7f);
+ }
+
+ .addButton {
+ border: none;
+ background: var(--white, #2d71f7);
+ color: var(--white, #fff);
+ cursor: pointer;
+ }
+ .addButton:hover {
+ border: none;
+ background: var(--blue, #083e7f);
+ color: var(--white, #fff);
+ }
+ }
+ }
+ }
+}
|
Unknown
|
PR์ด ๋จธ์ง๋๋ค๋ฉด, ์ด ํ๋ก์ ํธ์ ๋ชจ๋ button ํ๊ทธ์ `width: 120px, height: 50px` ์์ฑ์ด ์ ์ฉ๋๊ฒ ๋ค์!
์ด๋ฅผ ๋ฐฉ์งํ๊ธฐ ์ํด์๋ ์์ ์ ํด์ฃผ์ ๊ฒ์ฒ๋ผ nesting๋์ด์ผ ํฉ๋๋ค.
์ถ๊ฐ๋ก, ํ๊ทธ ์ ํ์์ ์ฌ์ฉ์ ๋ค์์ ๊ฒฝ์ฐ ์ธ์๋ ์ง์ํ๋ ๊ฒ ์ข์ต๋๋ค.
1. ์ ์ญ์ ์ ์ฉ๋์ด์ผ ํ๋ ์คํ์ผ (e.g. common.scss, reset.scss)
2. ์์ผ๋ก๋ ๋ณ๊ฒฝ๋์ง ์๋๋ค๋ ํ์ ์ด ์๋ ์์
className์ ๋ถ์ฌํด์ ์คํ์ผ ์์ฑ ๋ถ์ฌํด ์ฃผ์ธ์!
|
@@ -1,7 +1,17 @@
@import url('https://fonts.googleapis.com/css2?family=Noto+Sans+KR:wght@100;300;400;500;700;900&display=swap');
-
* {
box-sizing: border-box;
font-family: 'Noto Sans KR', sans-serif;
-}
\ No newline at end of file
+}
+body {
+ width: 100vw;
+ height: 100vh;
+ display: flex;
+ align-items: center;
+ justify-content: center;
+}
+
+button {
+ cursor: pointer;
+}
|
Unknown
|
๊ณต์ฉ ํ์ผ์ ์์ ํด์ ์ฌ๋ ค์ฃผ์
จ๋๋ฐ, ๊ณต์ฉ ํ์ผ์ ์์ ์
1. ํ์๊ณผ์ ์ถฉ๋ถํ ์์ ํ์
2. ํด๋น ํ์ผ๋ง ์์ ํ๋ ๋ด์ฉ์ PR
์ ์ฌ๋ ค์ฃผ์
์ผ ํฉ๋๋ค!
|
@@ -1,14 +1,77 @@
-import React from "react";
-import "./PostAdd.scss";
+import React, { useState } from 'react';
+import { useNavigate } from 'react-router-dom';
+import './PostAdd.scss';
+import { Button } from '../PostAdd/components/Post.jsx';
const PostAdd = () => {
+ const [comment, setComment] = useState('');
-return(
- <div className="postAdd">
- <div>๋ก๊ทธ์ธ</div>
- </div>
-);
+ const navigate = useNavigate();
-};
+ const handleText = value => {
+ setComment(value);
+ };
+ console.log(handleText);
+
+ const cancel = () => {
+ const confirmed = window.confirm(
+ '์ ์ผ์ ๊ธ์ ์ทจ์ํ๊ณ post-list๋ก ๋์ด๊ฐ๊ฒ ์ต๋๊น?',
+ );
+ if (confirmed) {
+ navigate('/post-list');
+ }
+ };
+
+ const posting = () => {
+ if (comment.length >= 1) {
+ navigate('/post-list');
-export default PostAdd;
\ No newline at end of file
+ fetch({
+ method: 'POST',
+ headers: {
+ 'Content-Type': 'application/json;charset=utf-8',
+ },
+ body: JSON.stringify({
+ content: '์ ์ ๊ฐ ์์ฑํ ๊ธ',
+ }),
+ })
+ .then(response => response.json)
+ .then(data => console.log(data));
+ } else {
+ alert('๋ด์ฉ์ ์์ฑ์ฃผ์ธ์.');
+ }
+ };
+
+ return (
+ <div className="userBox">
+ <div className="userWrap">
+ <img className="user" src="/images/user.png" alt="userPicture" />
+ <div className="contentBox">
+ <div className="userName">NAME</div>
+ <textarea
+ onChange={event => handleText(event.target.value)}
+ className="textArea"
+ cols="80"
+ rows="30"
+ type="text"
+ value={comment}
+ />
+
+ <div className="buttonWrap">
+ <Button
+ className="customButton cancelButton"
+ buttonName="์ทจ์"
+ active={cancel}
+ />
+ <Button
+ className="customButton addButton"
+ buttonName="๊ฒ์"
+ active={posting}
+ />
+ </div>
+ </div>
+ </div>
+ </div>
+ );
+};
+export default PostAdd;
|
JavaScript
|
๋ฉํ ๋ฆฌ๋ทฐ ๋ฐ์ ์๋ฃ
|
@@ -1,14 +1,77 @@
-import React from "react";
-import "./PostAdd.scss";
+import React, { useState } from 'react';
+import { useNavigate } from 'react-router-dom';
+import './PostAdd.scss';
+import { Button } from '../PostAdd/components/Post.jsx';
const PostAdd = () => {
+ const [comment, setComment] = useState('');
-return(
- <div className="postAdd">
- <div>๋ก๊ทธ์ธ</div>
- </div>
-);
+ const navigate = useNavigate();
-};
+ const handleText = value => {
+ setComment(value);
+ };
+ console.log(handleText);
+
+ const cancel = () => {
+ const confirmed = window.confirm(
+ '์ ์ผ์ ๊ธ์ ์ทจ์ํ๊ณ post-list๋ก ๋์ด๊ฐ๊ฒ ์ต๋๊น?',
+ );
+ if (confirmed) {
+ navigate('/post-list');
+ }
+ };
+
+ const posting = () => {
+ if (comment.length >= 1) {
+ navigate('/post-list');
-export default PostAdd;
\ No newline at end of file
+ fetch({
+ method: 'POST',
+ headers: {
+ 'Content-Type': 'application/json;charset=utf-8',
+ },
+ body: JSON.stringify({
+ content: '์ ์ ๊ฐ ์์ฑํ ๊ธ',
+ }),
+ })
+ .then(response => response.json)
+ .then(data => console.log(data));
+ } else {
+ alert('๋ด์ฉ์ ์์ฑ์ฃผ์ธ์.');
+ }
+ };
+
+ return (
+ <div className="userBox">
+ <div className="userWrap">
+ <img className="user" src="/images/user.png" alt="userPicture" />
+ <div className="contentBox">
+ <div className="userName">NAME</div>
+ <textarea
+ onChange={event => handleText(event.target.value)}
+ className="textArea"
+ cols="80"
+ rows="30"
+ type="text"
+ value={comment}
+ />
+
+ <div className="buttonWrap">
+ <Button
+ className="customButton cancelButton"
+ buttonName="์ทจ์"
+ active={cancel}
+ />
+ <Button
+ className="customButton addButton"
+ buttonName="๊ฒ์"
+ active={posting}
+ />
+ </div>
+ </div>
+ </div>
+ </div>
+ );
+};
+export default PostAdd;
|
JavaScript
|
๋ฉํ ๋ฆฌ๋ทฐ ๋ฐ์ ์๋ฃ
|
@@ -1,14 +1,77 @@
-import React from "react";
-import "./PostAdd.scss";
+import React, { useState } from 'react';
+import { useNavigate } from 'react-router-dom';
+import './PostAdd.scss';
+import { Button } from '../PostAdd/components/Post.jsx';
const PostAdd = () => {
+ const [comment, setComment] = useState('');
-return(
- <div className="postAdd">
- <div>๋ก๊ทธ์ธ</div>
- </div>
-);
+ const navigate = useNavigate();
-};
+ const handleText = value => {
+ setComment(value);
+ };
+ console.log(handleText);
+
+ const cancel = () => {
+ const confirmed = window.confirm(
+ '์ ์ผ์ ๊ธ์ ์ทจ์ํ๊ณ post-list๋ก ๋์ด๊ฐ๊ฒ ์ต๋๊น?',
+ );
+ if (confirmed) {
+ navigate('/post-list');
+ }
+ };
+
+ const posting = () => {
+ if (comment.length >= 1) {
+ navigate('/post-list');
-export default PostAdd;
\ No newline at end of file
+ fetch({
+ method: 'POST',
+ headers: {
+ 'Content-Type': 'application/json;charset=utf-8',
+ },
+ body: JSON.stringify({
+ content: '์ ์ ๊ฐ ์์ฑํ ๊ธ',
+ }),
+ })
+ .then(response => response.json)
+ .then(data => console.log(data));
+ } else {
+ alert('๋ด์ฉ์ ์์ฑ์ฃผ์ธ์.');
+ }
+ };
+
+ return (
+ <div className="userBox">
+ <div className="userWrap">
+ <img className="user" src="/images/user.png" alt="userPicture" />
+ <div className="contentBox">
+ <div className="userName">NAME</div>
+ <textarea
+ onChange={event => handleText(event.target.value)}
+ className="textArea"
+ cols="80"
+ rows="30"
+ type="text"
+ value={comment}
+ />
+
+ <div className="buttonWrap">
+ <Button
+ className="customButton cancelButton"
+ buttonName="์ทจ์"
+ active={cancel}
+ />
+ <Button
+ className="customButton addButton"
+ buttonName="๊ฒ์"
+ active={posting}
+ />
+ </div>
+ </div>
+ </div>
+ </div>
+ );
+};
+export default PostAdd;
|
JavaScript
|
๋ฉํ ๋ฆฌ๋ทฐ ๋ฐ์์๋ฃ
|
@@ -1,14 +1,77 @@
-import React from "react";
-import "./PostAdd.scss";
+import React, { useState } from 'react';
+import { useNavigate } from 'react-router-dom';
+import './PostAdd.scss';
+import { Button } from '../PostAdd/components/Post.jsx';
const PostAdd = () => {
+ const [comment, setComment] = useState('');
-return(
- <div className="postAdd">
- <div>๋ก๊ทธ์ธ</div>
- </div>
-);
+ const navigate = useNavigate();
-};
+ const handleText = value => {
+ setComment(value);
+ };
+ console.log(handleText);
+
+ const cancel = () => {
+ const confirmed = window.confirm(
+ '์ ์ผ์ ๊ธ์ ์ทจ์ํ๊ณ post-list๋ก ๋์ด๊ฐ๊ฒ ์ต๋๊น?',
+ );
+ if (confirmed) {
+ navigate('/post-list');
+ }
+ };
+
+ const posting = () => {
+ if (comment.length >= 1) {
+ navigate('/post-list');
-export default PostAdd;
\ No newline at end of file
+ fetch({
+ method: 'POST',
+ headers: {
+ 'Content-Type': 'application/json;charset=utf-8',
+ },
+ body: JSON.stringify({
+ content: '์ ์ ๊ฐ ์์ฑํ ๊ธ',
+ }),
+ })
+ .then(response => response.json)
+ .then(data => console.log(data));
+ } else {
+ alert('๋ด์ฉ์ ์์ฑ์ฃผ์ธ์.');
+ }
+ };
+
+ return (
+ <div className="userBox">
+ <div className="userWrap">
+ <img className="user" src="/images/user.png" alt="userPicture" />
+ <div className="contentBox">
+ <div className="userName">NAME</div>
+ <textarea
+ onChange={event => handleText(event.target.value)}
+ className="textArea"
+ cols="80"
+ rows="30"
+ type="text"
+ value={comment}
+ />
+
+ <div className="buttonWrap">
+ <Button
+ className="customButton cancelButton"
+ buttonName="์ทจ์"
+ active={cancel}
+ />
+ <Button
+ className="customButton addButton"
+ buttonName="๊ฒ์"
+ active={posting}
+ />
+ </div>
+ </div>
+ </div>
+ </div>
+ );
+};
+export default PostAdd;
|
JavaScript
|
alt ์์ฑ์ ํ๋ฉด์ ์ด๋ฏธ์ง๊ฐ ํ์๋์ง ์์๋ ์ฌ์ฉ์๊ฐ ์ ์ ์๋๋ก ๋์ฒด ํ
์คํธ๋ฅผ ์ ๊ณตํ๋ ์ญํ ์ ํ๊ธฐ ๋๋ฌธ์ alt ๊ฐ์ userPicture๋ฅผ ๋ฃ๊ฒ ์๋๋ค..
|
@@ -0,0 +1,79 @@
+.userBox {
+ margin: 20px;
+ gap: 0 24px;
+ display: flex;
+ justify-content: center;
+ flex-direction: column;
+
+ .userWrap {
+ display: flex;
+ flex-direction: row;
+ justify-content: center;
+
+ .user {
+ width: 50px;
+ height: 50px;
+ border-radius: 50%;
+ }
+
+ .contentBox {
+ display: flex;
+ flex-direction: column;
+ gap: 10px;
+ margin-left: 20px;
+
+ .userName {
+ font-size: 20px;
+ font-weight: 700;
+ }
+
+ .textArea {
+ padding: 10px;
+ border-radius: 6px;
+ border: 1px solid var(--grey-88, #e0e0e0);
+ background: var(--white, #fff);
+ resize: none;
+ transition: border-color 0.3s;
+ outline: none;
+ }
+ .textArea:hover {
+ border-color: var(--gray, #999999);
+ }
+
+ .buttonWrap {
+ justify-content: space-between;
+ display: flex;
+
+ .customButton {
+ width: 120px;
+ height: 50px;
+ border-radius: 6px;
+ }
+
+ .cancelButton {
+ border: 1px solid var(--blue, #2d71f7);
+ background: var(--white, #fff);
+ color: var(--blue, #2d71f7);
+ cursor: pointer;
+ }
+ .cancelButton:hover {
+ border: 1px solid var(--navy, #083e7f);
+ background: var(--white, #fff);
+ color: var(--navy, #083e7f);
+ }
+
+ .addButton {
+ border: none;
+ background: var(--white, #2d71f7);
+ color: var(--white, #fff);
+ cursor: pointer;
+ }
+ .addButton:hover {
+ border: none;
+ background: var(--blue, #083e7f);
+ color: var(--white, #fff);
+ }
+ }
+ }
+ }
+}
|
Unknown
|
๋ฉํ ๋ฆฌ๋ทฐ ๋ฐ์ ์๋ฃ
|
@@ -1,14 +1,77 @@
-import React from "react";
-import "./PostAdd.scss";
+import React, { useState } from 'react';
+import { useNavigate } from 'react-router-dom';
+import './PostAdd.scss';
+import { Button } from '../PostAdd/components/Post.jsx';
const PostAdd = () => {
+ const [comment, setComment] = useState('');
-return(
- <div className="postAdd">
- <div>๋ก๊ทธ์ธ</div>
- </div>
-);
+ const navigate = useNavigate();
-};
+ const handleText = value => {
+ setComment(value);
+ };
+ console.log(handleText);
+
+ const cancel = () => {
+ const confirmed = window.confirm(
+ '์ ์ผ์ ๊ธ์ ์ทจ์ํ๊ณ post-list๋ก ๋์ด๊ฐ๊ฒ ์ต๋๊น?',
+ );
+ if (confirmed) {
+ navigate('/post-list');
+ }
+ };
+
+ const posting = () => {
+ if (comment.length >= 1) {
+ navigate('/post-list');
-export default PostAdd;
\ No newline at end of file
+ fetch({
+ method: 'POST',
+ headers: {
+ 'Content-Type': 'application/json;charset=utf-8',
+ },
+ body: JSON.stringify({
+ content: '์ ์ ๊ฐ ์์ฑํ ๊ธ',
+ }),
+ })
+ .then(response => response.json)
+ .then(data => console.log(data));
+ } else {
+ alert('๋ด์ฉ์ ์์ฑ์ฃผ์ธ์.');
+ }
+ };
+
+ return (
+ <div className="userBox">
+ <div className="userWrap">
+ <img className="user" src="/images/user.png" alt="userPicture" />
+ <div className="contentBox">
+ <div className="userName">NAME</div>
+ <textarea
+ onChange={event => handleText(event.target.value)}
+ className="textArea"
+ cols="80"
+ rows="30"
+ type="text"
+ value={comment}
+ />
+
+ <div className="buttonWrap">
+ <Button
+ className="customButton cancelButton"
+ buttonName="์ทจ์"
+ active={cancel}
+ />
+ <Button
+ className="customButton addButton"
+ buttonName="๊ฒ์"
+ active={posting}
+ />
+ </div>
+ </div>
+ </div>
+ </div>
+ );
+};
+export default PostAdd;
|
JavaScript
|
๋ต!
|
@@ -1,14 +1,77 @@
-import React from "react";
-import "./PostAdd.scss";
+import React, { useState } from 'react';
+import { useNavigate } from 'react-router-dom';
+import './PostAdd.scss';
+import { Button } from '../PostAdd/components/Post.jsx';
const PostAdd = () => {
+ const [comment, setComment] = useState('');
-return(
- <div className="postAdd">
- <div>๋ก๊ทธ์ธ</div>
- </div>
-);
+ const navigate = useNavigate();
-};
+ const handleText = value => {
+ setComment(value);
+ };
+ console.log(handleText);
+
+ const cancel = () => {
+ const confirmed = window.confirm(
+ '์ ์ผ์ ๊ธ์ ์ทจ์ํ๊ณ post-list๋ก ๋์ด๊ฐ๊ฒ ์ต๋๊น?',
+ );
+ if (confirmed) {
+ navigate('/post-list');
+ }
+ };
+
+ const posting = () => {
+ if (comment.length >= 1) {
+ navigate('/post-list');
-export default PostAdd;
\ No newline at end of file
+ fetch({
+ method: 'POST',
+ headers: {
+ 'Content-Type': 'application/json;charset=utf-8',
+ },
+ body: JSON.stringify({
+ content: '์ ์ ๊ฐ ์์ฑํ ๊ธ',
+ }),
+ })
+ .then(response => response.json)
+ .then(data => console.log(data));
+ } else {
+ alert('๋ด์ฉ์ ์์ฑ์ฃผ์ธ์.');
+ }
+ };
+
+ return (
+ <div className="userBox">
+ <div className="userWrap">
+ <img className="user" src="/images/user.png" alt="userPicture" />
+ <div className="contentBox">
+ <div className="userName">NAME</div>
+ <textarea
+ onChange={event => handleText(event.target.value)}
+ className="textArea"
+ cols="80"
+ rows="30"
+ type="text"
+ value={comment}
+ />
+
+ <div className="buttonWrap">
+ <Button
+ className="customButton cancelButton"
+ buttonName="์ทจ์"
+ active={cancel}
+ />
+ <Button
+ className="customButton addButton"
+ buttonName="๊ฒ์"
+ active={posting}
+ />
+ </div>
+ </div>
+ </div>
+ </div>
+ );
+};
+export default PostAdd;
|
JavaScript
|
๋ฉํ ๋ฆฌ๋ทฐ ๋ฐ์ ์๋ฃ(?)
|
@@ -0,0 +1,37 @@
+package nextstep.authentication;
+
+public class UsernamePasswordAuthenticationToken implements Authentication {
+
+ private final String principal;
+ private final String credentials;
+ private boolean authenticated;
+
+ public UsernamePasswordAuthenticationToken(String principal, String credentials, boolean authenticated) {
+ this.principal = principal;
+ this.credentials = credentials;
+ this.authenticated = authenticated;
+ }
+
+ public static UsernamePasswordAuthenticationToken authenticated(String principal, String credentials) {
+ return new UsernamePasswordAuthenticationToken(principal, credentials, true);
+ }
+
+ public static UsernamePasswordAuthenticationToken unauthenticated(String principal, String credentials) {
+ return new UsernamePasswordAuthenticationToken(principal, credentials, false);
+ }
+
+ @Override
+ public String getPrincipal() {
+ return principal;
+ }
+
+ @Override
+ public String getCredentials() {
+ return credentials;
+ }
+
+ @Override
+ public boolean isAuthenticated() {
+ return authenticated;
+ }
+}
|
Java
|
`AuthenticationToken`์ ๋ง๊ทธ๋๋ก ์ธ์ฆ๋ ํ ํฐ์ด๊ธฐ ๋๋ฌธ์ `UserDetails`๋ ํ์๋ก ํ์ง ์์ต๋๋ค.
`UserDetails`์ ์ฌ์ฉ์ฒ๋ฅผ ์๊ฐํด๋ณด๋ฉด, ์ต์ด ์ธ์
๋ ์ ์ ๊ฐ ์ธ์ฆ์ด ๊ฐ๋ฅํ ์ ์ ์ธ์ง ํ์ธํ๊ธฐ ์ํด์ ์ฌ์ฉ๋ ๋ฟ์ด์ง ์ด๋ฏธ ์ธ์ฆ๋ ํ ํฐ์๋ ๋ณ๋๋ก `UserDetails`๋ฅผ ์ฌ์ฉํ์ง ์์ต๋๋ค. ํ์ฌ ๋ง๋ค์ด์ฃผ์ ์ฝ๋์๋ ์ฌ์ฉ์ฒ๊ฐ ์๊ธฐ๋ ํ๊ตฌ์.
|
@@ -0,0 +1,37 @@
+package nextstep.authentication;
+
+public class UsernamePasswordAuthenticationToken implements Authentication {
+
+ private final String principal;
+ private final String credentials;
+ private boolean authenticated;
+
+ public UsernamePasswordAuthenticationToken(String principal, String credentials, boolean authenticated) {
+ this.principal = principal;
+ this.credentials = credentials;
+ this.authenticated = authenticated;
+ }
+
+ public static UsernamePasswordAuthenticationToken authenticated(String principal, String credentials) {
+ return new UsernamePasswordAuthenticationToken(principal, credentials, true);
+ }
+
+ public static UsernamePasswordAuthenticationToken unauthenticated(String principal, String credentials) {
+ return new UsernamePasswordAuthenticationToken(principal, credentials, false);
+ }
+
+ @Override
+ public String getPrincipal() {
+ return principal;
+ }
+
+ @Override
+ public String getCredentials() {
+ return credentials;
+ }
+
+ @Override
+ public boolean isAuthenticated() {
+ return authenticated;
+ }
+}
|
Java
|
์ฌ์ฉ๋์ง ์๋ ๋ฉ์๋๋ค์ ๋ชจ๋ ์ ๊ฑฐํด์ฃผ์๋ฉด ์ข์ ๊ฒ ๊ฐ์์ :)
|
@@ -0,0 +1,29 @@
+package nextstep.authentication;
+
+import nextstep.authentication.exception.AuthenticationException;
+import nextstep.authentication.exception.ProviderNotFoundException;
+
+import java.util.List;
+import java.util.Objects;
+
+public class ProviderManager implements AuthenticationManager {
+
+ private final List<AuthenticationProvider> providers;
+
+ public ProviderManager(List<AuthenticationProvider> providers) {
+ this.providers = providers;
+ }
+
+ @Override
+ public Authentication authenticate(Authentication authentication) throws AuthenticationException {
+
+ Class<? extends Authentication> target = authentication.getClass();
+
+ return providers.stream()
+ .filter(provider -> provider.supports(target))
+ .map(provider -> provider.authenticate(authentication))
+ .filter(Objects::nonNull)
+ .findAny()
+ .orElseThrow(() -> new ProviderNotFoundException(String.format("No AuthenticationProvider found for %s", target.getName())));
+ }
+}
|
Java
|
`toTest`๋ณด๋ค ์ ์ ํ ๋ค์ด๋ฐ์ ์ด๋จ๊น์?
|
@@ -0,0 +1,29 @@
+package nextstep.authentication;
+
+import nextstep.authentication.exception.AuthenticationException;
+import nextstep.authentication.exception.ProviderNotFoundException;
+
+import java.util.List;
+import java.util.Objects;
+
+public class ProviderManager implements AuthenticationManager {
+
+ private final List<AuthenticationProvider> providers;
+
+ public ProviderManager(List<AuthenticationProvider> providers) {
+ this.providers = providers;
+ }
+
+ @Override
+ public Authentication authenticate(Authentication authentication) throws AuthenticationException {
+
+ Class<? extends Authentication> target = authentication.getClass();
+
+ return providers.stream()
+ .filter(provider -> provider.supports(target))
+ .map(provider -> provider.authenticate(authentication))
+ .filter(Objects::nonNull)
+ .findAny()
+ .orElseThrow(() -> new ProviderNotFoundException(String.format("No AuthenticationProvider found for %s", target.getName())));
+ }
+}
|
Java
|
```suggestion
return providers.stream()
.filter(provider -> provider.supports(toTest))
.map(provider -> provider.authenticate(authentication))
.filter(Objects::nonNull)
.findAny()
.orElseThrow();
```
๋ก ํํ๋ ์ ์์ ๊ฒ ๊ฐ๋ค์ :)
|
@@ -0,0 +1,68 @@
+package nextstep.authentication.filter;
+
+import jakarta.servlet.Filter;
+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.authentication.Authentication;
+import nextstep.authentication.AuthenticationManager;
+import nextstep.authentication.UsernamePasswordAuthenticationToken;
+import nextstep.authentication.context.SecurityContextHolder;
+import nextstep.authentication.exception.AuthenticationException;
+import nextstep.authentication.util.matcher.MvcRequestMatcher;
+import org.springframework.http.HttpMethod;
+
+import java.io.IOException;
+
+public class FormLoginAuthenticationFilter implements Filter {
+
+ private static final MvcRequestMatcher DEFAULT_REQUEST_MATCHER = new MvcRequestMatcher(HttpMethod.POST, "/login");
+
+ private final AuthenticationManager authenticationManager;
+
+ public FormLoginAuthenticationFilter(AuthenticationManager authenticationManager) {
+ this.authenticationManager = authenticationManager;
+ }
+
+ @Override
+ public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
+ if (!DEFAULT_REQUEST_MATCHER.matches((HttpServletRequest) servletRequest)) {
+ filterChain.doFilter(servletRequest, servletResponse);
+ return;
+ }
+
+ HttpServletRequest request = (HttpServletRequest) servletRequest;
+ HttpServletResponse response = (HttpServletResponse) servletResponse;
+
+ try {
+
+ Authentication authenticationResult = attemptAuthentication(request, response);
+ if (authenticationResult == null) {
+ filterChain.doFilter(servletRequest, servletResponse);
+ return;
+ }
+
+ SecurityContextHolder.getContext().setAuthentication(authenticationResult);
+
+ } catch (Exception e) {
+ SecurityContextHolder.clearContext();
+ response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
+
+ return;
+ }
+
+ filterChain.doFilter(servletRequest, servletResponse);
+ }
+
+ private Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {
+
+ String username = request.getParameter("username");
+ String password = request.getParameter("password");
+ UsernamePasswordAuthenticationToken authRequest = UsernamePasswordAuthenticationToken.unauthenticated(username, password);
+
+ return authenticationManager.authenticate(authRequest);
+ }
+}
|
Java
|
์ธ์ฆ์ด null์ผ ๋ ๋ฐ๋ก returnํ๋ฉด ํํฐ ๋์์ด ์ด๋๋ก ํฅํ ๊น์?
|
@@ -0,0 +1,85 @@
+package nextstep.authentication.filter;
+
+import jakarta.servlet.Filter;
+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.authentication.Authentication;
+import nextstep.authentication.AuthenticationManager;
+import nextstep.authentication.UsernamePasswordAuthenticationToken;
+import nextstep.authentication.context.SecurityContextHolder;
+import nextstep.authentication.exception.AuthenticationException;
+import nextstep.authentication.util.Base64Convertor;
+import nextstep.authentication.util.matcher.MvcRequestMatcher;
+import org.springframework.http.HttpMethod;
+
+import java.io.IOException;
+
+public class BasicAuthenticationFilter implements Filter {
+
+ private static final MvcRequestMatcher DEFAULT_REQUEST_MATCHER = new MvcRequestMatcher(HttpMethod.GET, "/members");
+
+ private final AuthenticationManager authenticationManager;
+
+ public BasicAuthenticationFilter(AuthenticationManager authenticationManager) {
+ this.authenticationManager = authenticationManager;
+ }
+
+ @Override
+ public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
+ if (!DEFAULT_REQUEST_MATCHER.matches((HttpServletRequest) servletRequest)) {
+ filterChain.doFilter(servletRequest, servletResponse);
+ return;
+ }
+
+ HttpServletRequest request = (HttpServletRequest) servletRequest;
+ HttpServletResponse response = (HttpServletResponse) servletResponse;
+
+ try {
+
+ Authentication authenticationResult = attemptAuthentication(request, response);
+ if (authenticationResult == null) {
+ filterChain.doFilter(servletRequest, servletResponse);
+ return;
+ }
+
+ SecurityContextHolder.getContext().setAuthentication(authenticationResult);
+
+ } catch (Exception e) {
+ SecurityContextHolder.clearContext();
+ response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
+
+ return;
+ }
+
+ filterChain.doFilter(servletRequest, servletResponse);
+ }
+
+ private Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {
+
+ UsernamePasswordAuthenticationToken authRequest;
+
+ var securityContext = SecurityContextHolder.getContext();
+
+ if (securityContext.getAuthentication() == null) {
+
+ String authorization = request.getHeader("Authorization");
+ String credentials = authorization.split(" ")[1];
+ String decodedString = Base64Convertor.decode(credentials);
+ String[] usernameAndPassword = decodedString.split(":");
+
+ String username = usernameAndPassword[0];
+ String password = usernameAndPassword[1];
+
+ authRequest = UsernamePasswordAuthenticationToken.unauthenticated(username, password);
+
+ } else {
+ authRequest = (UsernamePasswordAuthenticationToken) securityContext.getAuthentication();
+ }
+
+ return authenticationManager.authenticate(authRequest);
+ }
+}
|
Java
|
`attempAuthentication`ํ๋ ๋์์ request์์ ํค๋๋ฅผ ๋ณด๊ณ ํ ํฐ์ ์ฝ์ด `authenticationManager.authenticate`๋ฅผ ์คํํ๋ ๊ณผ์ ์ธ๋ฐ์. ์ด ๊ณผ์ ์์ `SecurityContext`๋ ์ฌ์ค ๋ถํ์ํ ๋์์
๋๋ค.
ํ์ฌ ํํฐ์์์ ๋์์
1. ํค๋์ ์ํ๋ ๊ฐ์ ๋ฝ์๋ด์ด ํ ํฐ์ ์์ฑํ๋ค.
2. ํ ํฐ์ ๊ฐ์ง๊ณ `AuthenticationManager.authenticate`๋ฅผ ์คํํ๋ค.
3. ์ฑ๊ณตํ๋ฉด SecurityContext์ ์ธ์ฆ ๊ฐ์ ๋ฃ๋๋ค.
4. ์คํจํ๋ฉด ์ด๊ธฐํํ๊ณ 401์ ๋ฐํํ๋ค.
์
๋๋ค. ์ฆ, `SecurityContext`๋ฅผ ์กฐ์ํ๋ ํ์๋ ๋ชจ๋ ์ธ์ฆ ๊ณผ์ ์ด ๋๋๊ณ ์ฑ๊ณต๊ณผ ์คํจ์ ๋ฐ๋ฅธ ํ์์ด์ง ๊ทธ ์ค๊ฐ์ `SecurityContext`๋ฅผ ๊ฑด๋ค์ง ์์์.
|
@@ -0,0 +1,38 @@
+package nextstep.authentication.context;
+
+import jakarta.servlet.http.HttpServletRequest;
+import jakarta.servlet.http.HttpServletResponse;
+import jakarta.servlet.http.HttpSession;
+
+public class HttpSessionSecurityContextRepository implements SecurityContextRepository {
+
+ private static final String SPRING_SECURITY_CONTEXT_KEY = "SPRING_SECURITY_CONTEXT";
+
+ @Override
+ public SecurityContext loadContext(HttpServletRequest request) {
+
+ HttpSession httpSession = request.getSession(false);
+ if (httpSession == null) {
+ return null;
+ }
+
+ return (SecurityContext) httpSession.getAttribute(SPRING_SECURITY_CONTEXT_KEY);
+ }
+
+ @Override
+ public void saveContext(SecurityContext context, HttpServletRequest request, HttpServletResponse response) {
+
+ // SecurityContext๊ฐ null์ด๊ฑฐ๋ ์ธ์ฆ์ ๋ณด๊ฐ ์์ผ๋ฉด ์ธ์
์์ ์ ๊ฑฐ
+ if (context == null || context.getAuthentication() == null) {
+ HttpSession session = request.getSession(false);
+ if (session != null) {
+ session.removeAttribute(SPRING_SECURITY_CONTEXT_KEY);
+ }
+ return;
+ }
+
+ // ์ธ์
์ด ์์ผ๋ฉด ์์ฑํ๊ณ , SecurityContext๋ฅผ ์ ์ฅ
+ HttpSession session = request.getSession(true);
+ session.setAttribute(SPRING_SECURITY_CONTEXT_KEY, context);
+ }
+}
|
Java
|
๋ก์ง์ด ๋ณต์กํ ํ์ ์์ด `loadContext`๋ ๋จ์ํ
1. request.getSession์ ๊ฐ์ด null์ด๋ฉด null์ ๋ฐํํ๋ค.
2. httpSession.getAttribute(SPRING_SECURITY_CONTEXT_KEY)๋ฅผ ๋ฐํํ๋ค.
๋ฉด ๋ฉ๋๋ค. `readSecurityContextFromSession`์ ๋ถ๊ธฐ๋ ์ ๊ณผ์ ์ผ๋ก ์ด๋ฏธ ๋์ผํ๊ฒ ๋ก์ง์ด ๊ตฌ์ฑ๋ ์ ์์ด ๋ณ๋๋ก ํ์ ์์ด๋ณด์ฌ์.
|
@@ -0,0 +1,29 @@
+package nextstep.authentication;
+
+import nextstep.authentication.exception.AuthenticationException;
+import nextstep.authentication.exception.ProviderNotFoundException;
+
+import java.util.List;
+import java.util.Objects;
+
+public class ProviderManager implements AuthenticationManager {
+
+ private final List<AuthenticationProvider> providers;
+
+ public ProviderManager(List<AuthenticationProvider> providers) {
+ this.providers = providers;
+ }
+
+ @Override
+ public Authentication authenticate(Authentication authentication) throws AuthenticationException {
+
+ Class<? extends Authentication> target = authentication.getClass();
+
+ return providers.stream()
+ .filter(provider -> provider.supports(target))
+ .map(provider -> provider.authenticate(authentication))
+ .filter(Objects::nonNull)
+ .findAny()
+ .orElseThrow(() -> new ProviderNotFoundException(String.format("No AuthenticationProvider found for %s", target.getName())));
+ }
+}
|
Java
|
target์ผ๋ก ๋ณ์๋ช
์ ์์ ํ์ต๋๋ค!
|
@@ -0,0 +1,68 @@
+package nextstep.authentication.filter;
+
+import jakarta.servlet.Filter;
+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.authentication.Authentication;
+import nextstep.authentication.AuthenticationManager;
+import nextstep.authentication.UsernamePasswordAuthenticationToken;
+import nextstep.authentication.context.SecurityContextHolder;
+import nextstep.authentication.exception.AuthenticationException;
+import nextstep.authentication.util.matcher.MvcRequestMatcher;
+import org.springframework.http.HttpMethod;
+
+import java.io.IOException;
+
+public class FormLoginAuthenticationFilter implements Filter {
+
+ private static final MvcRequestMatcher DEFAULT_REQUEST_MATCHER = new MvcRequestMatcher(HttpMethod.POST, "/login");
+
+ private final AuthenticationManager authenticationManager;
+
+ public FormLoginAuthenticationFilter(AuthenticationManager authenticationManager) {
+ this.authenticationManager = authenticationManager;
+ }
+
+ @Override
+ public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
+ if (!DEFAULT_REQUEST_MATCHER.matches((HttpServletRequest) servletRequest)) {
+ filterChain.doFilter(servletRequest, servletResponse);
+ return;
+ }
+
+ HttpServletRequest request = (HttpServletRequest) servletRequest;
+ HttpServletResponse response = (HttpServletResponse) servletResponse;
+
+ try {
+
+ Authentication authenticationResult = attemptAuthentication(request, response);
+ if (authenticationResult == null) {
+ filterChain.doFilter(servletRequest, servletResponse);
+ return;
+ }
+
+ SecurityContextHolder.getContext().setAuthentication(authenticationResult);
+
+ } catch (Exception e) {
+ SecurityContextHolder.clearContext();
+ response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
+
+ return;
+ }
+
+ filterChain.doFilter(servletRequest, servletResponse);
+ }
+
+ private Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {
+
+ String username = request.getParameter("username");
+ String password = request.getParameter("password");
+ UsernamePasswordAuthenticationToken authRequest = UsernamePasswordAuthenticationToken.unauthenticated(username, password);
+
+ return authenticationManager.authenticate(authRequest);
+ }
+}
|
Java
|
์ธ์ฆ์ด null์ผ ๋ ๋ค์ ํํฐ๋ก ์ด๋ํ ์ ์๋๋ก `filterChain.doFilter(servletRequest, servletResponse);` ์ฝ๋๋ฅผ ์ถ๊ฐํ์ต๋๋ค!
|
@@ -0,0 +1,85 @@
+package nextstep.authentication.filter;
+
+import jakarta.servlet.Filter;
+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.authentication.Authentication;
+import nextstep.authentication.AuthenticationManager;
+import nextstep.authentication.UsernamePasswordAuthenticationToken;
+import nextstep.authentication.context.SecurityContextHolder;
+import nextstep.authentication.exception.AuthenticationException;
+import nextstep.authentication.util.Base64Convertor;
+import nextstep.authentication.util.matcher.MvcRequestMatcher;
+import org.springframework.http.HttpMethod;
+
+import java.io.IOException;
+
+public class BasicAuthenticationFilter implements Filter {
+
+ private static final MvcRequestMatcher DEFAULT_REQUEST_MATCHER = new MvcRequestMatcher(HttpMethod.GET, "/members");
+
+ private final AuthenticationManager authenticationManager;
+
+ public BasicAuthenticationFilter(AuthenticationManager authenticationManager) {
+ this.authenticationManager = authenticationManager;
+ }
+
+ @Override
+ public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
+ if (!DEFAULT_REQUEST_MATCHER.matches((HttpServletRequest) servletRequest)) {
+ filterChain.doFilter(servletRequest, servletResponse);
+ return;
+ }
+
+ HttpServletRequest request = (HttpServletRequest) servletRequest;
+ HttpServletResponse response = (HttpServletResponse) servletResponse;
+
+ try {
+
+ Authentication authenticationResult = attemptAuthentication(request, response);
+ if (authenticationResult == null) {
+ filterChain.doFilter(servletRequest, servletResponse);
+ return;
+ }
+
+ SecurityContextHolder.getContext().setAuthentication(authenticationResult);
+
+ } catch (Exception e) {
+ SecurityContextHolder.clearContext();
+ response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
+
+ return;
+ }
+
+ filterChain.doFilter(servletRequest, servletResponse);
+ }
+
+ private Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {
+
+ UsernamePasswordAuthenticationToken authRequest;
+
+ var securityContext = SecurityContextHolder.getContext();
+
+ if (securityContext.getAuthentication() == null) {
+
+ String authorization = request.getHeader("Authorization");
+ String credentials = authorization.split(" ")[1];
+ String decodedString = Base64Convertor.decode(credentials);
+ String[] usernameAndPassword = decodedString.split(":");
+
+ String username = usernameAndPassword[0];
+ String password = usernameAndPassword[1];
+
+ authRequest = UsernamePasswordAuthenticationToken.unauthenticated(username, password);
+
+ } else {
+ authRequest = (UsernamePasswordAuthenticationToken) securityContext.getAuthentication();
+ }
+
+ return authenticationManager.authenticate(authRequest);
+ }
+}
|
Java
|
SecurityContext๋ฅผ ์ฌ์ฉํ์ง ์์ผ๋ฉด FormLoginTest.login_after_members() ํ
์คํธ๊ฐ ํต๊ณผํ์ง ์๋๋ฐ ํ
์คํธ๋ฅผ ์์ ํ๋๊ฒ ์ข์๊น์?
|
@@ -0,0 +1,85 @@
+package nextstep.authentication.filter;
+
+import jakarta.servlet.Filter;
+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.authentication.Authentication;
+import nextstep.authentication.AuthenticationManager;
+import nextstep.authentication.UsernamePasswordAuthenticationToken;
+import nextstep.authentication.context.SecurityContextHolder;
+import nextstep.authentication.exception.AuthenticationException;
+import nextstep.authentication.util.Base64Convertor;
+import nextstep.authentication.util.matcher.MvcRequestMatcher;
+import org.springframework.http.HttpMethod;
+
+import java.io.IOException;
+
+public class BasicAuthenticationFilter implements Filter {
+
+ private static final MvcRequestMatcher DEFAULT_REQUEST_MATCHER = new MvcRequestMatcher(HttpMethod.GET, "/members");
+
+ private final AuthenticationManager authenticationManager;
+
+ public BasicAuthenticationFilter(AuthenticationManager authenticationManager) {
+ this.authenticationManager = authenticationManager;
+ }
+
+ @Override
+ public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
+ if (!DEFAULT_REQUEST_MATCHER.matches((HttpServletRequest) servletRequest)) {
+ filterChain.doFilter(servletRequest, servletResponse);
+ return;
+ }
+
+ HttpServletRequest request = (HttpServletRequest) servletRequest;
+ HttpServletResponse response = (HttpServletResponse) servletResponse;
+
+ try {
+
+ Authentication authenticationResult = attemptAuthentication(request, response);
+ if (authenticationResult == null) {
+ filterChain.doFilter(servletRequest, servletResponse);
+ return;
+ }
+
+ SecurityContextHolder.getContext().setAuthentication(authenticationResult);
+
+ } catch (Exception e) {
+ SecurityContextHolder.clearContext();
+ response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
+
+ return;
+ }
+
+ filterChain.doFilter(servletRequest, servletResponse);
+ }
+
+ private Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {
+
+ UsernamePasswordAuthenticationToken authRequest;
+
+ var securityContext = SecurityContextHolder.getContext();
+
+ if (securityContext.getAuthentication() == null) {
+
+ String authorization = request.getHeader("Authorization");
+ String credentials = authorization.split(" ")[1];
+ String decodedString = Base64Convertor.decode(credentials);
+ String[] usernameAndPassword = decodedString.split(":");
+
+ String username = usernameAndPassword[0];
+ String password = usernameAndPassword[1];
+
+ authRequest = UsernamePasswordAuthenticationToken.unauthenticated(username, password);
+
+ } else {
+ authRequest = (UsernamePasswordAuthenticationToken) securityContext.getAuthentication();
+ }
+
+ return authenticationManager.authenticate(authRequest);
+ }
+}
|
Java
|
SecurityContext๋ฅผ ์ฌ์ฉํ์ง ์์ผ๋ ค๊ณ ์๋์ฒ๋ผ ์์ ์ ์๋ํ์์ต๋๋ค.
```java
private Authentication attemptAuthentication(HttpServletRequest request) throws AuthenticationException {
String authorization = request.getHeader("Authorization");
String credentials = authorization.split(" ")[1];
String decodedString = Base64Convertor.decode(credentials);
String[] usernameAndPassword = decodedString.split(":");
String username = usernameAndPassword[0];
String password = usernameAndPassword[1];
UsernamePasswordAuthenticationToken authRequest = UsernamePasswordAuthenticationToken.unauthenticated(username, password);
return authenticationManager.authenticate(authRequest);
}
```
|
@@ -0,0 +1,85 @@
+package nextstep.authentication.filter;
+
+import jakarta.servlet.Filter;
+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.authentication.Authentication;
+import nextstep.authentication.AuthenticationManager;
+import nextstep.authentication.UsernamePasswordAuthenticationToken;
+import nextstep.authentication.context.SecurityContextHolder;
+import nextstep.authentication.exception.AuthenticationException;
+import nextstep.authentication.util.Base64Convertor;
+import nextstep.authentication.util.matcher.MvcRequestMatcher;
+import org.springframework.http.HttpMethod;
+
+import java.io.IOException;
+
+public class BasicAuthenticationFilter implements Filter {
+
+ private static final MvcRequestMatcher DEFAULT_REQUEST_MATCHER = new MvcRequestMatcher(HttpMethod.GET, "/members");
+
+ private final AuthenticationManager authenticationManager;
+
+ public BasicAuthenticationFilter(AuthenticationManager authenticationManager) {
+ this.authenticationManager = authenticationManager;
+ }
+
+ @Override
+ public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
+ if (!DEFAULT_REQUEST_MATCHER.matches((HttpServletRequest) servletRequest)) {
+ filterChain.doFilter(servletRequest, servletResponse);
+ return;
+ }
+
+ HttpServletRequest request = (HttpServletRequest) servletRequest;
+ HttpServletResponse response = (HttpServletResponse) servletResponse;
+
+ try {
+
+ Authentication authenticationResult = attemptAuthentication(request, response);
+ if (authenticationResult == null) {
+ filterChain.doFilter(servletRequest, servletResponse);
+ return;
+ }
+
+ SecurityContextHolder.getContext().setAuthentication(authenticationResult);
+
+ } catch (Exception e) {
+ SecurityContextHolder.clearContext();
+ response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
+
+ return;
+ }
+
+ filterChain.doFilter(servletRequest, servletResponse);
+ }
+
+ private Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {
+
+ UsernamePasswordAuthenticationToken authRequest;
+
+ var securityContext = SecurityContextHolder.getContext();
+
+ if (securityContext.getAuthentication() == null) {
+
+ String authorization = request.getHeader("Authorization");
+ String credentials = authorization.split(" ")[1];
+ String decodedString = Base64Convertor.decode(credentials);
+ String[] usernameAndPassword = decodedString.split(":");
+
+ String username = usernameAndPassword[0];
+ String password = usernameAndPassword[1];
+
+ authRequest = UsernamePasswordAuthenticationToken.unauthenticated(username, password);
+
+ } else {
+ authRequest = (UsernamePasswordAuthenticationToken) securityContext.getAuthentication();
+ }
+
+ return authenticationManager.authenticate(authRequest);
+ }
+}
|
Java
|
ํ
์คํธ๋ ๊ทธ๋๋ก ๋๋ ๊ฒ์ด ๋ง์ต๋๋ค. ํ
์คํธ๊ฐ ํฐ์ง๋ ์์ธ์ `String authorization = request.getHeader("Authorization");`์์ ํค๋๊ฐ์ด ์๋๋ฐ ๊ฐ์ ธ์ค๋ ค๊ณ ํ๋ ๊ฒ์ผ๋ก, ์์ผ๋ฉด null์ ๋ฐํํ๊ฒ๋ ๋์์ํค๋ฉด ๋ฉ๋๋ค. ํด๋น ํํฐ๋ ํค๋์ `Authorization`์ด ์์ผ๋ฉด ๋์ํ ํ์๊ฐ ์์ด ๋ฐ์ดํจ์คํ๋ฉด ๋๋๊น์.
ํ์ฌ๋จ๊ณ์์๋ ๋ณ๋ path์ ๋ฐ๋ฅธ ์ธ๊ฐ์ฒ๋ฆฌ๊ฐ ์๊ธฐ ๋๋ฌธ์ ๊ทธ์ ๋๋ก๋ง ์ฒ๋ฆฌํ๊ณ ๋์ด๊ฐ์ฃผ์
๋๋ฉ๋๋ค.
|
@@ -0,0 +1,10 @@
+package nextstep.authentication;
+
+public interface Authentication {
+
+ String getPrincipal();
+
+ String getCredentials();
+
+ boolean isAuthenticated();
+}
|
Java
|
์ค์ ํจํค์ง ๊ตฌ์กฐ๋ `authentication`์์ ๋ชจ๋ ๊ฒ์ด ์๋ ๊ฒ์ด ์๋ ์น์ ๋ํ ํธ์ถ์ ์ฒ๋ฆฌํ๋ `FilterChainProxy`์ ๊ฐ์ ํด๋์ค๋ค์ `web`ํจํค์ง์, `UserDetails`์ ๊ฐ์ด ์ ์ ์ ๋ณด๋ฅผ ํํํ๋ ํด๋์ค๋ค์ ๋ณ๋๋ก `userdetails`์์ ๊ด๋ฆฌํฉ๋๋ค.
|
@@ -0,0 +1,27 @@
+package nextstep.authentication.context;
+
+public class SecurityContextHolder {
+
+ private static final ThreadLocal<SecurityContext> contextHolder = new ThreadLocal<>();
+
+ public static SecurityContext getContext() {
+ SecurityContext context = contextHolder.get();
+ if (context == null) {
+ context = createEmptyContext();
+ contextHolder.set(context);
+ }
+ return context;
+ }
+
+ public static void setContext(SecurityContext context) {
+ contextHolder.set(context);
+ }
+
+ public static void clearContext() {
+ contextHolder.remove();
+ }
+
+ public static SecurityContext createEmptyContext() {
+ return new SecurityContextImpl();
+ }
+}
|
Java
|
`SecurityContextHolder`๋ผ๋ ๊ตฌํ์ฒด๋ฅผ ์ฌ์ฉํ๊ฒ ๋๋ ๊ฒฝ์ฐ์๋ ์ด ํด๋์ค๋ฅผ ์ฌ์ฉํ๋ ๋ค๋ฅธ ํด๋์ค์์ ๊ตฌํ์ฒด์ ์์กดํ์ฌ ํ
์คํธํ๊ธฐ ์ด๋ ค์ด ๊ตฌ์กฐ๊ฐ ๋ ์ ์์ด ์ค์ ๋ก๋ ์ด๋ฅผ ๋ํํ ์ธํฐํ์ด์ค๋ฅผ ์ฌ์ฉํ๊ฒ๋ ๊ตฌ์ฑ๋์ด์์ต๋๋ค.
https://github.com/spring-projects/spring-security/blob/main/core/src/main/java/org/springframework/security/core/context/SecurityContextHolderStrategy.java
|
@@ -0,0 +1,19 @@
+package nextstep.authentication.exception;
+
+import org.springframework.http.HttpStatus;
+import org.springframework.web.bind.annotation.ResponseStatus;
+
+@ResponseStatus(code = HttpStatus.UNAUTHORIZED)
+public class AuthenticationException extends RuntimeException {
+
+ public AuthenticationException() {
+ }
+
+ public AuthenticationException(String msg, Throwable cause) {
+ super(msg, cause);
+ }
+
+ public AuthenticationException(String msg) {
+ super(msg);
+ }
+}
|
Java
|
์ฌ์ฉํ๊ณ ์์ง ์๊ณ ์๋ ๊ฒ ๊ฐ๋ค์.
|
@@ -0,0 +1,85 @@
+package nextstep.authentication.filter;
+
+import jakarta.servlet.Filter;
+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.authentication.Authentication;
+import nextstep.authentication.AuthenticationManager;
+import nextstep.authentication.UsernamePasswordAuthenticationToken;
+import nextstep.authentication.context.SecurityContextHolder;
+import nextstep.authentication.exception.AuthenticationException;
+import nextstep.authentication.util.Base64Convertor;
+import nextstep.authentication.util.matcher.MvcRequestMatcher;
+import org.springframework.http.HttpMethod;
+
+import java.io.IOException;
+
+public class BasicAuthenticationFilter implements Filter {
+
+ private static final MvcRequestMatcher DEFAULT_REQUEST_MATCHER = new MvcRequestMatcher(HttpMethod.GET, "/members");
+
+ private final AuthenticationManager authenticationManager;
+
+ public BasicAuthenticationFilter(AuthenticationManager authenticationManager) {
+ this.authenticationManager = authenticationManager;
+ }
+
+ @Override
+ public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
+ if (!DEFAULT_REQUEST_MATCHER.matches((HttpServletRequest) servletRequest)) {
+ filterChain.doFilter(servletRequest, servletResponse);
+ return;
+ }
+
+ HttpServletRequest request = (HttpServletRequest) servletRequest;
+ HttpServletResponse response = (HttpServletResponse) servletResponse;
+
+ try {
+
+ Authentication authenticationResult = attemptAuthentication(request, response);
+ if (authenticationResult == null) {
+ filterChain.doFilter(servletRequest, servletResponse);
+ return;
+ }
+
+ SecurityContextHolder.getContext().setAuthentication(authenticationResult);
+
+ } catch (Exception e) {
+ SecurityContextHolder.clearContext();
+ response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
+
+ return;
+ }
+
+ filterChain.doFilter(servletRequest, servletResponse);
+ }
+
+ private Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {
+
+ UsernamePasswordAuthenticationToken authRequest;
+
+ var securityContext = SecurityContextHolder.getContext();
+
+ if (securityContext.getAuthentication() == null) {
+
+ String authorization = request.getHeader("Authorization");
+ String credentials = authorization.split(" ")[1];
+ String decodedString = Base64Convertor.decode(credentials);
+ String[] usernameAndPassword = decodedString.split(":");
+
+ String username = usernameAndPassword[0];
+ String password = usernameAndPassword[1];
+
+ authRequest = UsernamePasswordAuthenticationToken.unauthenticated(username, password);
+
+ } else {
+ authRequest = (UsernamePasswordAuthenticationToken) securityContext.getAuthentication();
+ }
+
+ return authenticationManager.authenticate(authRequest);
+ }
+}
|
Java
|
ํน์ path๋ก ์ฌ์ฉํ๋ค๊ณ ํ๋๋ผ๋ ๋ค๋ฅธ path๊ฐ ์ถ๊ฐ๋๋ ๊ฒฝ์ฐ ์ด ํ๋ ์์ํฌ๋ฅผ ์ฌ์ฉํ๋ ์ฌ๋์ด ์์๋ฅผ ๊ฑด๋๋ฆด ์ ์์ผ๋ ์ฃผ์
๋ฐ์ ์ฌ์ฉํ๋ ํํ๊ฐ ๋ ์ ์ ํ๊ฒ ๋ค์.
|
@@ -3,21 +3,17 @@
<mapper namespace="com.midnear.midnearshopping.mapper.coupon_point.PointMapper">
<insert id="grantPoints" useGeneratedKeys="true" keyProperty="pointId">
INSERT INTO point (
- amount, reason
+ amount, reason, review_id, user_id, grant_date
) VALUES (
- #{amount}, #{reason}
+ #{amount}, #{reason}, #{reviewId}, #{userId}, NOW()
)
</insert>
- <insert id="setReviewPointAmount">
- INSERT INTO review_point (
- text_review, photo_review
- ) VALUES (
- #{textReview}, #{photoReview}
- )
- </insert>
- <delete id="deletePreviousData">
- delete from review_point
- </delete>
+ <select id="getProductInfoByReviewId" resultType="java.lang.String">
+ select concat(op.product_name, ' _ ', op.color)
+ from reviews r
+ join order_products op on r.order_product_id = op.order_product_id
+ where review_id = #{reviewId}
+ </select>
<!--์๋ ํ์ผ ๋ฐ๋ก ๋บด๊ธฐ ์ ๋งคํด์ ์ฌ๊ธฐ์ ๋ฃ์-->
<select id="getPointList">
select
|
Unknown
|
๊ฐ์ฌํฉ๋๋ค..
|
@@ -0,0 +1,24 @@
+import { BASE_URL } from '@/constants';
+import { GetReviewsParams, ReviewScore } from '@/types/reviewType';
+
+export const getReviewScore = async ({
+ gatheringId,
+ type,
+}: GetReviewsParams): Promise<ReviewScore[]> => {
+ const params = new URLSearchParams();
+ if (gatheringId) params.append('gatheringId', gatheringId);
+ if (type) params.append('type', type);
+
+ const res = await fetch(`${BASE_URL}/reviews/scores?${params.toString()}`, {
+ method: 'GET',
+ headers: {
+ 'Content-Type': 'application/json',
+ },
+ });
+
+ if (!res.ok) {
+ throw new Error(`${res.status}`);
+ }
+
+ return res.json();
+};
|
TypeScript
|
[p5] BASE_URL์ importํด์ ์ฌ์ฉํ ๋ถ๋ถ ์ข์ต๋๋ค!๐ฑ
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.