Compare commits

..

1 Commits

Author SHA1 Message Date
Freddy Heredia 238ebe231a agrega spring security
2 years ago

@ -27,7 +27,7 @@ dependencies {
annotationProcessor 'org.projectlombok:lombok'
testImplementation 'org.springframework.boot:spring-boot-starter-test'
implementation 'org.springframework.boot:spring-boot-starter-security'
implementation 'org.springdoc:springdoc-openapi-starter-webmvc-ui:2.0.2'
implementation 'org.springdoc:springdoc-openapi-starter-webmvc-ui:2.0.2'
implementation 'org.springdoc:springdoc-openapi-starter-common:2.0.2'
implementation 'org.hibernate.validator:hibernate-validator:8.0.0.Final'
implementation 'io.jsonwebtoken:jjwt:0.9.1'

@ -107,7 +107,7 @@ public class JWTAuthenticationFilter extends UsernamePasswordAuthenticationFilte
public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception)
throws IOException, ServletException {
response.setStatus(401);
response.setContentType("application/json; charset=utf-8");
response.setContentType("application/json");
response.getWriter().append(json(exception.getLocalizedMessage()));
}
@ -117,7 +117,7 @@ public class JWTAuthenticationFilter extends UsernamePasswordAuthenticationFilte
return "{\"timestamp\": " + date + ", "
+ "\"status\": 401, "
+ "\"error\": \"Not authorized\", "
+ "\"message\": \""+ message+ "\", "
+ "\"message\": "+ message+ ", "
+ "\"path\": \"/login\"}";
}
}

@ -1,8 +1,5 @@
package erp.pedidos.authz.conf;
import java.util.Arrays;
import java.util.Collections;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@ -11,10 +8,6 @@ import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.www.BasicAuthenticationFilter;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.CorsConfigurationSource;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import erp.pedidos.authz.service.UserService;
@Configuration
@ -30,8 +23,6 @@ public class SecurityConfiguration{
http
.csrf().disable()
.cors()
.and()
.authorizeHttpRequests((authorize) -> authorize
.requestMatchers("/login").permitAll()
.requestMatchers("/swagger-ui/*").permitAll()
@ -45,33 +36,4 @@ public class SecurityConfiguration{
return http.build();
}
@Bean
protected CorsConfigurationSource corsConfigurationSource() {
final CorsConfiguration configuration = new CorsConfiguration();
configuration.setAllowedOrigins(Collections.singletonList("http://localhost:3000"));
configuration.setAllowedMethods(Arrays.asList("HEAD", "GET", "POST", "PUT", "DELETE", "PATCH"));
// NOTE: setAllowCredentials(true) is important,
// otherwise, the value of the 'Access-Control-Allow-Origin' header in the response
// must not be the wildcard '*' when the request's credentials mode is 'include'.
configuration.setAllowCredentials(true);
// NOTE: setAllowedHeaders is important!
// Without it, OPTIONS preflight request will fail with 403 Invalid CORS request
configuration.setAllowedHeaders(Arrays.asList(
"Authorization",
"Accept",
"Cache-Control",
"Content-Type",
"Origin",
"x-csrf-token",
"x-requested-with"
));
final UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", configuration);
return source;
}
}

@ -5,7 +5,6 @@ import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
@ -17,27 +16,20 @@ import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
@RestController
@RequestMapping("/api/ciudad")
@CrossOrigin({"*"})
@Tag(name = "Controlador de ciudades, tabla (ciudad)")
public class CiudadController {
@Autowired
CiudadService service;
@Operation(summary = "Obtiene una ciudad por su identificador pasado como parametro en {id}")
@GetMapping("/{id}/")
public Ciudad findById(@PathVariable long id){
return service.findById(id);
}
@Operation(summary = "Obtiene todas las ciudades en un arreglo, requiere el permiso: Ciudad_LeerTodas")
@GetMapping("/")
@PreAuthorize("hasAuthority('Ciudad_LeerTodas')")
public List<Ciudad> findAll(){
return service.findAll();
}

@ -5,7 +5,6 @@ import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
@ -16,8 +15,6 @@ import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
@RestController
@RequestMapping("/api/cliente")
@ -28,12 +25,10 @@ public class ClienteController {
ClienteService service;
@GetMapping("/{id}/")
public Cliente findById(@PathVariable long id){
return service.findById(id);
}
@PreAuthorize("hasAuthority('Cliente_LeerTodos')")
@GetMapping("/")
public List<Cliente> findAll(){
return service.findAll();
@ -46,7 +41,6 @@ public class ClienteController {
return service.save(entity);
}
@PreAuthorize("hasAuthority('Cliente_Actualizar')")
@PutMapping("/")
public Cliente update (@RequestBody Cliente entity){
return service.save(entity);
@ -71,9 +65,7 @@ public class ClienteController {
try {
Field campoEntidad = Cliente.class.getDeclaredField(fieldName);
campoEntidad.setAccessible(true);
ObjectMapper mapper = new ObjectMapper();
mapper.registerModule(new JavaTimeModule());
campoEntidad.set(entity, mapper.convertValue(fieldValue, campoEntidad.getType()));
campoEntidad.set(entity, fieldValue);
} catch (NoSuchFieldException | IllegalAccessException ex) {
// maneja la excepción si ocurre algún error al acceder al campo
}

@ -1,25 +0,0 @@
package erp.pedidos.pedido;
import java.math.BigDecimal;
import erp.pedidos.producto.Producto;
import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
import lombok.Data;
import jakarta.persistence.ManyToOne;
@Data
@Entity
public class DetallePedido {
@Id
@GeneratedValue(strategy = GenerationType.AUTO )
private Integer id;
@ManyToOne
private Producto producto;
private BigDecimal precio;
private Integer cantidad;
}

@ -1,34 +0,0 @@
package erp.pedidos.pedido;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;
import erp.pedidos.cliente.Cliente;
import jakarta.persistence.CascadeType;
import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
import jakarta.persistence.JoinColumn;
import jakarta.persistence.ManyToOne;
import jakarta.persistence.OneToMany;
import lombok.Data;
@Data
@Entity
public class Pedido {
@Id
@GeneratedValue(strategy = GenerationType.AUTO )
private Integer id;
private Integer numero;
private LocalDate fecha;
@ManyToOne
private Cliente cliente;
@OneToMany(cascade = CascadeType.ALL, orphanRemoval = true)
@JoinColumn(name="pedido_id")
private List<DetallePedido> detalle = new ArrayList<>();
}

@ -1,76 +0,0 @@
package erp.pedidos.pedido;
import java.lang.reflect.Field;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PatchMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/api/pedido")
@CrossOrigin({"*"})
public class PedidoController {
@Autowired
PedidoService service;
@GetMapping("/{id}/")
public Pedido findById(@PathVariable Integer id){
return service.findById(id);
}
@GetMapping("/")
public List<Pedido> findAll(){
return service.findAll();
}
//Create
//Delimitador de acceso (public, private), tipo de dato de retorno, nombre del método, parametros de entrada { Sentencias }
@PostMapping("/")
public Pedido save (@RequestBody Pedido entity ){
return service.save(entity);
}
@PutMapping("/")
public Pedido update (@RequestBody Pedido entity){
return service.save(entity);
}
@DeleteMapping("/{id}/")
public void deleteById(@PathVariable Integer id){
service.deleteById(id);
}
@PatchMapping("/{id}/")
public Pedido partialUpdate(@PathVariable Integer id, @RequestBody Map<String, Object> fields){
Pedido entity = findById(id);
// itera sobre los campos que se desean actualizar
for (Map.Entry<String, Object> field : fields.entrySet()) {
String fieldName = field.getKey();
Object fieldValue = field.getValue();
// utiliza reflection para establecer el valor del campo en la entidad
try {
Field campoEntidad = Pedido.class.getDeclaredField(fieldName);
campoEntidad.setAccessible(true);
campoEntidad.set(entity, fieldValue);
} catch (NoSuchFieldException | IllegalAccessException ex) {
// maneja la excepción si ocurre algún error al acceder al campo
}
}
return update(entity);
}
}

@ -1,10 +0,0 @@
package erp.pedidos.pedido;
import java.util.List;
import org.springframework.data.repository.CrudRepository;
public interface PedidoRepository extends CrudRepository <Pedido, Integer> {
List<Pedido> findAll();
}

@ -1,28 +0,0 @@
package erp.pedidos.pedido;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class PedidoService {
@Autowired
PedidoRepository repository;
public Pedido save( Pedido entity){
return repository.save(entity);
}
public void deleteById(Integer id){
repository.deleteById(id);
}
public Pedido findById(Integer id){
return repository.findById(id).orElse(null);
}
public List<Pedido> findAll(){
return repository.findAll();
}
}

@ -16,9 +16,6 @@ import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
@RestController
@RequestMapping("/api/producto")
@CrossOrigin({"*"})
@ -68,9 +65,7 @@ public class ProductoController {
try {
Field campoEntidad = Producto.class.getDeclaredField(fieldName);
campoEntidad.setAccessible(true);
ObjectMapper mapper = new ObjectMapper();
mapper.registerModule(new JavaTimeModule());
campoEntidad.set(producto, mapper.convertValue(fieldValue, campoEntidad.getType()));
campoEntidad.set(producto, fieldValue);
} catch (NoSuchFieldException | IllegalAccessException ex) {
// maneja la excepción si ocurre algún error al acceder al campo
}

@ -15,8 +15,6 @@ import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
@RestController
@RequestMapping("/api/provincia")
@ -67,9 +65,7 @@ public class ProvinciaController {
try {
Field campoEntidad = Provincia.class.getDeclaredField(fieldName);
campoEntidad.setAccessible(true);
ObjectMapper mapper = new ObjectMapper();
mapper.registerModule(new JavaTimeModule());
campoEntidad.set(entity, mapper.convertValue(fieldValue, campoEntidad.getType()));
campoEntidad.set(entity, fieldValue);
} catch (NoSuchFieldException | IllegalAccessException ex) {
// maneja la excepción si ocurre algún error al acceder al campo
}

Loading…
Cancel
Save