shjung 2 gadi atpakaļ
vecāks
revīzija
2a77f4d0ad

+ 20 - 0
src/main/java/com/its/op/dto/validate/PhoneNumber.java

@@ -0,0 +1,20 @@
+package com.its.op.dto.validate;
+
+import javax.validation.Constraint;
+import javax.validation.Payload;
+import java.lang.annotation.Retention;
+import java.lang.annotation.Target;
+
+import static java.lang.annotation.ElementType.FIELD;
+import static java.lang.annotation.RetentionPolicy.RUNTIME;
+
+@Target({FIELD})
+@Retention(RUNTIME)
+@Constraint(validatedBy = PhoneNumberValidator.class)
+public @interface PhoneNumber {
+
+    String message() default "전화번호 형식이 잘못 되었습니다.";
+    Class<?>[] groups() default { };
+    Class<? extends Payload>[] payload() default { };
+
+}

+ 23 - 0
src/main/java/com/its/op/dto/validate/PhoneNumberValidator.java

@@ -0,0 +1,23 @@
+package com.its.op.dto.validate;
+
+import javax.validation.ConstraintValidator;
+import javax.validation.ConstraintValidatorContext;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+
+public class PhoneNumberValidator implements ConstraintValidator<PhoneNumber, String> {
+
+    /**
+     * 전화번호 검증: xxx-xxxx-xxxx 형식만 검증
+     * @param value : 입력 전화번호
+     * @param constraintValidatorContext : 컨텍스트
+     * @return
+     */
+    @Override
+    public boolean isValid(String value, ConstraintValidatorContext constraintValidatorContext) {
+        Pattern pattern = Pattern.compile("\\d{3}-\\d{4}-\\d{4}");
+        Matcher matcher = pattern.matcher(value);
+        return matcher.matches();
+    }
+
+}

+ 15 - 0
src/main/java/com/its/op/dto/validate/ValidateTestController.java

@@ -0,0 +1,15 @@
+package com.its.op.dto.validate;
+
+import io.swagger.annotations.Api;
+import lombok.RequiredArgsConstructor;
+import org.springframework.validation.annotation.Validated;
+import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.bind.annotation.RestController;
+
+@Api(tags = "999.Controller Test")
+@Validated
+@RestController
+@RequiredArgsConstructor
+@RequestMapping("/api/test")
+public class ValidateTestController {
+}

+ 11 - 0
src/main/java/com/its/op/dto/validate/ValidateTestDto.java

@@ -0,0 +1,11 @@
+package com.its.op.dto.validate;
+
+import lombok.Data;
+
+@Data
+public class ValidateTestDto {
+
+    @PhoneNumber
+    private String phoneNumber;
+
+}

+ 12 - 0
src/main/java/com/its/op/security/WebController.java

@@ -20,6 +20,7 @@ public class WebController {
     private final String wallContext = "forward:/application/wall";
     private final String fcltContext = "forward:/application/facility";
     private final String dashBoardContext = "forward:/application/dashboard";
+    private final String manualContext    = "forward:/application/manual";
 
     /**
      * 로그인 화면 리다이렉션
@@ -73,4 +74,15 @@ public class WebController {
         return new ModelAndView(this.dashBoardContext + "/index.html");
     }
 
+    /**
+     * 도움말 리다이렉션
+     * @param request
+     * @param response
+     * @return
+     */
+    @GetMapping({"/manual", "/manual/", "/manual/manual.do"})
+    public ModelAndView manual(HttpServletRequest request, HttpServletResponse response) {
+        return new ModelAndView(this.manualContext + "/index.html");
+    }
+
 }

+ 7 - 74
src/main/java/com/its/op/security/WebSecurityConfig.java

@@ -59,82 +59,13 @@ public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
         web.ignoring().antMatchers(HttpMethod.PUT, "/api/scrs/file/**");  // GET Method 는 모두 통과
         web.ignoring().antMatchers(HttpMethod.DELETE, "/api/scrs/file/**");  // GET Method 는 모두 통과
 
-    }
-
-    //@Override
-    protected void configure_non_login(HttpSecurity http) {
+        web.ignoring().antMatchers(HttpMethod.GET, "/api/test/**");  // GET Method 는 모두 통과
+        web.ignoring().antMatchers(HttpMethod.POST, "/api/test/**");  // GET Method 는 모두 통과
+        web.ignoring().antMatchers(HttpMethod.PUT, "/api/test/**");  // GET Method 는 모두 통과
+        web.ignoring().antMatchers(HttpMethod.DELETE, "/api/test/**");  // GET Method 는 모두 통과
 
-        // URL 권한 설정
-        //setAntMatchers(http, "ROLE_");
+        web.ignoring().antMatchers(HttpMethod.GET, "/manual/**");  // GET Method 는 모두 통과
 
-        try {
-            http.csrf().disable();  // REST API 호출 유효하게(POST...)
-            http
-                    .authorizeRequests()
-                    // SWAGGER 권한 설정
-                    .antMatchers("/swagger-ui.html", "/swagger/**", "/swagger-resources/**", "/webjars/**", "/v2/api-docs").permitAll()
-                    // 웹소켓 권한 설정하지
-                    .antMatchers("/ws/**").permitAll()
-                    .antMatchers("/api/resource/**").permitAll()
-                    .antMatchers("/api/reload/**").permitAll()
-                    .antMatchers("/api/scrs/file/**").permitAll()
-//                    .antMatchers("/api/**").permitAll()
-                    // 지도 URI 권한 설정하지
-                    .antMatchers("/MAPDATA/**").permitAll()
-                    .antMatchers("/download/**").permitAll()
-                    // 페이지 권한 설정
-                    .antMatchers("/application/**", "/facility/**").permitAll()
-                    .antMatchers("/application/wall/**", "/wall/**").permitAll()
-                    .antMatchers("/application/facility/**", "/facility/**").permitAll()
-                    .antMatchers("/application/dashboard/**", "/dashboard/**").permitAll()
-                    .antMatchers("/application/login/**").permitAll()
-                    .antMatchers("/api/auth/**").permitAll()
-                    .anyRequest().authenticated()
-                    .and()
-                    .formLogin()
-                    .loginPage("/application/op/00.main/main.html")
-                    //.loginPage("/api/auth/login.do")
-                    .loginProcessingUrl("/api/auth/login.do")
-                    .defaultSuccessUrl("/application/op/00.main/main.html", true)
-                    .usernameParameter("username")
-                    .passwordParameter("password")
-                    .successHandler(this.webLoginSuccessHandler)
-                    .failureHandler(this.webLoginFailureHandler)
-                    .permitAll()
-                    .and()
-                    .logout()
-                    //.logoutUrl("/api/auth/logout.do")
-                    //.logoutRequestMatcher(new AntPathRequestMatcher("/api/auth/logout.do"))
-                    .addLogoutHandler(new UserLogoutHandler()).permitAll()
-                    .logoutSuccessUrl("/application/login/login.html").permitAll()
-                    //.logoutSuccessUrl("/api/auth/login.do").permitAll()
-                    .invalidateHttpSession(true)
-                    .deleteCookies("JSESSIONID")
-                    .deleteCookies(WebConstants.USER_UUID)
-                    .deleteCookies(WebConstants.USER_TIME)
-                    .and()
-                    .sessionManagement()
-                    .sessionCreationPolicy(SessionCreationPolicy.IF_REQUIRED)   // 스프링 시큐리티가 필요 시 생성 (default)
-                    // 인증에 성공할 때 마다 세션 ID나 세션을 변경해서 발급해줌으로써
-                    // 세션을 중간에서 가로채더라도 해당 세션이 유효하지 않게 하는 기능
-                    .invalidSessionUrl("/application/login/login.html")    // 세션이 유효하지 않을 경우 이동 할 페이지
-                    //.invalidSessionUrl("/api/auth/login.do")    // 세션이 유효하지 않을 경우 이동 할 페이지
-                    .sessionFixation().changeSessionId()        // changeSessionId : 새로운 세션 ID를 발급해서 전달(default)
-                    // none            : 아무 동작 안함
-                    // migrateSession  : 새로운 세션을 생성해서 전달 (속성값 유지)
-                    // newSession      : 새로운 세션 전달 (속성값 유지 안됨)
-                    .maximumSessions(20)                        // 최대 허용 가능 세션 수, -1인 경우 무제한 세션 허용
-                    .maxSessionsPreventsLogin(true)             // 동시 로그인 차단, false 인 경우 기존 세션 만료(default)
-                    .expiredUrl("/application/login/login.html")          // 세션이 만료된 경우 이동 할 페이지
-                    //.expiredUrl("/api/auth/login.do")          // 세션이 만료된 경우 이동 할 페이지
-                    .sessionRegistry(sessionRegistry())
-            ;
-        } catch (IOException e) {
-            // FOR KISA Secure Coding pass
-            log.error("{configure: IOException}");
-        } catch (Exception e) {
-            log.error("{configure: Exception}");
-        }
     }
 
     @Override
@@ -155,6 +86,8 @@ public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
                     .antMatchers("/ws/**").permitAll()
                     .antMatchers("/api/resource/**").permitAll()
                     .antMatchers("/api/reload/**").permitAll()
+                    .antMatchers("/api/test/**").permitAll()
+                    .antMatchers("/api/manual/**").permitAll()
 //                    .antMatchers("/api/**").permitAll()   // 로그인 하지 않을 경우 주석해제
                     // 지도 URI 권한 설정하지
                     .antMatchers("/MAPDATA/**").permitAll()

+ 2 - 0
src/main/java/com/its/op/service/its/cctv/TbCctvCtlrService.java

@@ -77,6 +77,8 @@ public class TbCctvCtlrService {
             data = this.repo.findAllList();
         }
 
+//        result = data.stream().map(obj -> obj.toDto()).collect(Collectors.toList());
+//        result = data.stream().map(TbCctvCtlr::toDto).collect(Collectors.toList());
         data.forEach(obj -> {
             result.add(obj.toDto());
         });

+ 6 - 2
src/test/java/com/its/op/ItsOpServerApplicationTests.java

@@ -32,6 +32,10 @@ public class ItsOpServerApplicationTests {
     @Autowired
     private EntityManager em;
 
+    @Test
+    void res() {
+        //Result result = new Result(1, null);
+    }
     @Test
     void qry() {
         List<TbAtrd> result = em.createQuery("select m from TbAtrd m", TbAtrd.class)
@@ -42,8 +46,8 @@ public class ItsOpServerApplicationTests {
         });
 
         log.error("======================================================================================");
-        List<TbAtrd> result_ = em.createQuery("select m from TbAtrd m where m.atrdId = :id", TbAtrd.class)
-                .setParameter("id", "ATRD010")
+        List<TbAtrd> result_ = em.createQuery("select m from TbAtrd m where m.atrdId = :paramId", TbAtrd.class)
+                .setParameter("paramId", "ATRD010")
                 .getResultList();
         log.error("{} EA.", result_.size());
         result_.forEach(obj -> {

+ 51 - 0
src/test/java/com/its/op/TbCctvCtlrControllerTest.java

@@ -0,0 +1,51 @@
+package com.its.op;
+
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.its.op.dto.its.cctv.TbCctvCtlrDto;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.DisplayName;
+import org.junit.jupiter.api.Test;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.test.web.servlet.MockMvc;
+import org.springframework.test.web.servlet.setup.MockMvcBuilders;
+import org.springframework.web.context.WebApplicationContext;
+
+//@WebMvcTest(TbCctvCtlrController.class)
+public class TbCctvCtlrControllerTest {
+
+    @Autowired
+    private MockMvc mockMvc;
+    @Autowired
+    private WebApplicationContext ctx;
+    @Autowired
+    private ObjectMapper objectMapper;
+
+    @BeforeEach
+    void setUp() {
+        //RequestResponseBodyMethodProcessor
+        mockMvc = MockMvcBuilders.webAppContextSetup(ctx)
+//                .alwaysDo(print())
+                .build();
+    }
+
+    @Test
+    @DisplayName("Post @Valid 테스트")
+    void test() throws Exception {
+        final String obj = objectMapper.writeValueAsString(new TbCctvCtlrDto.TbCctvCtlrUpdReq());
+
+//        mockMvc.perform(post("/api/cctv/manager/info/1")
+//                        .content(obj)
+//                        .contentType(MediaType.APPLICATION_JSON_VALUE))
+//                .andExpect(status().isBadRequest());
+    }
+
+    @Test
+    @DisplayName("Get @Validated 테스트")
+    void hiTest() throws Exception {
+//        mockMvc.perform(get("/api/cctv/manager/info/1")
+//                        //.param("value", "0")
+//                        .contentType(MediaType.APPLICATION_JSON_VALUE)
+//                )
+//                .andExpect(status().isInternalServerError());
+    }
+}