Advertisement
Guest User

Untitled

a guest
Jan 28th, 2018
106
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 13.49 KB | None | 0 0
  1. @RestController
  2. @RequestMapping("/account")
  3. public class AccountController {
  4.  
  5. @Autowired
  6. private AccountService accountService;
  7.  
  8. @RequestMapping(value = "/{id}", method = RequestMethod.GET)
  9. public ResponseEntity<?> getAccount(@PathVariable("id") Long accountId) {
  10. Account account = accountService.getAccountById(accountId);
  11. if (account == null) {
  12. return getErrorResponseBody(ApplicationErrorTypes.ACCOUNT_ID_NOT_FOUND);
  13. }
  14. return new ResponseEntity<>(convert(account), HttpStatus.OK);
  15. }
  16.  
  17. @RequestMapping(value = "/{id}", method = RequestMethod.DELETE)
  18. public ResponseEntity<?> deleteAccount(@PathVariable("id") Long accountId) {
  19. try {
  20. accountService.deleteAccountById(accountId);
  21. } catch (AccountIsNotExistsException accountIsNotExists) {
  22. return getErrorResponseBody(ApplicationErrorTypes.ACCOUNT_ID_NOT_FOUND);
  23. }
  24. return new ResponseEntity<>(null, HttpStatus.OK);
  25. }
  26.  
  27. @RequestMapping(value = "/", method = RequestMethod.PUT)
  28. public ResponseEntity<?> createAccount(@RequestParam("email") String email, @RequestParam("password") String password) {
  29. Account account = null;
  30. try {
  31. account = accountService.createAccount(email, password);
  32. } catch (AccountHasExistsException accountHasExist) {
  33. return getErrorResponseBody(ApplicationErrorTypes.ACCOUNT_HAS_EXISTS);
  34. }
  35. return new ResponseEntity<>(convert(account), HttpStatus.OK);
  36. }
  37.  
  38. @RequestMapping(value = "/{id}/account_info", method = RequestMethod.PUT)
  39. public ResponseEntity<?> addAccountInfo(@PathVariable("id") Long accountId, @RequestBody AccountInfoDTO info) {
  40. Account account = accountService.getAccountById(accountId);
  41. if (account == null) {
  42. return getErrorResponseBody(ApplicationErrorTypes.ACCOUNT_ID_NOT_FOUND);
  43. }
  44.  
  45. LocalDateTime birthday = info.getBirthday() == null ? null : info.getBirthday().getLocalDateData();
  46. if (account.getAccountInfo() == null) {
  47. account = accountService.addAccountInfo(account, info.getFirstName(), info.getLastName(), info.getNick(), info.getPhotoLink(), birthday);
  48. } else {
  49. account = accountService.updateAccountInfo(account, info.getFirstName(), info.getLastName(), info.getNick(), info.getPhotoLink(), birthday);
  50. }
  51. return new ResponseEntity<>(convert(account), HttpStatus.OK);
  52. }
  53.  
  54. private AccountDTO convert(Account dbModel) {
  55. return (dbModel == null) ? null : new AccountDTO(dbModel);
  56. }
  57.  
  58. private ResponseEntity<ErrorResponseBody> getErrorResponseBody(ApplicationErrorTypes errorType) {
  59. return new ResponseEntity<>(new ErrorResponseBody(errorType), HttpStatus.NOT_FOUND);
  60. }
  61. }
  62.  
  63. @Component
  64. public class CustomCsrfHeaderFilter extends OncePerRequestFilter {
  65.  
  66. @Override
  67. protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
  68. throws ServletException, IOException {
  69.  
  70. CsrfToken csrf = (CsrfToken) request.getAttribute(CsrfToken.class.getName());
  71. if (csrf != null) {
  72. Cookie cookie = WebUtils.getCookie(request, "XSRF-TOKEN");
  73. String token = csrf.getToken();
  74. if (cookie == null || token != null && !token.equals(cookie.getValue())) {
  75. cookie = new Cookie("XSRF-TOKEN", token);
  76. cookie.setPath("/");
  77. response.addCookie(cookie);
  78. }
  79. }
  80. filterChain.doFilter(request, response);
  81. }
  82. }
  83.  
  84. @Configuration
  85. public class SpringSecurityBeans {
  86.  
  87. @Autowired
  88. private UserDetailsService userDetailsService;
  89.  
  90. /**
  91. *
  92. * @return Сервис для реализации функции "Запомнить пароль" при входе
  93. * пользователя в систему.
  94. *
  95. */
  96. @Bean
  97. public TokenBasedRememberMeServices rememberMeServices() {
  98.  
  99. TokenBasedRememberMeServices service = new TokenBasedRememberMeServices("ASTONONE_REMEMBER_TOKEN",
  100. userDetailsService);
  101.  
  102. service.setCookieName("ASTONONE_REMEMBER_ME_COOKIE");
  103. service.setUseSecureCookie(false);
  104. service.setAlwaysRemember(false);
  105.  
  106. return service;
  107. }
  108.  
  109. @Bean
  110. public CsrfTokenRepository customCsrfTokenRepository() {
  111.  
  112. HttpSessionCsrfTokenRepository repository = new HttpSessionCsrfTokenRepository();
  113. repository.setHeaderName("X-XSRF-TOKEN");
  114.  
  115. return repository;
  116. }
  117.  
  118. @Bean
  119. public Http403ForbiddenEntryPoint http403ForbiddenEntryPoint() {
  120. return new Http403ForbiddenEntryPoint();
  121. }
  122.  
  123. /**
  124. * @return the userDetailsService
  125. */
  126. public UserDetailsService getUserDetailsService() {
  127. return userDetailsService;
  128. }
  129.  
  130. /**
  131. * @param userDetailsService
  132. * the userDetailsService to set
  133. */
  134. public void setUserDetailsService(UserDetailsService userDetailsService) {
  135. this.userDetailsService = userDetailsService;
  136. }
  137. }
  138.  
  139. @Service
  140. public class UserDetailsSecurityService implements UserDetailsService {
  141.  
  142. @Autowired
  143. AccountService accountService;
  144.  
  145. @Override
  146. public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
  147.  
  148. Account account = accountService.findAccountByEmail(username);
  149. if (account != null) {
  150. return account;
  151. }
  152. throw new UsernameNotFoundException("User with name = " + username + " not found");
  153. }
  154. }
  155.  
  156. <?xml version="1.0" encoding="UTF-8"?>
  157. <beans xmlns="http://www.springframework.org/schema/beans"
  158. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  159. xmlns:mvc="http://www.springframework.org/schema/mvc"
  160. xmlns:context="http://www.springframework.org/schema/context"
  161. xsi:schemaLocation="http://www.springframework.org/schema/beans
  162. http://www.springframework.org/schema/beans/spring-beans.xsd
  163. http://www.springframework.org/schema/mvc
  164. http://www.springframework.org/schema/mvc/spring-mvc.xsd
  165. http://www.springframework.org/schema/context
  166. http://www.springframework.org/schema/context/spring-context.xsd">
  167.  
  168. <context:component-scan base-package="com.astonone.cofing" />
  169. <context:component-scan base-package="com.astonone.auth" />
  170. <import resource="music-cloud.xml"/>
  171.  
  172. <mvc:resources mapping="/resources/**" location="/resources/" />
  173. </beans>
  174.  
  175. <beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  176. xmlns:p="http://www.springframework.org/schema/p"
  177. xmlns:context="http://www.springframework.org/schema/context"
  178. xmlns:mvc="http://www.springframework.org/schema/mvc"
  179. xmlns="http://www.springframework.org/schema/beans"
  180. xmlns:tx="http://www.springframework.org/schema/tx"
  181. xmlns:jpa="http://www.springframework.org/schema/data/jpa"
  182. xsi:schemaLocation="http://www.springframework.org/schema/mvc
  183. http://www.springframework.org/schema/mvc/spring-mvc.xsd
  184. http://www.springframework.org/schema/beans
  185. http://www.springframework.org/schema/beans/spring-beans.xsd
  186. http://www.springframework.org/schema/context
  187. http://www.springframework.org/schema/context/spring-context.xsd
  188. http://www.springframework.org/schema/tx
  189. http://www.springframework.org/schema/tx/spring-tx.xsd
  190. http://www.springframework.org/schema/data/jpa
  191. http://www.springframework.org/schema/data/jpa/spring-jpa.xsd">
  192. <!--Activates various annotations to be detected in bean classes: Spring's @Required and @Autowired and so on-->
  193. <context:annotation-config/>
  194.  
  195. <context:component-scan base-package="com.astonone">
  196. <context:exclude-filter expression="org.springframework.stereotype.Controller"
  197. type="annotation" />
  198. </context:component-scan>
  199.  
  200. <!--Spring service pagages-->
  201. <context:component-scan base-package="com.astonone.web"/>
  202. <context:component-scan base-package="com.astonone.service"/>
  203. <!-- Need for Repository abstraction -->
  204. <jpa:repositories base-package="com.astonone.repository" entity-manager-factory-ref="emf"
  205. transaction-manager-ref="transactionManager"/>
  206. <mvc:annotation-driven />
  207.  
  208. <!--@Transaction annotation support -->
  209. <tx:annotation-driven transaction-manager="transactionManager"/>
  210.  
  211. <!--Обеспечивает работу с транзакциями в Spring -->
  212. <bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
  213. <property name="entityManagerFactory" ref="emf"/>
  214. </bean>
  215.  
  216. <!-- EntityManagerFactory -->
  217. <bean id="emf" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
  218. <property name="dataSource" ref="dataSource" />
  219. <!--Поставщик данных - hibernate-->
  220. <property name="jpaVendorAdapter">
  221. <bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter" />
  222. </property>
  223. <!--поиск сущностей в этом пакете-->
  224. <property name="packagesToScan" value="com.astonone.model"/>
  225. <!--детали конфигурации поставщика постоянства (hibernate) -->
  226. <property name="jpaProperties">
  227. <props>
  228. <prop key="hibernate.dialect">
  229. org.hibernate.dialect.PostgreSQL9Dialect
  230. </prop>
  231. <prop key="hibernate.max_fetch_depth">0</prop>
  232. <prop key="hibernate.jdbc.fetch_size">0</prop>
  233. <prop key="hibernate.jdbc.batch_size">5</prop>
  234. <prop key="hibernate.show_sql">true</prop>
  235. </props>
  236. </property>
  237. </bean>
  238.  
  239. <!-- Datasource. Источник данных - база PostgreSQL -->
  240. <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
  241. <property name="driverClassName" value="org.postgresql.Driver" />
  242. <property name="url" value="jdbc:postgresql://localhost:5432/music_cloud" />
  243. <property name="username" value="viktor_kulygin" />
  244. <property name="password" value="123456" />
  245. </bean>
  246.  
  247. <beans:beans xmlns="http://www.springframework.org/schema/security"
  248. xmlns:beans="http://www.springframework.org/schema/beans"
  249. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  250. xsi:schemaLocation="http://www.springframework.org/schema/beans
  251. http://www.springframework.org/schema/beans/spring-beans-4.3.xsd
  252. http://www.springframework.org/schema/security
  253. http://www.springframework.org/schema/security/spring-security-4.1.xsd">
  254.  
  255. <http>
  256. <intercept-url pattern="/resources/partials/protected/*"
  257. access="hasRole('USER')" />
  258. <http-basic entry-point-ref="http403ForbiddenEntryPoint" />
  259. <csrf token-repository-ref="customCsrfTokenRepository" />
  260. <custom-filter after="CSRF_FILTER" ref="customCsrfHeaderFilter" />
  261. <remember-me key="ASTONONE_REMEMBER_TOKEN" services-ref="rememberMeServices" />
  262. </http>
  263.  
  264. <authentication-manager alias="authenticationManager">
  265. <authentication-provider user-service-ref="userDetailsSecurityService">
  266. <password-encoder hash="bcrypt" />
  267. </authentication-provider>
  268. </authentication-manager>
  269.  
  270. <beans:bean id="encoder"
  271. class="org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder">
  272. <beans:constructor-arg name="strength" value="11"/>
  273. </beans:bean>
  274.  
  275. <?xml version="1.0" encoding="UTF-8"?>
  276. <web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
  277. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  278. xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
  279. http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
  280. version="3.1">
  281.  
  282. <display-name>music-cloud</display-name>
  283. <description>music service</description>
  284.  
  285. <context-param>
  286. <param-name>contextConfigLocation</param-name>
  287. <param-value>
  288. /WEB-INF/config/application-context.xml
  289. /WEB-INF/config/spring-security.xml
  290. </param-value>
  291. </context-param>
  292.  
  293. <listener>
  294. <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  295. </listener>
  296. <listener>
  297. <listener-class>org.springframework.web.context.request.RequestContextListener</listener-class>
  298. </listener>
  299.  
  300. <servlet>
  301. <servlet-name>music-cloud</servlet-name>
  302. <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
  303. <init-param>
  304. <param-name>contextConfigLocation</param-name>
  305. <param-value>
  306. /WEB-INF/config/music-cloud.xml
  307. /WEB-INF/config/application-context.xml
  308. </param-value>
  309. </init-param>
  310. <load-on-startup>1</load-on-startup>
  311. </servlet>
  312.  
  313. <servlet-mapping>
  314. <servlet-name>music-cloud</servlet-name>
  315. <url-pattern>/</url-pattern>
  316. </servlet-mapping>
  317.  
  318. <filter>
  319. <filter-name>springSecurityFilterChain</filter-name>
  320. <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
  321. </filter>
  322. <filter-mapping>
  323. <filter-name>springSecurityFilterChain</filter-name>
  324. <url-pattern>/*</url-pattern>
  325. </filter-mapping>
  326. <filter>
  327. <filter-name>encodingFilter</filter-name>
  328. <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
  329. <init-param>
  330. <param-name>encoding</param-name>
  331. <param-value>UTF-8</param-value>
  332. </init-param>
  333. <init-param>
  334. <param-name>forceEncoding</param-name>
  335. <param-value>true</param-value>
  336. </init-param>
  337. </filter>
  338. <filter-mapping>
  339. <filter-name>encodingFilter</filter-name>
  340. <url-pattern>/*</url-pattern>
  341. </filter-mapping>
  342. </web-app>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement