Skip to content

Commit

Permalink
Add more controllers for demo.
Browse files Browse the repository at this point in the history
  • Loading branch information
czetsuya committed May 12, 2019
1 parent f048ca3 commit 6ee5f63
Show file tree
Hide file tree
Showing 14 changed files with 363 additions and 33 deletions.
41 changes: 41 additions & 0 deletions pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,48 @@
<groupId>org.keycloak</groupId>
<artifactId>keycloak-spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-rest-hal-browser</artifactId>
</dependency>

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-rest</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-hateoas</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.xml.bind</groupId>
<artifactId>jaxb-api</artifactId>
</dependency>
<dependency>
<groupId>com.sun.xml.bind</groupId>
<artifactId>jaxb-impl</artifactId>
<version>2.3.1</version>
</dependency>
<dependency>
<groupId>com.sun.xml.bind</groupId>
<artifactId>jaxb-core</artifactId>
<version>2.3.0.1</version>
</dependency>

<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
Expand Down
4 changes: 2 additions & 2 deletions src/main/java/com/broodcamp/SecurityConfig.java
Original file line number Diff line number Diff line change
Expand Up @@ -82,13 +82,13 @@ protected void configure(HttpSecurity http) throws Exception {
http.cors() //
.and() //
.csrf().disable() //
.anonymous().disable() //
// .anonymous().disable() //
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS) //
.and() //
.authorizeRequests() //
.antMatchers("/users*").hasRole("USER") //
.antMatchers("/admin*").hasRole("ADMIN") //
.anyRequest().denyAll(); //
.anyRequest().permitAll(); //
}

@Bean
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
package com.broodcamp.business.exception;

/**
* @author Edward P. Legaspi
*/
public class CustomerNotFoundException extends RuntimeException {

private static final long serialVersionUID = -3310173336873980506L;

public CustomerNotFoundException(Long id) {
super("Could not find customer " + id);
}

}
20 changes: 0 additions & 20 deletions src/main/java/com/broodcamp/controllers/UserController.java

This file was deleted.

31 changes: 31 additions & 0 deletions src/main/java/com/broodcamp/data/LoadDatabase.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
package com.broodcamp.data;

import org.springframework.boot.CommandLineRunner;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import com.broodcamp.data.entity.Customer;
import com.broodcamp.data.repository.CustomerRepository;

import lombok.extern.slf4j.Slf4j;

/**
* @author Edward P. Legaspi
*/
@Configuration
@Slf4j
public class LoadDatabase {

@Bean
CommandLineRunner initDatabase(final CustomerRepository customerRepository) {
return args -> {
log.debug("Preloading 6 customers");
customerRepository.save(new Customer("Kira Yamato", 16, "[email protected]"));
customerRepository.save(new Customer("Aerith Gainsborough", 16, "[email protected]"));
customerRepository.save(new Customer("Tifa Lockheart", 16, "[email protected]"));
customerRepository.save(new Customer("Garnet Til Alexandros", 16, "[email protected]"));
customerRepository.save(new Customer("Terra Branford", 16, "[email protected]"));
};
}

}
34 changes: 34 additions & 0 deletions src/main/java/com/broodcamp/data/entity/Customer.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
package com.broodcamp.data.entity;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

/**
* @author Edward P. Legaspi
*/
@Entity
@AllArgsConstructor
@NoArgsConstructor
@Data
public class Customer {

@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;

private String name;
private int age;
private String email;

public Customer(String name, int age, String email) {
this.name = name;
this.age = age;
this.email = email;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
package com.broodcamp.data.repository;

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;

import com.broodcamp.data.entity.Customer;

/**
* @author Edward P. Legaspi
*/
@Repository
public interface CustomerRepository extends JpaRepository<Customer, Long> {
}
60 changes: 60 additions & 0 deletions src/main/java/com/broodcamp/utils/SecurityContextUtils.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
package com.broodcamp.utils;

import java.util.HashSet;
import java.util.Set;

import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;

import lombok.extern.slf4j.Slf4j;

/**
* @author Edward P. Legaspi
*/
@Component
@Slf4j
public class SecurityContextUtils {

private static final String ANONYMOUS = "anonymous";

private SecurityContextUtils() {
}

public static String getUserName() {
SecurityContext securityContext = SecurityContextHolder.getContext();
Authentication authentication = securityContext.getAuthentication();
String username = ANONYMOUS;

if (null != authentication) {
if (authentication.getPrincipal() instanceof UserDetails) {
UserDetails springSecurityUser = (UserDetails) authentication.getPrincipal();
username = springSecurityUser.getUsername();

} else if (authentication.getPrincipal() instanceof String) {
username = (String) authentication.getPrincipal();

} else {
log.debug("User details not found in Security Context");
}

} else {
log.debug("Request not authenticated, hence no user name available");
}

return username;
}

public static Set<String> getUserRoles() {
SecurityContext securityContext = SecurityContextHolder.getContext();
Authentication authentication = securityContext.getAuthentication();
Set<String> roles = new HashSet<>();

if (null != authentication) {
authentication.getAuthorities().forEach(e -> roles.add(e.getAuthority()));
}
return roles;
}
}
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
package com.broodcamp.controllers;
package com.broodcamp.web.application;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,91 @@
package com.broodcamp.web.application;

import static org.springframework.hateoas.mvc.ControllerLinkBuilder.linkTo;
import static org.springframework.hateoas.mvc.ControllerLinkBuilder.methodOn;

import java.net.URI;
import java.net.URISyntaxException;
import java.util.List;
import java.util.stream.Collectors;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.hateoas.Resource;
import org.springframework.hateoas.Resources;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.broodcamp.business.exception.CustomerNotFoundException;
import com.broodcamp.data.entity.Customer;
import com.broodcamp.data.repository.CustomerRepository;
import com.broodcamp.web.assembler.CustomerResourceAssembler;

@RestController
@RequestMapping(value = "/v1/customers")
public class CustomerController {

@Autowired
private CustomerRepository repository;

@Autowired
private CustomerResourceAssembler assembler;

/**
* Get all the customer available in the underlying system
*
* @return list of customers
*/
@GetMapping
public Resources<Resource<Customer>> all() {
List<Resource<Customer>> entities = repository.findAll().stream().map(assembler::toResource).collect(Collectors.toList());

return new Resources<>(entities, linkTo(methodOn(CustomerController.class).all()).withSelfRel());
}

/**
* Create a customer with the system.This end point accepts customer information
* in the json format.It will create and send back the data to the REST
* customer.
*
* @param newCustomer
* @return newly created customer
* @throws URISyntaxException
*/
@PostMapping(value = "/")
public ResponseEntity<Resource<Customer>> newCustomer(@RequestBody Customer newCustomer) throws URISyntaxException {

Resource<Customer> resource = assembler.toResource(repository.save(newCustomer));
return ResponseEntity.created(new URI(resource.getId().expand().getHref())).body(resource);
}

/**
* Deleted the customer from the system.client will pass the ID for the customer
* and this end point will remove customer from the system if found.
*
* @param id
* @return
*/
@DeleteMapping(value = "/{id}")
public ResponseEntity<String> deleteCustomer(@PathVariable Long id) {
repository.deleteById(id);
return ResponseEntity.noContent().build();
}

/**
* Get the customer detail based on the id passed by the client API.
*
* @param id
* @return customer detail
*/
@GetMapping(value = "/{id}")
public Resource<Customer> one(@PathVariable Long id) {

Customer entity = repository.findById(id).orElseThrow(() -> new CustomerNotFoundException(id));
return assembler.toResource(entity);
}
}
38 changes: 38 additions & 0 deletions src/main/java/com/broodcamp/web/application/UserController.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
package com.broodcamp.web.application;

import java.util.Set;

import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.broodcamp.utils.SecurityContextUtils;

/**
* @author Edward P. Legaspi
*/
@RestController
@RequestMapping("/users")
//@PreAuthorize("hasRole('ADMIN') or hasRole('USER')")
public class UserController {

@GetMapping(path = "")
public String index() {
return "Users";
}

@GetMapping(path = "/user")
@PreAuthorize("hasAnyAuthority('USER')")
public ResponseEntity<String> getAuthorizedUserName() {
return ResponseEntity.ok(SecurityContextUtils.getUserName());
}

@GetMapping(path = "/roles")
@PreAuthorize("hasAnyAuthority('USER')")
public ResponseEntity<Set<String>> getAuthorizedUserRoles() {
return ResponseEntity.ok(SecurityContextUtils.getUserRoles());
}

}
Loading

0 comments on commit 6ee5f63

Please sign in to comment.