Skip to content

Commit 7cb8077

Browse files
committed
version 1.0
1 parent fb70b95 commit 7cb8077

File tree

8 files changed

+123
-10
lines changed

8 files changed

+123
-10
lines changed

BD/bd_sfm_msql.sql

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -15,4 +15,5 @@ CREATE TABLE empresa(
1515
-- EMPRESA
1616
INSERT INTO empresa (codigo,ruc,nombre,direccion,distrito,telefono,imagen) VALUE ('EP1','44445555777','Shoes For Men','Av. Carlos Izaguirre 233','Independencia','000-0000','https://raw.githubusercontent.com/paledot02/Img_Calzados/main/logo_reporte_01.png');
1717
-- https://raw.githubusercontent.com/paledot02/Img_Calzados/main/logo_reporte_02.png
18-
-- SELECT * FROM empresa;
18+
-- SELECT * FROM empresa;
19+

BD/bd_sfm_psql.sql

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -196,11 +196,13 @@ INSERT INTO rol (cod_rol, nombre_rol) VALUES ('RL01','ROLE_ADMIN');
196196
INSERT INTO rol (cod_rol, nombre_rol) VALUES ('RL02','ROLE_USER');
197197

198198
-- EMPLEADO -> SELECT * FROM empleado;
199-
INSERT INTO empleado (cod_empleado,cod_distrito,cod_estado,nombre,apellidos,dni,direccion,telefono,email,usuario,contrasena) VALUES ('EM10001','DI01','ES2','KEVIN','B','00000000','DIRECCION','999999999','paledot01@gmail.com','kevinB','$2a$10$Jtfxa0EuEjZrfQ4OvR4WbuqD00OBIfIp.5Sv33A7G8ya3xTI542nq');
199+
INSERT INTO empleado (cod_empleado,cod_distrito,cod_estado,nombre,apellidos,dni,direccion,telefono,email,usuario,contrasena) VALUES ('EM10001','DI01','ES2','KEVIN','B','00000000','DIRECCION','9999999','paledot01@gmail.com','kevinB','$2a$10$Jtfxa0EuEjZrfQ4OvR4WbuqD00OBIfIp.5Sv33A7G8ya3xTI542nq'); --pass: admin
200+
INSERT INTO empleado (cod_empleado,cod_distrito,cod_estado,nombre,apellidos,dni,direccion,telefono,email,usuario,contrasena) VALUES ('EM10002','DI02','ES2','PEDRO','C','11111111','DIRECCION2','8888888','pedro@gmail.com','pedroC','$2a$10$XoXoVkCDdDGeMHkDfM0/8.Q6Einje7.SWZiyggAv/XMMNKw89wFI2'); -- pass: 123
200201

201202
-- EMPLEADO-ROL -> SELECT * FROM empleado_rol;
202203
INSERT INTO empleado_rol (cod_rol,cod_empleado) VALUES ('RL01','EM10001');
203204
INSERT INTO empleado_rol (cod_rol,cod_empleado) VALUES ('RL02','EM10001');
205+
INSERT INTO empleado_rol (cod_rol,cod_empleado) VALUES ('RL02','EM10002');
204206

205207
-- MARCA -> SELECT * FROM marca; --> DELETE FROM marca WHERE cod_marca = 'MA10002'; --> UPDATE marca SET field='C', field2='Z' WHERE id=3;
206208
INSERT INTO marca (cod_marca, nombre_marca) VALUES ('MA10001','Calimod');

pom.xml

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -64,6 +64,15 @@
6464
<artifactId>jasperreports</artifactId>
6565
<version>6.19.0</version>
6666
</dependency>
67+
<dependency>
68+
<groupId>org.springframework.boot</groupId>
69+
<artifactId>spring-boot-starter-security</artifactId>
70+
</dependency>
71+
<dependency>
72+
<groupId>org.springframework.security</groupId>
73+
<artifactId>spring-security-test</artifactId>
74+
<scope>test</scope>
75+
</dependency>
6776
</dependencies>
6877

6978
<build>

src/main/java/com/cibertec/shoesformen_api/controller/DistritoController.java

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -26,12 +26,12 @@ public class DistritoController {
2626
private DistritoRepository distritoRepo;
2727

2828

29-
@GetMapping()
30-
public List<Distrito> all() {
31-
return distritoRepo.findAll();
32-
}
29+
// @GetMapping() // LISTAR -> SIN PAGINACION
30+
// public List<Distrito> all() {
31+
// return distritoRepo.findAll();
32+
// }
3333

34-
@GetMapping("/list")
34+
@GetMapping() // LISTA -> CON PAGINACION
3535
public ResponseEntity<List<Distrito>> getAllEmployees(
3636
@RequestParam(defaultValue = "0") Integer pageNo,
3737
@RequestParam(defaultValue = "3") Integer pageSize,

src/main/java/com/cibertec/shoesformen_api/exception/ApplicationExceptionHandler.java

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,6 @@
1717
@RestControllerAdvice
1818
public class ApplicationExceptionHandler {
1919

20-
2120
// Cuando la lista que devuelve esta vacia.
2221
@ExceptionHandler({ListEmptyException.class})
2322
public ResponseEntity<Objects> handleListEmptyException(ListEmptyException ex) {
@@ -33,7 +32,7 @@ public Map<String, String> handleFoundException(IllegalArgumentException ex) {
3332
return errorMap;
3433
}
3534

36-
// Cuando no encuentra la propiedad de una entidad
35+
// Cuando no encuentra la propiedad dentro de la entidad respectiva
3736
@ResponseStatus(HttpStatus.BAD_REQUEST)
3837
@ExceptionHandler({PropertyReferenceException.class})
3938
public Map<String, String> handlePropertyFoundException(PropertyReferenceException ex) {
Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
package com.cibertec.shoesformen_api.security;
2+
3+
import com.cibertec.shoesformen_api.model.Empleado;
4+
import com.cibertec.shoesformen_api.model.Rol;
5+
import com.cibertec.shoesformen_api.repository.EmpleadoRepository;
6+
import org.springframework.beans.factory.annotation.Autowired;
7+
import org.springframework.security.core.GrantedAuthority;
8+
import org.springframework.security.core.authority.SimpleGrantedAuthority;
9+
import org.springframework.security.core.userdetails.User;
10+
import org.springframework.security.core.userdetails.UserDetails;
11+
import org.springframework.security.core.userdetails.UserDetailsService;
12+
import org.springframework.security.core.userdetails.UsernameNotFoundException;
13+
import org.springframework.stereotype.Service;
14+
import org.springframework.transaction.annotation.Transactional;
15+
16+
import java.util.ArrayList;
17+
import java.util.List;
18+
19+
@Service
20+
public class EmpleadoDetailsService implements UserDetailsService {
21+
22+
@Autowired
23+
private EmpleadoRepository empleadoRepo;
24+
25+
@Override
26+
@Transactional(readOnly = true)
27+
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
28+
Empleado emp = empleadoRepo.findByUsuario(username);
29+
List<GrantedAuthority> autorizacion = new ArrayList<>();
30+
31+
if(emp == null) throw new UsernameNotFoundException("Usuario o password inválidos GAAAA");
32+
33+
for(Rol rol : emp.getRoles() ) {
34+
autorizacion.add(new SimpleGrantedAuthority(rol.getNombreRol()));
35+
}
36+
System.out.println(emp);
37+
System.out.println(autorizacion);
38+
return new User(emp.getUsuario(), emp.getContrasena(), true, true, true, true, autorizacion); // user, pass, roles
39+
}
40+
41+
}
Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
package com.cibertec.shoesformen_api.security;
2+
3+
import org.springframework.beans.factory.annotation.Autowired;
4+
import org.springframework.context.annotation.Bean;
5+
import org.springframework.context.annotation.Configuration;
6+
import org.springframework.http.HttpMethod;
7+
import org.springframework.security.authentication.AuthenticationProvider;
8+
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
9+
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
10+
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
11+
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
12+
import org.springframework.security.crypto.password.PasswordEncoder;
13+
import org.springframework.security.web.SecurityFilterChain;
14+
15+
@Configuration
16+
@EnableWebSecurity // si no lo anoto en alguna de mis clases la aplicacion pedirá nombre de usuario y contraseña
17+
public class SecurityConfiguration {
18+
19+
@Autowired
20+
private EmpleadoDetailsService empleadoDetails;
21+
22+
@Bean
23+
public PasswordEncoder encriptador() {
24+
// return NoOpPasswordEncoder.getInstance(); --> este codigo permite leer contraseñas sin codificar.
25+
return new BCryptPasswordEncoder(); // --> valida que las constraseñas sean del tipo BCryptPasswordEncoder
26+
}
27+
28+
@Bean
29+
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception{
30+
// Tenga en cuenta que el orden de los elementos antMatchers() es significativo; las reglas más
31+
// específicas deben ir primero, seguidas de las más generales(permitAll)
32+
http.httpBasic().and().authorizeHttpRequests()
33+
.requestMatchers(HttpMethod.POST,"/empleados").hasAnyRole("ADMIN") // solo los ADMIN pueden utilizar los POST, PUT, DELETE
34+
.requestMatchers(HttpMethod.PUT,"/empleados/**").hasAnyRole("ADMIN")
35+
.requestMatchers(HttpMethod.DELETE,"/empleados/**").hasAnyRole("ADMIN")
36+
.requestMatchers(HttpMethod.PUT,"/empresa/**").hasAnyRole("ADMIN")
37+
.requestMatchers(HttpMethod.GET,"/empleados").hasAnyRole("ADMIN","USER") // tanto los USER y ADMIN pueden utilizar los GET
38+
.requestMatchers(HttpMethod.GET,"/empleados/**").hasAnyRole("ADMIN","USER")
39+
.requestMatchers(HttpMethod.GET,"/distritos").hasAnyRole("ADMIN","USER")
40+
.requestMatchers(HttpMethod.GET,"/empresa").hasAnyRole("ADMIN","USER")
41+
.requestMatchers("/").hasAnyRole("ADMIN","USER")
42+
.requestMatchers("/img/**","/js/**","/css/**").permitAll()
43+
// .and().formLogin().successHandler(sucessHandler).loginPage("/login").loginProcessingUrl("/login")
44+
// .defaultSuccessUrl("/",true).permitAll()
45+
// .and().logout().clearAuthentication(true).invalidateHttpSession(true).logoutSuccessUrl("/login?logout").permitAll() //.logoutRequestMatcher(new AntPathRequestMatcher("/logout")).deleteCookies("JSESSIONID") // url[logout es el parametro que se envia] - para que no invalide la session - eliminar cookies.
46+
.and().csrf().disable(); // <-------- CSRF bloquea los metodos POST, y esta habilitado por defecto
47+
return http.build();
48+
}
49+
50+
@Bean
51+
public AuthenticationProvider authenticationProvider() {
52+
DaoAuthenticationProvider auth = new DaoAuthenticationProvider();
53+
auth.setUserDetailsService(empleadoDetails);
54+
auth.setPasswordEncoder(encriptador());
55+
return auth;
56+
}
57+
58+
}

src/main/java/com/cibertec/shoesformen_api/service/EmpleadoServiceImpl.java

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,7 @@
2929
import org.springframework.data.domain.Sort;
3030
import org.springframework.data.mapping.PropertyReferenceException;
3131
import org.springframework.http.HttpHeaders;
32+
import org.springframework.security.crypto.password.PasswordEncoder;
3233
import org.springframework.stereotype.Service;
3334

3435
import java.io.FileInputStream;
@@ -51,6 +52,8 @@ public class EmpleadoServiceImpl implements EmpleadoService{
5152
private EmpresaRepository empresaRepo;
5253
@Autowired
5354
private Validator validator;
55+
@Autowired
56+
private PasswordEncoder encriptador;
5457

5558
// LISTA NORMAL
5659
// @Override
@@ -140,7 +143,7 @@ public Empleado buildEmpleado(EmpleadoDTO dto) throws IllegalArgumentException {
140143
dto.getTelefono(),
141144
dto.getEmail(),
142145
dto.getUsuario(),
143-
dto.getContrasena(),
146+
encriptador.encode(dto.getContrasena()), // -> encriptamos la contraseña
144147
Arrays.asList(rol.get()));
145148
return empleado;
146149
}

0 commit comments

Comments
 (0)