Advertisement
Guest User

Untitled

a guest
Feb 9th, 2017
117
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 10.67 KB | None | 0 0
  1. @Configuration
  2. @EnableWebSecurity
  3. public class WebSecurityConfiguration extends WebSecurityConfigurerAdapter {
  4.  
  5. @Autowired
  6. private UserDetailsService userDetailsService;
  7.  
  8. @Autowired
  9. private AuthenticationSuccessHandler authenticationSuccessHandler;
  10.  
  11. @Autowired
  12. protected void configureGlobalSecurity(AuthenticationManagerBuilder auth) throws Exception {
  13. auth.userDetailsService(userDetailsService);
  14. auth.authenticationProvider(authenticationProvider());
  15. }
  16.  
  17. @Bean
  18. public AuthenticationProvider authenticationProvider() {
  19. DaoAuthenticationProvider authenticationProvider = new DaoAuthenticationProvider();
  20. authenticationProvider.setUserDetailsService(userDetailsService);
  21. authenticationProvider.setPasswordEncoder(passwordEncoder());
  22. return authenticationProvider;
  23. }
  24.  
  25. @Bean
  26. public PasswordEncoder passwordEncoder() {
  27. return new BCryptPasswordEncoder();
  28. }
  29.  
  30. @Override
  31. protected void configure(HttpSecurity http) throws Exception {
  32. http
  33. .authorizeRequests()
  34. .antMatchers("/", "/login").permitAll()
  35. .antMatchers("/logout").authenticated()
  36. .antMatchers("/admin**/**").access("hasRole('ADMIN')")
  37. .antMatchers("/leader**/**").access("hasRole('LEADER')")
  38. .antMatchers("/user**/**").access("hasRole('LEADER') or hasRole('USER')")
  39. .antMatchers("/askhelp").authenticated()
  40. .and()
  41.  
  42. .formLogin()
  43. .loginPage("/login")
  44. .loginProcessingUrl("/login")
  45. .successHandler(authenticationSuccessHandler)
  46. .failureUrl("/login.html?error=true")
  47. .and()
  48.  
  49. .logout()
  50. .invalidateHttpSession(true)
  51. .logoutSuccessUrl("/logout")
  52. .deleteCookies("JSESSIONID", "XSRF-TOKEN")
  53. .and()
  54.  
  55. .exceptionHandling()
  56. .accessDeniedPage("/access_denied")
  57. .and()
  58.  
  59. .csrf()
  60. .csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse());
  61. }
  62.  
  63. private Filter csrfHeaderFilter() {
  64. return new OncePerRequestFilter() {
  65. @Override
  66. protected void doFilterInternal(HttpServletRequest request,
  67. HttpServletResponse response, FilterChain filterChain)
  68. throws ServletException, IOException {
  69. CsrfToken csrf = (CsrfToken) request.getAttribute(CsrfToken.class
  70. .getName());
  71. if (csrf != null) {
  72. Cookie cookie = WebUtils.getCookie(request, "X-XSRF-TOKEN");
  73. String token = csrf.getToken();
  74. if (cookie == null || token != null
  75. && !token.equals(cookie.getValue())) {
  76. cookie = new Cookie("X-XSRF-TOKEN", token);
  77. cookie.setPath("/");
  78. response.addCookie(cookie);
  79. }
  80. }
  81. filterChain.doFilter(request, response);
  82. }
  83. };
  84. }
  85.  
  86.  
  87. private CsrfTokenRepository csrfTokenRepository() {
  88. HttpSessionCsrfTokenRepository repository = new HttpSessionCsrfTokenRepository();
  89. repository.setHeaderName("X-XSRF-TOKEN");
  90. return repository;
  91. }
  92.  
  93. @Bean
  94. public AuthenticationTrustResolver getAuthenticationTrustResolver() {
  95. return new AuthenticationTrustResolverImpl();
  96. }
  97. }
  98.  
  99. @RestController
  100.  
  101. public class VillagesController {
  102. private static final Logger log = LoggerFactory.getLogger(VillagesController.class);
  103. @Autowired
  104. VillageService villageService;
  105. @Autowired
  106. UserService userService;
  107.  
  108.  
  109. @RequestMapping(value = "/village/{id}", method = RequestMethod.GET)
  110. public ResponseEntity<Village> getVillageById(@PathVariable(name = "id") String id) {
  111. Village village = villageService.getById(id);
  112. if (village == null)
  113. return new ResponseEntity<>(HttpStatus.NOT_FOUND);
  114. return new ResponseEntity<>(village, HttpStatus.OK);
  115. }
  116.  
  117. /**
  118. * Adds new village in a database.
  119. * @param village
  120. * @return added village.
  121. * @throws JsonProcessingException
  122. * @throws EntityNotUniqueException
  123. */
  124. @RequestMapping(value = "/village/", method = RequestMethod.POST)
  125. public ResponseEntity<Village> addVillage(@RequestBody Village village) throws JsonProcessingException, EntityNotUniqueException {
  126. UserDetails principal = (UserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
  127. log.info("I'm here");
  128. User userByUsername = userService.getUserByUsername(principal.getUsername());
  129. village.setPlayer(userByUsername.getPlayer());
  130.  
  131. if (villageService.isUnique(village)) {
  132. villageService.add(village);
  133. log.info("Village added : {}",village);
  134. }
  135. return new ResponseEntity<>(village, HttpStatus.CREATED);
  136. }
  137.  
  138. /**
  139. * Updates village.
  140. * @param id
  141. * @param village
  142. * @return updated village.
  143. */
  144. @RequestMapping(value = "/village/{id}", method = RequestMethod.PUT)
  145. public ResponseEntity<Village> updateVillage(@PathVariable(name = "id") String id, @RequestBody Village village) {
  146. Village current_village = villageService.getById(id);
  147. if (current_village != null) {
  148. current_village.setName(village.getName());
  149. current_village.setxCoord(village.getxCoord());
  150. current_village.setyCoord(village.getyCoord());
  151. current_village.setPopulation(village.getPopulation());
  152. current_village.setWall(village.getWall());
  153. current_village.setIsCapital(village.getIsCapital());
  154. current_village.setUuid(village.getUuid());
  155. Collections.sort(village.getArmies());
  156. current_village.setArmies(village.getArmies());
  157. if (villageService.isUnique(current_village)) {
  158. villageService.update(current_village);
  159. log.info("Village updated : {}",current_village);
  160. }
  161. return new ResponseEntity<>(current_village, HttpStatus.CREATED);
  162. }
  163.  
  164. return new ResponseEntity<>(HttpStatus.NOT_FOUND);
  165. }
  166.  
  167. @RequestMapping(value = "/village/{id}", method = RequestMethod.DELETE)
  168. public ResponseEntity<Village> deleteVillage(@PathVariable(name = "id") String id) {
  169. Village Village = villageService.getById(id);
  170. if (Village == null) {
  171. return new ResponseEntity<>(HttpStatus.NOT_FOUND);
  172. }
  173. villageService.delete(Village);
  174. return new ResponseEntity<>(Village, HttpStatus.NO_CONTENT);
  175. }
  176.  
  177. }
  178.  
  179. @ContextConfiguration(classes = {WebConfiguration.class, WebSecurityConfiguration.class})
  180. @WebAppConfiguration
  181. public class VillagesControllerTest extends AbstractTestNGSpringContextTests {
  182.  
  183.  
  184. VillageService villageService;
  185.  
  186. @Mock
  187. UserService userService;
  188.  
  189. @Autowired
  190. private WebApplicationContext context;
  191.  
  192.  
  193. @Autowired
  194. private FilterChainProxy springSecurityFilterChain;
  195.  
  196.  
  197.  
  198. @InjectMocks
  199. VillagesController villagesController;
  200.  
  201. private MockMvc mockMvc;
  202. @Spy
  203. List<Village> alliances = new ArrayList<>();
  204. @BeforeClass
  205. public void setUp(){
  206. this.villageService=mock(VillageService.class,withSettings().verboseLogging());
  207. MockitoAnnotations.initMocks(this);
  208. this.mockMvc = MockMvcBuilders.webAppContextSetup(context)
  209. .apply(SecurityMockMvcConfigurers.springSecurity())
  210. // .addFilters(this.springSecurityFilterChain)
  211. .build();
  212.  
  213. }
  214. @AfterMethod
  215. public void resetAllMocks(){
  216. Mockito.reset(villageService);
  217. }
  218.  
  219.  
  220.  
  221.  
  222. @Test
  223. // @WithMockUser(username = "trinity",password = "222",roles = {"USER"})
  224. public void testAddVillage() throws Exception {
  225. Village village = new Village();
  226. village.setName("Villkljkj");
  227. village.setPlayer(new Player());
  228. village.setxCoord((short) 58);
  229. village.setyCoord((short) 32);
  230. village.setArmies(new ArrayList<>());
  231. village.setIsCapital(true);
  232. village.setPopulation((short) 500);
  233. village.setWall((byte) 20);
  234. village.setUuid("0");
  235.  
  236.  
  237. when(userService.getUserByUsername(anyString())).thenReturn(new ua.cv.tim.model.User());
  238.  
  239. doNothing().when(villageService).add(village);
  240.  
  241. MockHttpServletRequestBuilder builder =
  242. MockMvcRequestBuilders.post("/villagkjje")
  243. .contentType(MediaType.APPLICATION_JSON)
  244. .content(convertObjectToJsonBytes(village));
  245. // .with(user("trinity").password("222").roles("ADMIN"));
  246. this.mockMvc.perform(builder)
  247. .andExpect(unauthenticated())
  248. .andExpect(MockMvcResultMatchers.status().isCreated());
  249. // .andDo(MockMvcResultHandlers.print());
  250.  
  251.  
  252.  
  253.  
  254. // ArgumentCaptor<Village> villageArgumentCaptor = ArgumentCaptor.forClass(Village.class);
  255. verify(villageService, times(1)).add(village);
  256. // verify(villageService,times(1))
  257. }
  258.  
  259.  
  260. @Test
  261. // @WithMockUser(username = "trinity",password = "222",roles = {"USER"})
  262. public void testUpdateVillage() throws Exception {
  263. Village village = new Village();
  264. village.setName("Villkljkj");
  265. village.setPlayer(new Player());
  266. village.setxCoord((short) 58);
  267. village.setyCoord((short) 32);
  268. village.setArmies(new ArrayList<>());
  269. village.setIsCapital(true);
  270. village.setPopulation((short) 500);
  271. village.setWall((byte) 20);
  272. village.setUuid("0");
  273. when(villageService.getById("0")).thenReturn(village);
  274. when(villageService.isUnique(village)).thenReturn(true);
  275. MockHttpServletRequestBuilder builder =
  276. MockMvcRequestBuilders.post("/village/0")
  277. .contentType(MediaType.APPLICATION_JSON)
  278. .content(convertObjectToJsonBytes(village))
  279. .with(user("trinity").password("222").roles("USER")).with(csrf());
  280. this.mockMvc.perform(builder)
  281. .andExpect(MockMvcResultMatchers.status().isCreated())
  282. .andExpect(authenticated())
  283. .andDo(MockMvcResultHandlers.print());
  284. // verify(villageService, times(0)).update(village);
  285. }
  286.  
  287. public static byte[] convertObjectToJsonBytes(Object object) throws IOException {
  288. ObjectMapper mapper = new ObjectMapper();
  289. mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
  290. return mapper.writeValueAsBytes(object);
  291. }
  292.  
  293. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement