Skip to content

Commit

Permalink
Super secure + fix blog test
Browse files Browse the repository at this point in the history
  • Loading branch information
Matt Raible committed Jun 24, 2019
1 parent 539cfb7 commit 73bd82f
Show file tree
Hide file tree
Showing 3 changed files with 57 additions and 11 deletions.
26 changes: 22 additions & 4 deletions src/main/java/org/jhipster/blog/web/rest/BlogResource.java
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,15 @@

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 io.github.jhipster.web.util.HeaderUtil;
import io.github.jhipster.web.util.ResponseUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

Expand Down Expand Up @@ -47,11 +49,14 @@ public BlogResource(BlogRepository blogRepository) {
* @throws URISyntaxException if the Location URI syntax is incorrect.
*/
@PostMapping("/blogs")
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<>("error.http.403", HttpStatus.FORBIDDEN);
}
Blog result = blogRepository.save(blog);
return ResponseEntity.created(new URI("/api/blogs/" + result.getId()))
.headers(HeaderUtil.createEntityCreationAlert(applicationName, true, ENTITY_NAME, result.getId().toString()))
Expand All @@ -68,11 +73,15 @@ public ResponseEntity<Blog> createBlog(@Valid @RequestBody Blog blog) throws URI
* @throws URISyntaxException if the Location URI syntax is incorrect.
*/
@PutMapping("/blogs")
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<>("error.http.403", HttpStatus.FORBIDDEN);
}
Blog result = blogRepository.save(blog);
return ResponseEntity.ok()
.headers(HeaderUtil.createEntityUpdateAlert(applicationName, true, ENTITY_NAME, blog.getId().toString()))
Expand All @@ -97,9 +106,13 @@ public List<Blog> getAllBlogs() {
* @return the {@link ResponseEntity} with status {@code 200 (OK)} and with body the blog, or with status {@code 404 (Not Found)}.
*/
@GetMapping("/blogs/{id}")
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<>("error.http.403", HttpStatus.FORBIDDEN);
}
return ResponseUtil.wrapOrNotFound(blog);
}

Expand All @@ -110,8 +123,13 @@ public ResponseEntity<Blog> getBlog(@PathVariable Long id) {
* @return the {@link ResponseEntity} with status {@code 204 (NO_CONTENT)}.
*/
@DeleteMapping("/blogs/{id}")
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<>("error.http.403", HttpStatus.FORBIDDEN);
}
blogRepository.deleteById(id);
return ResponseEntity.noContent().headers(HeaderUtil.createEntityDeletionAlert(applicationName, true, ENTITY_NAME, id.toString())).build();
}
Expand Down
25 changes: 21 additions & 4 deletions src/main/java/org/jhipster/blog/web/rest/EntryResource.java
Original file line number Diff line number Diff line change
Expand Up @@ -55,12 +55,16 @@ public EntryResource(EntryRepository entryRepository) {
* @throws URISyntaxException if the Location URI syntax is incorrect.
*/
@PostMapping("/entries")
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");
}
Entry result = entryRepository.save(entry);
if (entry.getBlog() != null &&
!entry.getBlog().getUser().getLogin().equals(SecurityUtils.getCurrentUserLogin().orElse(""))) {
return new ResponseEntity<>("Unauthorized", HttpStatus.UNAUTHORIZED);
}
return ResponseEntity.created(new URI("/api/entries/" + result.getId()))
.headers(HeaderUtil.createEntityCreationAlert(applicationName, true, ENTITY_NAME, result.getId().toString()))
.body(result);
Expand All @@ -76,11 +80,15 @@ public ResponseEntity<Entry> createEntry(@Valid @RequestBody Entry entry) throws
* @throws URISyntaxException if the Location URI syntax is incorrect.
*/
@PutMapping("/entries")
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(applicationName, true, ENTITY_NAME, entry.getId().toString()))
Expand Down Expand Up @@ -111,9 +119,13 @@ public ResponseEntity<List<Entry>> getAllEntries(Pageable pageable, @RequestPara
* @return the {@link ResponseEntity} with status {@code 200 (OK)} and with body the entry, or with status {@code 404 (Not Found)}.
*/
@GetMapping("/entries/{id}")
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 @@ -124,8 +136,13 @@ public ResponseEntity<Entry> getEntry(@PathVariable Long id) {
* @return the {@link ResponseEntity} with status {@code 204 (NO_CONTENT)}.
*/
@DeleteMapping("/entries/{id}")
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.noContent().headers(HeaderUtil.createEntityDeletionAlert(applicationName, true, ENTITY_NAME, id.toString())).build();
}
Expand Down
17 changes: 14 additions & 3 deletions src/test/java/org/jhipster/blog/web/rest/BlogResourceIT.java
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
import org.jhipster.blog.BlogApp;
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.jupiter.api.BeforeEach;
Expand All @@ -13,6 +14,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.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.transaction.annotation.Transactional;
Expand Down Expand Up @@ -54,6 +56,9 @@ public class BlogResourceIT {
@Autowired
private EntityManager em;

@Autowired
private UserRepository userRepository;

@Autowired
private Validator validator;

Expand All @@ -79,10 +84,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 @@ -105,6 +111,7 @@ public void initTest() {

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

Expand Down Expand Up @@ -180,6 +187,7 @@ public void checkHandleIsRequired() throws Exception {

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

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

@Test
@Transactional
@WithMockUser
public void deleteBlog() throws Exception {
// Initialize the database
blogRepository.saveAndFlush(blog);
Expand Down

0 comments on commit 73bd82f

Please sign in to comment.