From 9694891f98c4c1076ee636664f2cb0f6cd7986f0 Mon Sep 17 00:00:00 2001 From: Matt Raible Date: Tue, 26 Jun 2018 17:40:16 -0600 Subject: [PATCH] Super secure --- .../jhipster/blog/web/rest/BlogResource.java | 27 ++++++++++++--- .../jhipster/blog/web/rest/EntryResource.java | 26 ++++++++++++--- .../blog/web/rest/BlogResourceIntTest.java | 20 +++++++++-- .../blog/web/rest/EntryResourceIntTest.java | 33 ++++++++++++++++++- 4 files changed, 92 insertions(+), 14 deletions(-) diff --git a/src/main/java/org/jhipster/blog/web/rest/BlogResource.java b/src/main/java/org/jhipster/blog/web/rest/BlogResource.java index 7c5b791..aea8e4d 100644 --- a/src/main/java/org/jhipster/blog/web/rest/BlogResource.java +++ b/src/main/java/org/jhipster/blog/web/rest/BlogResource.java @@ -3,11 +3,13 @@ import com.codahale.metrics.annotation.Timed; import org.jhipster.blog.domain.Blog; import org.jhipster.blog.repository.BlogRepository; +import org.jhipster.blog.security.SecurityUtils; import org.jhipster.blog.web.rest.errors.BadRequestAlertException; import org.jhipster.blog.web.rest.util.HeaderUtil; import io.github.jhipster.web.util.ResponseUtil; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; @@ -44,11 +46,14 @@ public BlogResource(BlogRepository blogRepository) { */ @PostMapping("/blogs") @Timed - public ResponseEntity createBlog(@Valid @RequestBody Blog blog) throws URISyntaxException { + public ResponseEntity createBlog(@Valid @RequestBody Blog blog) throws URISyntaxException { log.debug("REST request to save Blog : {}", blog); if (blog.getId() != null) { throw new BadRequestAlertException("A new blog cannot already have an ID", ENTITY_NAME, "idexists"); } + if (!blog.getUser().getLogin().equals(SecurityUtils.getCurrentUserLogin().orElse(""))) { + return new ResponseEntity<>("Unauthorized", HttpStatus.UNAUTHORIZED); + } Blog result = blogRepository.save(blog); return ResponseEntity.created(new URI("/api/blogs/" + result.getId())) .headers(HeaderUtil.createEntityCreationAlert(ENTITY_NAME, result.getId().toString())) @@ -66,11 +71,15 @@ public ResponseEntity createBlog(@Valid @RequestBody Blog blog) throws URI */ @PutMapping("/blogs") @Timed - public ResponseEntity updateBlog(@Valid @RequestBody Blog blog) throws URISyntaxException { + public ResponseEntity updateBlog(@Valid @RequestBody Blog blog) throws URISyntaxException { log.debug("REST request to update Blog : {}", blog); if (blog.getId() == null) { throw new BadRequestAlertException("Invalid id", ENTITY_NAME, "idnull"); } + if (blog.getUser() != null && + !blog.getUser().getLogin().equals(SecurityUtils.getCurrentUserLogin().orElse(""))) { + return new ResponseEntity<>("Unauthorized", HttpStatus.UNAUTHORIZED); + } Blog result = blogRepository.save(blog); return ResponseEntity.ok() .headers(HeaderUtil.createEntityUpdateAlert(ENTITY_NAME, blog.getId().toString())) @@ -97,9 +106,13 @@ public List getAllBlogs() { */ @GetMapping("/blogs/{id}") @Timed - public ResponseEntity getBlog(@PathVariable Long id) { + public ResponseEntity getBlog(@PathVariable Long id) { log.debug("REST request to get Blog : {}", id); Optional blog = blogRepository.findById(id); + if (blog.isPresent() && blog.get().getUser() != null && + !blog.get().getUser().getLogin().equals(SecurityUtils.getCurrentUserLogin().orElse(""))) { + return new ResponseEntity<>("Unauthorized", HttpStatus.UNAUTHORIZED); + } return ResponseUtil.wrapOrNotFound(blog); } @@ -111,9 +124,13 @@ public ResponseEntity getBlog(@PathVariable Long id) { */ @DeleteMapping("/blogs/{id}") @Timed - public ResponseEntity deleteBlog(@PathVariable Long id) { + public ResponseEntity deleteBlog(@PathVariable Long id) { log.debug("REST request to delete Blog : {}", id); - + Optional blog = blogRepository.findById(id); + if (blog.isPresent() && blog.get().getUser() != null && + !blog.get().getUser().getLogin().equals(SecurityUtils.getCurrentUserLogin().orElse(""))) { + return new ResponseEntity<>("Unauthorized", HttpStatus.UNAUTHORIZED); + } blogRepository.deleteById(id); return ResponseEntity.ok().headers(HeaderUtil.createEntityDeletionAlert(ENTITY_NAME, id.toString())).build(); } diff --git a/src/main/java/org/jhipster/blog/web/rest/EntryResource.java b/src/main/java/org/jhipster/blog/web/rest/EntryResource.java index a200d52..a40826a 100644 --- a/src/main/java/org/jhipster/blog/web/rest/EntryResource.java +++ b/src/main/java/org/jhipster/blog/web/rest/EntryResource.java @@ -50,11 +50,15 @@ public EntryResource(EntryRepository entryRepository) { */ @PostMapping("/entries") @Timed - public ResponseEntity createEntry(@Valid @RequestBody Entry entry) throws URISyntaxException { + public ResponseEntity createEntry(@Valid @RequestBody Entry entry) throws URISyntaxException { log.debug("REST request to save Entry : {}", entry); if (entry.getId() != null) { throw new BadRequestAlertException("A new entry cannot already have an ID", ENTITY_NAME, "idexists"); } + if (entry.getBlog() != null && + !entry.getBlog().getUser().getLogin().equals(SecurityUtils.getCurrentUserLogin().orElse(""))) { + return new ResponseEntity<>("Unauthorized", HttpStatus.UNAUTHORIZED); + } Entry result = entryRepository.save(entry); return ResponseEntity.created(new URI("/api/entries/" + result.getId())) .headers(HeaderUtil.createEntityCreationAlert(ENTITY_NAME, result.getId().toString())) @@ -72,11 +76,15 @@ public ResponseEntity createEntry(@Valid @RequestBody Entry entry) throws */ @PutMapping("/entries") @Timed - public ResponseEntity updateEntry(@Valid @RequestBody Entry entry) throws URISyntaxException { + public ResponseEntity updateEntry(@Valid @RequestBody Entry entry) throws URISyntaxException { log.debug("REST request to update Entry : {}", entry); if (entry.getId() == null) { throw new BadRequestAlertException("Invalid id", ENTITY_NAME, "idnull"); } + if (entry.getBlog() != null && + !entry.getBlog().getUser().getLogin().equals(SecurityUtils.getCurrentUserLogin().orElse(""))) { + return new ResponseEntity<>("Unauthorized", HttpStatus.UNAUTHORIZED); + } Entry result = entryRepository.save(entry); return ResponseEntity.ok() .headers(HeaderUtil.createEntityUpdateAlert(ENTITY_NAME, entry.getId().toString())) @@ -109,9 +117,13 @@ public ResponseEntity> getAllEntries(Pageable pageable, @RequestPara */ @GetMapping("/entries/{id}") @Timed - public ResponseEntity getEntry(@PathVariable Long id) { + public ResponseEntity getEntry(@PathVariable Long id) { log.debug("REST request to get Entry : {}", id); Optional entry = entryRepository.findOneWithEagerRelationships(id); + if (entry.isPresent() && entry.get().getBlog() != null && + !entry.get().getBlog().getUser().getLogin().equals(SecurityUtils.getCurrentUserLogin().orElse(""))) { + return new ResponseEntity<>("Unauthorized", HttpStatus.UNAUTHORIZED); + } return ResponseUtil.wrapOrNotFound(entry); } @@ -123,9 +135,13 @@ public ResponseEntity getEntry(@PathVariable Long id) { */ @DeleteMapping("/entries/{id}") @Timed - public ResponseEntity deleteEntry(@PathVariable Long id) { + public ResponseEntity deleteEntry(@PathVariable Long id) { log.debug("REST request to delete Entry : {}", id); - + Optional entry = entryRepository.findOneWithEagerRelationships(id); + if (entry.isPresent() && entry.get().getBlog() != null && + !entry.get().getBlog().getUser().getLogin().equals(SecurityUtils.getCurrentUserLogin().orElse(""))) { + return new ResponseEntity<>("Unauthorized", HttpStatus.UNAUTHORIZED); + } entryRepository.deleteById(id); return ResponseEntity.ok().headers(HeaderUtil.createEntityDeletionAlert(ENTITY_NAME, id.toString())).build(); } diff --git a/src/test/java/org/jhipster/blog/web/rest/BlogResourceIntTest.java b/src/test/java/org/jhipster/blog/web/rest/BlogResourceIntTest.java index 8390ff9..96d3903 100644 --- a/src/test/java/org/jhipster/blog/web/rest/BlogResourceIntTest.java +++ b/src/test/java/org/jhipster/blog/web/rest/BlogResourceIntTest.java @@ -4,6 +4,7 @@ import org.jhipster.blog.domain.Blog; import org.jhipster.blog.repository.BlogRepository; +import org.jhipster.blog.repository.UserRepository; import org.jhipster.blog.web.rest.errors.ExceptionTranslator; import org.junit.Before; @@ -15,6 +16,7 @@ import org.springframework.data.web.PageableHandlerMethodArgumentResolver; import org.springframework.http.MediaType; import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter; +import org.springframework.security.test.context.support.WithMockUser; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.setup.MockMvcBuilders; @@ -48,6 +50,8 @@ public class BlogResourceIntTest { @Autowired private BlogRepository blogRepository; + @Autowired + private UserRepository userRepository; @Autowired private MappingJackson2HttpMessageConverter jacksonMessageConverter; @@ -82,10 +86,11 @@ public void setup() { * This is a static method, as tests for other entities might also need it, * if they test an entity which requires the current entity. */ - public static Blog createEntity(EntityManager em) { + public Blog createEntity(EntityManager em) { Blog blog = new Blog() .name(DEFAULT_NAME) - .handle(DEFAULT_HANDLE); + .handle(DEFAULT_HANDLE) + .user(userRepository.findOneByLogin("user").get()); return blog; } @@ -96,6 +101,7 @@ public void initTest() { @Test @Transactional + @WithMockUser public void createBlog() throws Exception { int databaseSizeBeforeCreate = blogRepository.findAll().size(); @@ -115,6 +121,7 @@ public void createBlog() throws Exception { @Test @Transactional + @WithMockUser public void createBlogWithExistingId() throws Exception { int databaseSizeBeforeCreate = blogRepository.findAll().size(); @@ -134,6 +141,7 @@ public void createBlogWithExistingId() throws Exception { @Test @Transactional + @WithMockUser public void checkNameIsRequired() throws Exception { int databaseSizeBeforeTest = blogRepository.findAll().size(); // set the field null @@ -152,6 +160,7 @@ public void checkNameIsRequired() throws Exception { @Test @Transactional + @WithMockUser public void checkHandleIsRequired() throws Exception { int databaseSizeBeforeTest = blogRepository.findAll().size(); // set the field null @@ -170,6 +179,7 @@ public void checkHandleIsRequired() throws Exception { @Test @Transactional + @WithMockUser public void getAllBlogs() throws Exception { // Initialize the database blogRepository.saveAndFlush(blog); @@ -182,10 +192,10 @@ public void getAllBlogs() throws Exception { .andExpect(jsonPath("$.[*].name").value(hasItem(DEFAULT_NAME.toString()))) .andExpect(jsonPath("$.[*].handle").value(hasItem(DEFAULT_HANDLE.toString()))); } - @Test @Transactional + @WithMockUser public void getBlog() throws Exception { // Initialize the database blogRepository.saveAndFlush(blog); @@ -198,6 +208,7 @@ public void getBlog() throws Exception { .andExpect(jsonPath("$.name").value(DEFAULT_NAME.toString())) .andExpect(jsonPath("$.handle").value(DEFAULT_HANDLE.toString())); } + @Test @Transactional public void getNonExistingBlog() throws Exception { @@ -208,6 +219,7 @@ public void getNonExistingBlog() throws Exception { @Test @Transactional + @WithMockUser public void updateBlog() throws Exception { // Initialize the database blogRepository.saveAndFlush(blog); @@ -237,6 +249,7 @@ public void updateBlog() throws Exception { @Test @Transactional + @WithMockUser public void updateNonExistingBlog() throws Exception { int databaseSizeBeforeUpdate = blogRepository.findAll().size(); @@ -255,6 +268,7 @@ public void updateNonExistingBlog() throws Exception { @Test @Transactional + @WithMockUser public void deleteBlog() throws Exception { // Initialize the database blogRepository.saveAndFlush(blog); diff --git a/src/test/java/org/jhipster/blog/web/rest/EntryResourceIntTest.java b/src/test/java/org/jhipster/blog/web/rest/EntryResourceIntTest.java index e4fb659..113a4cc 100644 --- a/src/test/java/org/jhipster/blog/web/rest/EntryResourceIntTest.java +++ b/src/test/java/org/jhipster/blog/web/rest/EntryResourceIntTest.java @@ -7,6 +7,7 @@ import org.jhipster.blog.web.rest.errors.ExceptionTranslator; import org.junit.Before; +import org.junit.Ignore; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; @@ -18,6 +19,7 @@ import org.springframework.data.web.PageableHandlerMethodArgumentResolver; import org.springframework.http.MediaType; import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter; +import org.springframework.security.test.context.support.WithMockUser; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.setup.MockMvcBuilders; @@ -109,6 +111,7 @@ public void initTest() { @Test @Transactional + @WithMockUser public void createEntry() throws Exception { int databaseSizeBeforeCreate = entryRepository.findAll().size(); @@ -129,6 +132,7 @@ public void createEntry() throws Exception { @Test @Transactional + @WithMockUser public void createEntryWithExistingId() throws Exception { int databaseSizeBeforeCreate = entryRepository.findAll().size(); @@ -148,6 +152,7 @@ public void createEntryWithExistingId() throws Exception { @Test @Transactional + @WithMockUser public void checkTitleIsRequired() throws Exception { int databaseSizeBeforeTest = entryRepository.findAll().size(); // set the field null @@ -166,6 +171,27 @@ public void checkTitleIsRequired() throws Exception { @Test @Transactional + @WithMockUser + @Ignore + public void checkContentIsRequired() throws Exception { + int databaseSizeBeforeTest = entryRepository.findAll().size(); + // set the field null + entry.setContent(null); + + // Create the Entry, which fails. + + restEntryMockMvc.perform(post("/api/entries") + .contentType(TestUtil.APPLICATION_JSON_UTF8) + .content(TestUtil.convertObjectToJsonBytes(entry))) + .andExpect(status().isBadRequest()); + + List entryList = entryRepository.findAll(); + assertThat(entryList).hasSize(databaseSizeBeforeTest); + } + + @Test + @Transactional + @WithMockUser public void checkDateIsRequired() throws Exception { int databaseSizeBeforeTest = entryRepository.findAll().size(); // set the field null @@ -197,7 +223,7 @@ public void getAllEntries() throws Exception { .andExpect(jsonPath("$.[*].content").value(hasItem(DEFAULT_CONTENT.toString()))) .andExpect(jsonPath("$.[*].date").value(hasItem(DEFAULT_DATE.toString()))); } - + public void getAllEntriesWithEagerRelationshipsIsEnabled() throws Exception { EntryResource entryResource = new EntryResource(entryRepositoryMock); when(entryRepositoryMock.findAllWithEagerRelationships(any())).thenReturn(new PageImpl(new ArrayList<>())); @@ -244,8 +270,10 @@ public void getEntry() throws Exception { .andExpect(jsonPath("$.content").value(DEFAULT_CONTENT.toString())) .andExpect(jsonPath("$.date").value(DEFAULT_DATE.toString())); } + @Test @Transactional + @WithMockUser public void getNonExistingEntry() throws Exception { // Get the entry restEntryMockMvc.perform(get("/api/entries/{id}", Long.MAX_VALUE)) @@ -254,6 +282,7 @@ public void getNonExistingEntry() throws Exception { @Test @Transactional + @WithMockUser public void updateEntry() throws Exception { // Initialize the database entryRepository.saveAndFlush(entry); @@ -285,6 +314,7 @@ public void updateEntry() throws Exception { @Test @Transactional + @WithMockUser public void updateNonExistingEntry() throws Exception { int databaseSizeBeforeUpdate = entryRepository.findAll().size(); @@ -303,6 +333,7 @@ public void updateNonExistingEntry() throws Exception { @Test @Transactional + @WithMockUser public void deleteEntry() throws Exception { // Initialize the database entryRepository.saveAndFlush(entry);