Skip to content

Commit

Permalink
Super secure
Browse files Browse the repository at this point in the history
  • Loading branch information
Matt Raible committed Jun 26, 2018
1 parent 916cd6d commit 9694891
Show file tree
Hide file tree
Showing 4 changed files with 92 additions and 14 deletions.
27 changes: 22 additions & 5 deletions src/main/java/org/jhipster/blog/web/rest/BlogResource.java
Original file line number Diff line number Diff line change
Expand Up @@ -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.*;

Expand Down Expand Up @@ -44,11 +46,14 @@ public BlogResource(BlogRepository blogRepository) {
*/
@PostMapping("/blogs")
@Timed
public ResponseEntity<Blog> 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()))
Expand All @@ -66,11 +71,15 @@ public ResponseEntity<Blog> createBlog(@Valid @RequestBody Blog blog) throws URI
*/
@PutMapping("/blogs")
@Timed
public ResponseEntity<Blog> 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()))
Expand All @@ -97,9 +106,13 @@ public List<Blog> getAllBlogs() {
*/
@GetMapping("/blogs/{id}")
@Timed
public ResponseEntity<Blog> getBlog(@PathVariable Long id) {
public ResponseEntity<?> getBlog(@PathVariable Long id) {
log.debug("REST request to get Blog : {}", id);
Optional<Blog> 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);
}

Expand All @@ -111,9 +124,13 @@ public ResponseEntity<Blog> getBlog(@PathVariable Long id) {
*/
@DeleteMapping("/blogs/{id}")
@Timed
public ResponseEntity<Void> deleteBlog(@PathVariable Long id) {
public ResponseEntity<?> deleteBlog(@PathVariable Long id) {
log.debug("REST request to delete Blog : {}", id);

Optional<Blog> 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();
}
Expand Down
26 changes: 21 additions & 5 deletions src/main/java/org/jhipster/blog/web/rest/EntryResource.java
Original file line number Diff line number Diff line change
Expand Up @@ -50,11 +50,15 @@ public EntryResource(EntryRepository entryRepository) {
*/
@PostMapping("/entries")
@Timed
public ResponseEntity<Entry> 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()))
Expand All @@ -72,11 +76,15 @@ public ResponseEntity<Entry> createEntry(@Valid @RequestBody Entry entry) throws
*/
@PutMapping("/entries")
@Timed
public ResponseEntity<Entry> 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()))
Expand Down Expand Up @@ -109,9 +117,13 @@ public ResponseEntity<List<Entry>> getAllEntries(Pageable pageable, @RequestPara
*/
@GetMapping("/entries/{id}")
@Timed
public ResponseEntity<Entry> getEntry(@PathVariable Long id) {
public ResponseEntity<?> getEntry(@PathVariable Long id) {
log.debug("REST request to get Entry : {}", id);
Optional<Entry> 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);
}

Expand All @@ -123,9 +135,13 @@ public ResponseEntity<Entry> getEntry(@PathVariable Long id) {
*/
@DeleteMapping("/entries/{id}")
@Timed
public ResponseEntity<Void> deleteEntry(@PathVariable Long id) {
public ResponseEntity<?> deleteEntry(@PathVariable Long id) {
log.debug("REST request to delete Entry : {}", id);

Optional<Entry> 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();
}
Expand Down
20 changes: 17 additions & 3 deletions src/test/java/org/jhipster/blog/web/rest/BlogResourceIntTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -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;
Expand Down Expand Up @@ -48,6 +50,8 @@ public class BlogResourceIntTest {
@Autowired
private BlogRepository blogRepository;

@Autowired
private UserRepository userRepository;

@Autowired
private MappingJackson2HttpMessageConverter jacksonMessageConverter;
Expand Down Expand Up @@ -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;
}

Expand All @@ -96,6 +101,7 @@ public void initTest() {

@Test
@Transactional
@WithMockUser
public void createBlog() throws Exception {
int databaseSizeBeforeCreate = blogRepository.findAll().size();

Expand All @@ -115,6 +121,7 @@ public void createBlog() throws Exception {

@Test
@Transactional
@WithMockUser
public void createBlogWithExistingId() throws Exception {
int databaseSizeBeforeCreate = blogRepository.findAll().size();

Expand All @@ -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
Expand All @@ -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
Expand All @@ -170,6 +179,7 @@ public void checkHandleIsRequired() throws Exception {

@Test
@Transactional
@WithMockUser
public void getAllBlogs() throws Exception {
// Initialize the database
blogRepository.saveAndFlush(blog);
Expand All @@ -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);
Expand All @@ -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 {
Expand All @@ -208,6 +219,7 @@ public void getNonExistingBlog() throws Exception {

@Test
@Transactional
@WithMockUser
public void updateBlog() throws Exception {
// Initialize the database
blogRepository.saveAndFlush(blog);
Expand Down Expand Up @@ -237,6 +249,7 @@ public void updateBlog() throws Exception {

@Test
@Transactional
@WithMockUser
public void updateNonExistingBlog() throws Exception {
int databaseSizeBeforeUpdate = blogRepository.findAll().size();

Expand All @@ -255,6 +268,7 @@ public void updateNonExistingBlog() throws Exception {

@Test
@Transactional
@WithMockUser
public void deleteBlog() throws Exception {
// Initialize the database
blogRepository.saveAndFlush(blog);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -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;
Expand Down Expand Up @@ -109,6 +111,7 @@ public void initTest() {

@Test
@Transactional
@WithMockUser
public void createEntry() throws Exception {
int databaseSizeBeforeCreate = entryRepository.findAll().size();

Expand All @@ -129,6 +132,7 @@ public void createEntry() throws Exception {

@Test
@Transactional
@WithMockUser
public void createEntryWithExistingId() throws Exception {
int databaseSizeBeforeCreate = entryRepository.findAll().size();

Expand All @@ -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
Expand All @@ -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<Entry> entryList = entryRepository.findAll();
assertThat(entryList).hasSize(databaseSizeBeforeTest);
}

@Test
@Transactional
@WithMockUser
public void checkDateIsRequired() throws Exception {
int databaseSizeBeforeTest = entryRepository.findAll().size();
// set the field null
Expand Down Expand Up @@ -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<>()));
Expand Down Expand Up @@ -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))
Expand All @@ -254,6 +282,7 @@ public void getNonExistingEntry() throws Exception {

@Test
@Transactional
@WithMockUser
public void updateEntry() throws Exception {
// Initialize the database
entryRepository.saveAndFlush(entry);
Expand Down Expand Up @@ -285,6 +314,7 @@ public void updateEntry() throws Exception {

@Test
@Transactional
@WithMockUser
public void updateNonExistingEntry() throws Exception {
int databaseSizeBeforeUpdate = entryRepository.findAll().size();

Expand All @@ -303,6 +333,7 @@ public void updateNonExistingEntry() throws Exception {

@Test
@Transactional
@WithMockUser
public void deleteEntry() throws Exception {
// Initialize the database
entryRepository.saveAndFlush(entry);
Expand Down

0 comments on commit 9694891

Please sign in to comment.