Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- @RestController
- @RequestMapping("/account")
- public class AccountController {
- @Autowired
- private AccountService accountService;
- @RequestMapping(value = "/{id}", method = RequestMethod.GET)
- public ResponseEntity<?> getAccount(@PathVariable("id") Long accountId) {
- Account account = accountService.getAccountById(accountId);
- if (account == null) {
- return getErrorResponseBody(ApplicationErrorTypes.ACCOUNT_ID_NOT_FOUND);
- }
- return new ResponseEntity<>(convert(account), HttpStatus.OK);
- }
- @RequestMapping(value = "/{id}", method = RequestMethod.DELETE)
- public ResponseEntity<?> deleteAccount(@PathVariable("id") Long accountId) {
- try {
- accountService.deleteAccountById(accountId);
- } catch (AccountIsNotExistsException accountIsNotExists) {
- return getErrorResponseBody(ApplicationErrorTypes.ACCOUNT_ID_NOT_FOUND);
- }
- return new ResponseEntity<>(null, HttpStatus.OK);
- }
- @RequestMapping(value = "/", method = RequestMethod.PUT)
- public ResponseEntity<?> createAccount(@RequestParam("email") String email, @RequestParam("password") String password) {
- Account account = null;
- try {
- account = accountService.createAccount(email, password);
- } catch (AccountHasExistsException accountHasExist) {
- return getErrorResponseBody(ApplicationErrorTypes.ACCOUNT_HAS_EXISTS);
- }
- return new ResponseEntity<>(convert(account), HttpStatus.OK);
- }
- @RequestMapping(value = "/{id}/account_info", method = RequestMethod.PUT)
- public ResponseEntity<?> addAccountInfo(@PathVariable("id") Long accountId, @RequestBody AccountInfoDTO info) {
- Account account = accountService.getAccountById(accountId);
- if (account == null) {
- return getErrorResponseBody(ApplicationErrorTypes.ACCOUNT_ID_NOT_FOUND);
- }
- LocalDateTime birthday = info.getBirthday() == null ? null : info.getBirthday().getLocalDateData();
- if (account.getAccountInfo() == null) {
- account = accountService.addAccountInfo(account, info.getFirstName(), info.getLastName(), info.getNick(), info.getPhotoLink(), birthday);
- } else {
- account = accountService.updateAccountInfo(account, info.getFirstName(), info.getLastName(), info.getNick(), info.getPhotoLink(), birthday);
- }
- return new ResponseEntity<>(convert(account), HttpStatus.OK);
- }
- private AccountDTO convert(Account dbModel) {
- return (dbModel == null) ? null : new AccountDTO(dbModel);
- }
- private ResponseEntity<ErrorResponseBody> getErrorResponseBody(ApplicationErrorTypes errorType) {
- return new ResponseEntity<>(new ErrorResponseBody(errorType), HttpStatus.NOT_FOUND);
- }
- }
- @Component
- public class CustomCsrfHeaderFilter extends OncePerRequestFilter {
- @Override
- protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
- throws ServletException, IOException {
- CsrfToken csrf = (CsrfToken) request.getAttribute(CsrfToken.class.getName());
- if (csrf != null) {
- Cookie cookie = WebUtils.getCookie(request, "XSRF-TOKEN");
- String token = csrf.getToken();
- if (cookie == null || token != null && !token.equals(cookie.getValue())) {
- cookie = new Cookie("XSRF-TOKEN", token);
- cookie.setPath("/");
- response.addCookie(cookie);
- }
- }
- filterChain.doFilter(request, response);
- }
- }
- @Configuration
- public class SpringSecurityBeans {
- @Autowired
- private UserDetailsService userDetailsService;
- /**
- *
- * @return Сервис для реализации функции "Запомнить пароль" при входе
- * пользователя в систему.
- *
- */
- @Bean
- public TokenBasedRememberMeServices rememberMeServices() {
- TokenBasedRememberMeServices service = new TokenBasedRememberMeServices("ASTONONE_REMEMBER_TOKEN",
- userDetailsService);
- service.setCookieName("ASTONONE_REMEMBER_ME_COOKIE");
- service.setUseSecureCookie(false);
- service.setAlwaysRemember(false);
- return service;
- }
- @Bean
- public CsrfTokenRepository customCsrfTokenRepository() {
- HttpSessionCsrfTokenRepository repository = new HttpSessionCsrfTokenRepository();
- repository.setHeaderName("X-XSRF-TOKEN");
- return repository;
- }
- @Bean
- public Http403ForbiddenEntryPoint http403ForbiddenEntryPoint() {
- return new Http403ForbiddenEntryPoint();
- }
- /**
- * @return the userDetailsService
- */
- public UserDetailsService getUserDetailsService() {
- return userDetailsService;
- }
- /**
- * @param userDetailsService
- * the userDetailsService to set
- */
- public void setUserDetailsService(UserDetailsService userDetailsService) {
- this.userDetailsService = userDetailsService;
- }
- }
- @Service
- public class UserDetailsSecurityService implements UserDetailsService {
- @Autowired
- AccountService accountService;
- @Override
- public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
- Account account = accountService.findAccountByEmail(username);
- if (account != null) {
- return account;
- }
- throw new UsernameNotFoundException("User with name = " + username + " not found");
- }
- }
- <?xml version="1.0" encoding="UTF-8"?>
- <beans xmlns="http://www.springframework.org/schema/beans"
- xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xmlns:mvc="http://www.springframework.org/schema/mvc"
- xmlns:context="http://www.springframework.org/schema/context"
- xsi:schemaLocation="http://www.springframework.org/schema/beans
- http://www.springframework.org/schema/beans/spring-beans.xsd
- http://www.springframework.org/schema/mvc
- http://www.springframework.org/schema/mvc/spring-mvc.xsd
- http://www.springframework.org/schema/context
- http://www.springframework.org/schema/context/spring-context.xsd">
- <context:component-scan base-package="com.astonone.cofing" />
- <context:component-scan base-package="com.astonone.auth" />
- <import resource="music-cloud.xml"/>
- <mvc:resources mapping="/resources/**" location="/resources/" />
- </beans>
- <beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xmlns:p="http://www.springframework.org/schema/p"
- xmlns:context="http://www.springframework.org/schema/context"
- xmlns:mvc="http://www.springframework.org/schema/mvc"
- xmlns="http://www.springframework.org/schema/beans"
- xmlns:tx="http://www.springframework.org/schema/tx"
- xmlns:jpa="http://www.springframework.org/schema/data/jpa"
- xsi:schemaLocation="http://www.springframework.org/schema/mvc
- http://www.springframework.org/schema/mvc/spring-mvc.xsd
- http://www.springframework.org/schema/beans
- http://www.springframework.org/schema/beans/spring-beans.xsd
- http://www.springframework.org/schema/context
- http://www.springframework.org/schema/context/spring-context.xsd
- http://www.springframework.org/schema/tx
- http://www.springframework.org/schema/tx/spring-tx.xsd
- http://www.springframework.org/schema/data/jpa
- http://www.springframework.org/schema/data/jpa/spring-jpa.xsd">
- <!--Activates various annotations to be detected in bean classes: Spring's @Required and @Autowired and so on-->
- <context:annotation-config/>
- <context:component-scan base-package="com.astonone">
- <context:exclude-filter expression="org.springframework.stereotype.Controller"
- type="annotation" />
- </context:component-scan>
- <!--Spring service pagages-->
- <context:component-scan base-package="com.astonone.web"/>
- <context:component-scan base-package="com.astonone.service"/>
- <!-- Need for Repository abstraction -->
- <jpa:repositories base-package="com.astonone.repository" entity-manager-factory-ref="emf"
- transaction-manager-ref="transactionManager"/>
- <mvc:annotation-driven />
- <!--@Transaction annotation support -->
- <tx:annotation-driven transaction-manager="transactionManager"/>
- <!--Обеспечивает работу с транзакциями в Spring -->
- <bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
- <property name="entityManagerFactory" ref="emf"/>
- </bean>
- <!-- EntityManagerFactory -->
- <bean id="emf" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
- <property name="dataSource" ref="dataSource" />
- <!--Поставщик данных - hibernate-->
- <property name="jpaVendorAdapter">
- <bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter" />
- </property>
- <!--поиск сущностей в этом пакете-->
- <property name="packagesToScan" value="com.astonone.model"/>
- <!--детали конфигурации поставщика постоянства (hibernate) -->
- <property name="jpaProperties">
- <props>
- <prop key="hibernate.dialect">
- org.hibernate.dialect.PostgreSQL9Dialect
- </prop>
- <prop key="hibernate.max_fetch_depth">0</prop>
- <prop key="hibernate.jdbc.fetch_size">0</prop>
- <prop key="hibernate.jdbc.batch_size">5</prop>
- <prop key="hibernate.show_sql">true</prop>
- </props>
- </property>
- </bean>
- <!-- Datasource. Источник данных - база PostgreSQL -->
- <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
- <property name="driverClassName" value="org.postgresql.Driver" />
- <property name="url" value="jdbc:postgresql://localhost:5432/music_cloud" />
- <property name="username" value="viktor_kulygin" />
- <property name="password" value="123456" />
- </bean>
- <beans:beans xmlns="http://www.springframework.org/schema/security"
- xmlns:beans="http://www.springframework.org/schema/beans"
- xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xsi:schemaLocation="http://www.springframework.org/schema/beans
- http://www.springframework.org/schema/beans/spring-beans-4.3.xsd
- http://www.springframework.org/schema/security
- http://www.springframework.org/schema/security/spring-security-4.1.xsd">
- <http>
- <intercept-url pattern="/resources/partials/protected/*"
- access="hasRole('USER')" />
- <http-basic entry-point-ref="http403ForbiddenEntryPoint" />
- <csrf token-repository-ref="customCsrfTokenRepository" />
- <custom-filter after="CSRF_FILTER" ref="customCsrfHeaderFilter" />
- <remember-me key="ASTONONE_REMEMBER_TOKEN" services-ref="rememberMeServices" />
- </http>
- <authentication-manager alias="authenticationManager">
- <authentication-provider user-service-ref="userDetailsSecurityService">
- <password-encoder hash="bcrypt" />
- </authentication-provider>
- </authentication-manager>
- <beans:bean id="encoder"
- class="org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder">
- <beans:constructor-arg name="strength" value="11"/>
- </beans:bean>
- <?xml version="1.0" encoding="UTF-8"?>
- <web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
- xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
- http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
- version="3.1">
- <display-name>music-cloud</display-name>
- <description>music service</description>
- <context-param>
- <param-name>contextConfigLocation</param-name>
- <param-value>
- /WEB-INF/config/application-context.xml
- /WEB-INF/config/spring-security.xml
- </param-value>
- </context-param>
- <listener>
- <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
- </listener>
- <listener>
- <listener-class>org.springframework.web.context.request.RequestContextListener</listener-class>
- </listener>
- <servlet>
- <servlet-name>music-cloud</servlet-name>
- <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
- <init-param>
- <param-name>contextConfigLocation</param-name>
- <param-value>
- /WEB-INF/config/music-cloud.xml
- /WEB-INF/config/application-context.xml
- </param-value>
- </init-param>
- <load-on-startup>1</load-on-startup>
- </servlet>
- <servlet-mapping>
- <servlet-name>music-cloud</servlet-name>
- <url-pattern>/</url-pattern>
- </servlet-mapping>
- <filter>
- <filter-name>springSecurityFilterChain</filter-name>
- <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
- </filter>
- <filter-mapping>
- <filter-name>springSecurityFilterChain</filter-name>
- <url-pattern>/*</url-pattern>
- </filter-mapping>
- <filter>
- <filter-name>encodingFilter</filter-name>
- <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
- <init-param>
- <param-name>encoding</param-name>
- <param-value>UTF-8</param-value>
- </init-param>
- <init-param>
- <param-name>forceEncoding</param-name>
- <param-value>true</param-value>
- </init-param>
- </filter>
- <filter-mapping>
- <filter-name>encodingFilter</filter-name>
- <url-pattern>/*</url-pattern>
- </filter-mapping>
- </web-app>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement