Browse Source

Deprecate String vars for web URLs; read URLs from website.properties;

read auth field props from authentication.properties
Signed-off-by: Pekka Helenius <fincer89@hotmail.com>
v0.0.3-alpha
Pekka Helenius 4 years ago
parent
commit
e5449f8697
4 changed files with 67 additions and 81 deletions
  1. +24
    -19
      bookstore/src/main/java/com/fjordtek/bookstore/config/WebSecurityConfig.java
  2. +2
    -2
      bookstore/src/main/java/com/fjordtek/bookstore/web/BookBasePathAwareController.java
  3. +32
    -52
      bookstore/src/main/java/com/fjordtek/bookstore/web/BookController.java
  4. +9
    -8
      bookstore/src/main/java/com/fjordtek/bookstore/web/BookRestController.java

+ 24
- 19
bookstore/src/main/java/com/fjordtek/bookstore/config/WebSecurityConfig.java View File

@ -5,6 +5,7 @@ package com.fjordtek.bookstore.config;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order; import org.springframework.core.annotation.Order;
import org.springframework.core.env.Environment;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity; import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.builders.HttpSecurity;
@ -39,6 +40,9 @@ import com.fjordtek.bookstore.service.session.UserDetailServiceImpl;
) )
public class WebSecurityConfig extends WebSecurityConfigurerAdapter { public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private Environment env;
@Autowired @Autowired
private UserDetailServiceImpl userDetailService; private UserDetailServiceImpl userDetailService;
@ -67,12 +71,12 @@ public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Configuration @Configuration
@Order(1) @Order(1)
public static class ApiWebSecurityConfig extends WebSecurityConfigurerAdapter {
public class ApiWebSecurityConfig extends WebSecurityConfigurerAdapter {
@Override @Override
protected void configure(HttpSecurity httpSecurity) throws Exception { protected void configure(HttpSecurity httpSecurity) throws Exception {
httpSecurity httpSecurity
.antMatcher("/api/**")
.antMatcher(env.getProperty("spring.data.rest.base-path") + "/**")
.authorizeRequests( .authorizeRequests(
authorize -> authorize authorize -> authorize
.anyRequest().hasAuthority("ADMIN") .anyRequest().hasAuthority("ADMIN")
@ -88,7 +92,7 @@ public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Configuration @Configuration
@Order(2) @Order(2)
public static class WebFormWebSecurityConfig extends WebSecurityConfigurerAdapter {
public class WebFormWebSecurityConfig extends WebSecurityConfigurerAdapter {
/* /*
@Override @Override
public void configure(WebSecurity webSecurity) throws Exception { public void configure(WebSecurity webSecurity) throws Exception {
@ -101,31 +105,32 @@ public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
httpSecurity httpSecurity
.authorizeRequests() .authorizeRequests()
.antMatchers( .antMatchers(
"/h2-console/**",
"/",
"/booklist",
"/error",
"/favicon.ico",
"/css/**",
"/js/**",
"/images/**"
env.getProperty("spring.h2.console.path") + "/**",
env.getProperty("page.url.index"),
env.getProperty("page.url.list"),
env.getProperty("page.url.error"),
env.getProperty("page.url.resources.css") + "/**",
env.getProperty("page.url.resources.js") + "/**",
env.getProperty("page.url.resources.images") + "/**"
// "/favicon.ico",
).permitAll() ).permitAll()
.antMatchers("/apiref/**").hasAuthority("ADMIN")
.antMatchers(env.getProperty("page.url.apiref") + "/**")
.hasAuthority("ADMIN")
.anyRequest() .anyRequest()
.authenticated() .authenticated()
.and() .and()
.formLogin() .formLogin()
.usernameParameter("b_username")
.passwordParameter("b_password")
.usernameParameter(env.getProperty("auth.field.username"))
.passwordParameter(env.getProperty("auth.field.password"))
.successHandler(new BookStoreAuthenticationSuccessHandler()) .successHandler(new BookStoreAuthenticationSuccessHandler())
.failureHandler(new BookStoreAuthenticationFailureHandler()) .failureHandler(new BookStoreAuthenticationFailureHandler())
.loginProcessingUrl("/login")
.loginPage("/booklist")
.defaultSuccessUrl("/booklist")
.loginProcessingUrl(env.getProperty("page.url.login"))
.loginPage(env.getProperty("page.url.list"))
.defaultSuccessUrl(env.getProperty("page.url.list"))
.permitAll() .permitAll()
.and() .and()
.logout() .logout()
.logoutSuccessUrl("/booklist")
.logoutSuccessUrl(env.getProperty("page.url.list"))
.permitAll() .permitAll()
.invalidateHttpSession(true) .invalidateHttpSession(true)
.clearAuthentication(true) .clearAuthentication(true)
@ -135,7 +140,7 @@ public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
.accessDeniedHandler(new BookStoreAccessDeniedHandler()) .accessDeniedHandler(new BookStoreAccessDeniedHandler())
.and() .and()
.csrf() .csrf()
.ignoringAntMatchers("/h2-console/**")
.ignoringAntMatchers(env.getProperty("spring.h2.console.path") + "/**")
.and() .and()
.sessionManagement() .sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.IF_REQUIRED) .sessionCreationPolicy(SessionCreationPolicy.IF_REQUIRED)


+ 2
- 2
bookstore/src/main/java/com/fjordtek/bookstore/web/BookBasePathAwareController.java View File

@ -101,7 +101,7 @@ public class BookBasePathAwareController {
////////////////////////////// //////////////////////////////
@RequestMapping( @RequestMapping(
value = "booklist",
value = "${page.url.restapi.list}",
method = RequestMethod.POST, method = RequestMethod.POST,
consumes = "application/json", consumes = "application/json",
produces = "application/hal+json" produces = "application/hal+json"
@ -149,7 +149,7 @@ public class BookBasePathAwareController {
} }
@RequestMapping( @RequestMapping(
value = "booklist" + "/{id}",
value = "${page.url.restapi.list}" + "/{id}",
method = RequestMethod.PUT, method = RequestMethod.PUT,
consumes = "application/json", consumes = "application/json",
produces = "application/hal+json" produces = "application/hal+json"


+ 32
- 52
bookstore/src/main/java/com/fjordtek/bookstore/web/BookController.java View File

@ -4,14 +4,13 @@ package com.fjordtek.bookstore.web;
import java.math.BigDecimal; import java.math.BigDecimal;
import java.time.Year; import java.time.Year;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid; import javax.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.http.HttpStatus; import org.springframework.http.HttpStatus;
import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.Authentication; import org.springframework.security.core.Authentication;
@ -57,6 +56,9 @@ public class BookController {
binder.registerCustomEditor(BigDecimal.class, new BigDecimalPropertyEditor()); binder.registerCustomEditor(BigDecimal.class, new BigDecimalPropertyEditor());
} }
@Autowired
private Environment env;
@Autowired @Autowired
private CategoryRepository categoryRepository; private CategoryRepository categoryRepository;
@ -71,18 +73,6 @@ public class BookController {
private BookAuthorHelper bookAuthorHelper; private BookAuthorHelper bookAuthorHelper;
private static final String RestJSONPageView = "json";
private static final String RestAPIRefPageView = "apiref";
private static final String landingPageView = "index";
private static final String bookListPageView = "booklist";
private static final String bookAddPageView = "bookadd";
private static final String bookDeletePageView = "bookdelete";
private static final String bookEditPageView = "bookedit";
private static final String bookLoginPageView = "/login";
private static final String bookLogoutPageView = "/logout";
/* /*
* This method MUST exist with Autowired annotation. Handles autowiring of external classes. * This method MUST exist with Autowired annotation. Handles autowiring of external classes.
* If this method is not defined, they are not found by this controller class (are null). * If this method is not defined, they are not found by this controller class (are null).
@ -93,31 +83,21 @@ public class BookController {
) { ) {
this.bookAuthorHelper = bookAuthorHelper; this.bookAuthorHelper = bookAuthorHelper;
} }
/*
private Map<String,String> globalModelMap = new HashMap<String,String>() { private Map<String,String> globalModelMap = new HashMap<String,String>() {
private static final long serialVersionUID = 1L; private static final long serialVersionUID = 1L;
{ {
put("restpage", RestJSONPageView);
put("apirefpage", RestAPIRefPageView);
put("indexpage", landingPageView);
put("listpage", bookListPageView);
put("addpage", bookAddPageView);
put("deletepage", bookDeletePageView);
put("editpage", bookEditPageView);
put("loginpage", bookLoginPageView);
put("logoutpage", bookLogoutPageView);
put("foo", Stringbar);
...
}}; }};
*/
private HttpServerLogger httpServerLogger = new HttpServerLogger(); private HttpServerLogger httpServerLogger = new HttpServerLogger();
@ModelAttribute @ModelAttribute
public void globalAttributes(Model dataModel) { public void globalAttributes(Model dataModel) {
// Security implications of adding these all controller-wide? // Security implications of adding these all controller-wide?
dataModel.addAllAttributes(globalModelMap);
// dataModel.addAllAttributes(globalModelMap);
dataModel.addAttribute("categories", categoryRepository.findAll()); dataModel.addAttribute("categories", categoryRepository.findAll());
dataModel.addAttribute("authors", authorRepository.findAll()); dataModel.addAttribute("authors", authorRepository.findAll());
} }
@ -125,7 +105,7 @@ public class BookController {
////////////////////////////// //////////////////////////////
// LIST PAGE // LIST PAGE
@RequestMapping( @RequestMapping(
value = bookListPageView,
value = "${page.url.list}",
method = { RequestMethod.GET, RequestMethod.POST } method = { RequestMethod.GET, RequestMethod.POST }
) )
public String defaultWebFormGetPost( public String defaultWebFormGetPost(
@ -137,7 +117,7 @@ public class BookController {
dataModel.addAttribute("books", bookRepository.findAll()); dataModel.addAttribute("books", bookRepository.findAll());
httpServerLogger.log(requestData, responseData); httpServerLogger.log(requestData, responseData);
return bookListPageView;
return env.getProperty("page.url.list");
} }
////////////////////////////// //////////////////////////////
@ -148,7 +128,7 @@ public class BookController {
* @see com.fjordtek.bookstore.config.WebSecurityConfig * @see com.fjordtek.bookstore.config.WebSecurityConfig
*/ */
@RequestMapping( @RequestMapping(
value = "/autherror",
value = "${page.url.autherror}",
method = RequestMethod.POST method = RequestMethod.POST
) )
public String authErrorWebFormPost( public String authErrorWebFormPost(
@ -173,7 +153,7 @@ public class BookController {
*/ */
redirectAttributes.addFlashAttribute("authfailure", authfailure); redirectAttributes.addFlashAttribute("authfailure", authfailure);
return "redirect:/" + bookListPageView;
return "redirect:" + env.getProperty("page.url.list");
} }
@ -182,7 +162,7 @@ public class BookController {
@PreAuthorize("hasAuthority('MARKETING')") @PreAuthorize("hasAuthority('MARKETING')")
@RequestMapping( @RequestMapping(
value = bookAddPageView,
value = "${page.url.add}",
method = { RequestMethod.GET, RequestMethod.PUT } method = { RequestMethod.GET, RequestMethod.PUT }
) )
public String webFormAddBook( public String webFormAddBook(
@ -197,12 +177,12 @@ public class BookController {
httpServerLogger.log(requestData, responseData); httpServerLogger.log(requestData, responseData);
return bookAddPageView;
return env.getProperty("page.url.add");
} }
@PreAuthorize("hasAuthority('MARKETING')") @PreAuthorize("hasAuthority('MARKETING')")
@RequestMapping( @RequestMapping(
value = bookAddPageView,
value = "${page.url.add}",
method = RequestMethod.POST method = RequestMethod.POST
) )
public String webFormSaveNewBook( public String webFormSaveNewBook(
@ -220,7 +200,7 @@ public class BookController {
if (bindingResult.hasErrors()) { if (bindingResult.hasErrors()) {
responseData.setStatus(HttpServletResponse.SC_BAD_REQUEST); responseData.setStatus(HttpServletResponse.SC_BAD_REQUEST);
httpServerLogger.log(requestData, responseData); httpServerLogger.log(requestData, responseData);
return bookAddPageView;
return env.getProperty("page.url.add");
} }
httpServerLogger.log(requestData, responseData); httpServerLogger.log(requestData, responseData);
@ -246,7 +226,7 @@ public class BookController {
bookRepository.save(book); bookRepository.save(book);
bookHashRepository.save(bookHash); bookHashRepository.save(bookHash);
return "redirect:/" + bookListPageView;
return "redirect:" + env.getProperty("page.url.list");
} }
////////////////////////////// //////////////////////////////
@ -255,7 +235,7 @@ public class BookController {
@Transactional @Transactional
@PreAuthorize("hasAuthority('ADMIN')") @PreAuthorize("hasAuthority('ADMIN')")
@RequestMapping( @RequestMapping(
value = bookDeletePageView + "/{hash_id}",
value = "${page.url.delete}" + "/{hash_id}",
method = RequestMethod.GET method = RequestMethod.GET
) )
public String webFormDeleteBook( public String webFormDeleteBook(
@ -280,7 +260,7 @@ public class BookController {
httpServerLogger.log(requestData, responseData); httpServerLogger.log(requestData, responseData);
return "redirect:/" + bookListPageView;
return "redirect:" + env.getProperty("page.url.list");
} }
////////////////////////////// //////////////////////////////
@ -288,7 +268,7 @@ public class BookController {
@PreAuthorize("hasAnyAuthority('MARKETING', 'HELPDESK')") @PreAuthorize("hasAnyAuthority('MARKETING', 'HELPDESK')")
@RequestMapping( @RequestMapping(
value = bookEditPageView + "/{hash_id}",
value = "${page.url.edit}" + "/{hash_id}",
method = RequestMethod.GET method = RequestMethod.GET
) )
public String webFormEditBook( public String webFormEditBook(
@ -313,16 +293,16 @@ public class BookController {
*/ */
if (!book.getPublish() && !authorities.contains("MARKETING") ) { if (!book.getPublish() && !authorities.contains("MARKETING") ) {
//responseData.setStatus(HttpServletResponse.SC_BAD_REQUEST); //responseData.setStatus(HttpServletResponse.SC_BAD_REQUEST);
return "redirect:/" + bookListPageView;
return "redirect:" + env.getProperty("page.url.list");
} }
httpServerLogger.log(requestData, responseData); httpServerLogger.log(requestData, responseData);
return bookEditPageView;
return env.getProperty("page.url.edit");
} catch (NullPointerException e) { } catch (NullPointerException e) {
responseData.setStatus(HttpServletResponse.SC_BAD_REQUEST); responseData.setStatus(HttpServletResponse.SC_BAD_REQUEST);
httpServerLogger.log(requestData, responseData); httpServerLogger.log(requestData, responseData);
return "redirect:/" + bookListPageView;
return "redirect:" + env.getProperty("page.url.list");
} }
} }
@ -335,7 +315,7 @@ public class BookController {
*/ */
@PreAuthorize("hasAnyAuthority('MARKETING', 'HELPDESK')") @PreAuthorize("hasAnyAuthority('MARKETING', 'HELPDESK')")
@RequestMapping( @RequestMapping(
value = bookEditPageView + "/{hash_id}",
value = "${page.url.edit}" + "/{hash_id}",
method = RequestMethod.POST method = RequestMethod.POST
) )
public String webFormUpdateBook( public String webFormUpdateBook(
@ -354,7 +334,7 @@ public class BookController {
if (bookHash == null) { if (bookHash == null) {
responseData.setStatus(HttpServletResponse.SC_BAD_REQUEST); responseData.setStatus(HttpServletResponse.SC_BAD_REQUEST);
httpServerLogger.log(requestData, responseData); httpServerLogger.log(requestData, responseData);
return "redirect:/" + bookListPageView;
return "redirect:" + env.getProperty("page.url.list");
} }
// One-to-one unidirectional relationship handling // One-to-one unidirectional relationship handling
@ -395,7 +375,7 @@ public class BookController {
if (bindingResultBook.hasErrors()) { if (bindingResultBook.hasErrors()) {
responseData.setStatus(HttpServletResponse.SC_BAD_REQUEST); responseData.setStatus(HttpServletResponse.SC_BAD_REQUEST);
httpServerLogger.log(requestData, responseData); httpServerLogger.log(requestData, responseData);
return bookEditPageView;
return env.getProperty("page.url.edit");
} }
/* /*
@ -404,7 +384,7 @@ public class BookController {
*/ */
if (!book.getPublish() && !authorities.contains("MARKETING") ) { if (!book.getPublish() && !authorities.contains("MARKETING") ) {
//responseData.setStatus(HttpServletResponse.SC_BAD_REQUEST); //responseData.setStatus(HttpServletResponse.SC_BAD_REQUEST);
return "redirect:/" + bookListPageView;
return "redirect:" + env.getProperty("page.url.list");
} }
/* /*
@ -421,13 +401,13 @@ public class BookController {
} }
httpServerLogger.log(requestData, responseData); httpServerLogger.log(requestData, responseData);
return "redirect:/" + bookListPageView;
return "redirect:" + env.getProperty("page.url.list");
} }
////////////////////////////// //////////////////////////////
// API REFERENCE HELP PAGE // API REFERENCE HELP PAGE
@RequestMapping( @RequestMapping(
value = RestAPIRefPageView,
value = "${page.url.apiref}",
method = { RequestMethod.GET } method = { RequestMethod.GET }
) )
public String webFormRestApiRef( public String webFormRestApiRef(
@ -435,7 +415,7 @@ public class BookController {
HttpServletResponse responseData HttpServletResponse responseData
) { ) {
httpServerLogger.log(requestData, responseData); httpServerLogger.log(requestData, responseData);
return RestAPIRefPageView;
return env.getProperty("page.url.apiref");
} }
////////////////////////////// //////////////////////////////
@ -454,7 +434,7 @@ public class BookController {
responseData.setStatus(HttpServletResponse.SC_BAD_REQUEST); responseData.setStatus(HttpServletResponse.SC_BAD_REQUEST);
} }
httpServerLogger.log(requestData, responseData); httpServerLogger.log(requestData, responseData);
return "redirect:/" + bookListPageView;
return "redirect:" + env.getProperty("page.url.list");
} }
@RequestMapping( @RequestMapping(


+ 9
- 8
bookstore/src/main/java/com/fjordtek/bookstore/web/BookRestController.java View File

@ -8,6 +8,7 @@ import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.http.HttpStatus; import org.springframework.http.HttpStatus;
import org.springframework.security.core.Authentication; import org.springframework.security.core.Authentication;
import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PathVariable;
@ -32,9 +33,12 @@ import com.fjordtek.bookstore.service.HttpServerLogger;
*/ */
@RestController @RestController
@RequestMapping("json")
@RequestMapping("${page.url.json}")
public class BookRestController { public class BookRestController {
@Autowired
private Environment env;
@Autowired @Autowired
private BookRepository bookRepository; private BookRepository bookRepository;
@ -45,13 +49,10 @@ public class BookRestController {
private CategoryRepository categoryRepository; private CategoryRepository categoryRepository;
*/ */
// TODO Use single variable reference for all controllers
private static final String bookListPageView = "booklist";
private HttpServerLogger httpServerLogger = new HttpServerLogger(); private HttpServerLogger httpServerLogger = new HttpServerLogger();
@RequestMapping( @RequestMapping(
value = "booklist",
value = "${page.url.json.list}",
method = RequestMethod.GET method = RequestMethod.GET
) )
public @ResponseBody Iterable<Book> getAllBooksRestData( public @ResponseBody Iterable<Book> getAllBooksRestData(
@ -72,7 +73,7 @@ public class BookRestController {
} }
@RequestMapping( @RequestMapping(
value = "book" + "/{hash_id}",
value = "${page.url.json.book}" + "/{hash_id}",
method = RequestMethod.GET method = RequestMethod.GET
) )
public @ResponseBody Optional<Book> getBookRestData( public @ResponseBody Optional<Book> getBookRestData(
@ -95,7 +96,7 @@ public class BookRestController {
* data even if they knew hash id. * data even if they knew hash id.
*/ */
if (!book.getPublish() && !authorities.contains("MARKETING") ) { if (!book.getPublish() && !authorities.contains("MARKETING") ) {
responseData.setHeader("Location", "/" + bookListPageView);
responseData.setHeader("Location", env.getProperty("page.url.index"));
responseData.setStatus(302); responseData.setStatus(302);
httpServerLogger.log(requestData, responseData); httpServerLogger.log(requestData, responseData);
return null; return null;
@ -125,7 +126,7 @@ public class BookRestController {
HttpServletRequest requestData, HttpServletRequest requestData,
HttpServletResponse responseData HttpServletResponse responseData
) { ) {
responseData.setHeader("Location", "/" + bookListPageView);
responseData.setHeader("Location", env.getProperty("page.url.index"));
responseData.setStatus(302); responseData.setStatus(302);
httpServerLogger.log(requestData, responseData); httpServerLogger.log(requestData, responseData);
} }


Loading…
Cancel
Save