Autenticacion basica agregada

parent a2013f11
...@@ -63,6 +63,11 @@ ...@@ -63,6 +63,11 @@
<artifactId>jstl</artifactId> <artifactId>jstl</artifactId>
<version>1.2</version> <version>1.2</version>
</dependency> </dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
</dependencies> </dependencies>
<build> <build>
......
package com.roshka.configuration;
import java.util.Collection;
import com.roshka.modelo.RRHHUser;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
public class CustomUserDetails implements UserDetails {
private RRHHUser user;
public CustomUserDetails(RRHHUser user) {
this.user = user;
}
@Override
public Collection<? extends GrantedAuthority> getAuthorities() {
return null;
}
@Override
public String getPassword() {
return user.getPassword();
}
@Override
public String getUsername() {
return user.getEmail();
}
@Override
public boolean isAccountNonExpired() {
return true;
}
@Override
public boolean isAccountNonLocked() {
return true;
}
@Override
public boolean isCredentialsNonExpired() {
return true;
}
@Override
public boolean isEnabled() {
return true;
}
public String getFullName() {
return user.getFirstName() + " " + user.getLastName();
}
}
\ No newline at end of file
package com.roshka.configuration;
import com.roshka.modelo.RRHHUser;
import com.roshka.repositorio.RRHHUserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
public class CustomUserDetailsService implements UserDetailsService {
@Autowired
private RRHHUserRepository userRepo;
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
RRHHUser user = userRepo.findByEmail(username);
if (user == null) {
throw new UsernameNotFoundException("User not found");
}
return new CustomUserDetails(user);
}
}
package com.roshka.configuration;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import javax.sql.DataSource;
@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private DataSource dataSource;
@Bean
public UserDetailsService userDetailsService() {
return new CustomUserDetailsService();
}
@Bean
public BCryptPasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
@Bean
public DaoAuthenticationProvider authenticationProvider() {
DaoAuthenticationProvider authProvider = new DaoAuthenticationProvider();
authProvider.setUserDetailsService(userDetailsService());
authProvider.setPasswordEncoder(passwordEncoder());
return authProvider;
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.authenticationProvider(authenticationProvider());
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/").authenticated()
.antMatchers("/home").authenticated()
.anyRequest().permitAll()
.and()
.formLogin()
.usernameParameter("email")
.defaultSuccessUrl("/home")
.permitAll()
.and()
.logout().logoutSuccessUrl("/").permitAll();
}
}
\ No newline at end of file
package com.roshka.controller; package com.roshka.controller;
import java.util.List;
import javax.validation.ConstraintViolationException; import javax.validation.ConstraintViolationException;
...@@ -13,12 +12,7 @@ import com.roshka.modelo.EstadoCivil; ...@@ -13,12 +12,7 @@ import com.roshka.modelo.EstadoCivil;
import com.roshka.modelo.Nacionalidad; import com.roshka.modelo.Nacionalidad;
import com.roshka.modelo.Postulante; import com.roshka.modelo.Postulante;
import com.roshka.modelo.TipoExperiencia; import com.roshka.modelo.TipoExperiencia;
import com.roshka.repositorio.CiudadRepository; import com.roshka.repositorio.*;
import com.roshka.repositorio.DepartamentoRepository;
import com.roshka.repositorio.ExperienciaRepository;
import com.roshka.repositorio.InstitucionRepository;
import com.roshka.repositorio.PostulanteRepository;
import com.roshka.repositorio.TecnologiaRepository;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus; import org.springframework.http.HttpStatus;
...@@ -31,6 +25,7 @@ import org.springframework.web.bind.annotation.*; ...@@ -31,6 +25,7 @@ import org.springframework.web.bind.annotation.*;
@Controller @Controller
@RequestMapping("/")
public class PostulanteController { public class PostulanteController {
PostulanteRepository post; PostulanteRepository post;
TecnologiaRepository tecRepo; TecnologiaRepository tecRepo;
...@@ -40,7 +35,10 @@ public class PostulanteController { ...@@ -40,7 +35,10 @@ public class PostulanteController {
CiudadRepository ciuRepo; CiudadRepository ciuRepo;
@Autowired @Autowired
public PostulanteController(PostulanteRepository post, TecnologiaRepository tecRepo, ExperienciaRepository expRepo, InstitucionRepository institucionRepository, DepartamentoRepository depRepo, CiudadRepository ciuRepo) { public PostulanteController(
PostulanteRepository post, TecnologiaRepository tecRepo, ExperienciaRepository expRepo,
InstitucionRepository institucionRepository, DepartamentoRepository depRepo,
CiudadRepository ciuRepo) {
this.post = post; this.post = post;
this.tecRepo = tecRepo; this.tecRepo = tecRepo;
this.expRepo = expRepo; this.expRepo = expRepo;
...@@ -49,8 +47,7 @@ public class PostulanteController { ...@@ -49,8 +47,7 @@ public class PostulanteController {
this.ciuRepo = ciuRepo; this.ciuRepo = ciuRepo;
} }
@RequestMapping("home")
@RequestMapping("/")
public String index() { public String index() {
......
package com.roshka.controller;
import com.roshka.modelo.RRHHUser;
import com.roshka.repositorio.RRHHUserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import javax.servlet.http.HttpServletRequest;
@Controller
public class RRHHUserController {
private static final long REGISTER_CODE = 1234;
RRHHUserRepository rrhhUserRepository;
@Autowired
public RRHHUserController(RRHHUserRepository rrhhUserRepository){
this.rrhhUserRepository = rrhhUserRepository;
}
@GetMapping("/register")
public String showRegistrationForm(Model model) {
model.addAttribute("user", new RRHHUser());
return "registration";
}
@PostMapping("/process_register")
public String processRegister(HttpServletRequest request, RRHHUser user) {
if(Long.parseLong(request.getParameter("registrationCode")) != REGISTER_CODE){
return "redirect:/register";
}
BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
String encodedPassword = passwordEncoder.encode(user.getPassword());
user.setPassword(encodedPassword);
rrhhUserRepository.save(user);
return "register_success";
}
}
package com.roshka.modelo;
import javax.persistence.*;
@Entity
@Table(name = "recursos_humanos_user")
public class RRHHUser {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@Column(nullable = false, unique = true, length = 45)
private String email;
@Column(nullable = false, length = 64)
private String password;
@Column(name = "first_name", nullable = false, length = 20)
private String firstName;
@Column(name = "last_name", nullable = false, length = 20)
private String lastName;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
}
package com.roshka.repositorio;
import com.roshka.modelo.RRHHUser;
import org.springframework.data.jpa.repository.JpaRepository;
public interface RRHHUserRepository extends JpaRepository<RRHHUser, Long> {
RRHHUser findByEmail(String username);
}
spring.jpa.hibernate.ddl-auto=create-drop spring.jpa.hibernate.ddl-auto=create-drop
spring.jpa.database-platform=org.hibernate.dialect.PostgreSQLDialect spring.jpa.database-platform=org.hibernate.dialect.PostgreSQLDialect
spring.jpa.show-sql=true #spring.jpa.show-sql=true
spring.jpa.properties.hibernate.format_sql=true spring.jpa.properties.hibernate.format_sql=true
logging.level.org.hibernate.SQL=DEBUG #logging.level.org.hibernate.SQL=DEBUG
logging.level.org.hibernate.type.descriptor.sql.BasicBinder=TRACE #logging.level.org.hibernate.type.descriptor.sql.BasicBinder=TRACE
spring.sql.init.mode=always spring.sql.init.mode=always
spring.sql.init.platform=postgres spring.sql.init.platform=postgres
......
<!DOCTYPE html> <!DOCTYPE html>
<html lang="en"> <html lang="en">
<head> <head>
...@@ -8,5 +9,13 @@ ...@@ -8,5 +9,13 @@
</head> </head>
<body> <body>
<a href="postulante">Form postulante</a> <a href="postulante">Form postulante</a>
<div>
<form action="/logout" method="get">
<p>
Welcome
</p>
<input type="submit" value="Sign Out" />
</form>
</div>
</body> </body>
</html> </html>
\ No newline at end of file
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Registration Success</title>
<link rel="stylesheet" type="text/css" href="/webjars/bootstrap/css/bootstrap.min.css" />
</head>
<body>
<div class="container text-center">
<h3>You have signed up successfully!</h3>
<h4><a href="${pageContext.request.contextPath}/login">Click here to Login</a></h4>
</div>
</body>
</html>
\ No newline at end of file
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Registration Success</title>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js" integrity="sha384-ka7Sk0Gln4gmtz2MlQnikT1wXgYsOg+OMhuP+IlRH9sENBO0LRn5q+8nbTov4+1p" crossorigin="anonymous"></script>
</head>
<style>
@media (min-width: 1025px) {
.h-custom {
height: 100vh !important;
}
}
</style>
<body>
<section class="h-100 h-custom">
<div class="container py-5 h-100">
<div class="row d-flex justify-content-center align-items-center h-100">
<div class="col-lg-8 col-xl-6">
<div class="card rounded-3">
<img src="https://cdn.pixabay.com/photo/2013/08/09/05/54/layer-170971_960_720.jpg" class="w-100" style="border-top-left-radius: .3rem; border-top-right-radius: .3rem;height: 250px;" alt="Sample photo";>
<div class="card-body p-4 p-md-5">
<h3 class="mb-4 pb-2 pb-md-0 mb-md-5 px-md-2">Informacion de Registro</h3>
<form:form action="/process_register" class="px-md-2" method="POST" modelAttribute="user">
<div class="form-outline mb-4">
<form:label path="email" class="form-label">Email</form:label>
<form:input path="email" class="form-control" required="required"></form:input>
</div>
<div class="row">
<div class="col-md-6 mb-4">
<div class="form-outline">
<form:label path="firstName" class="form-label">Nombre </form:label>
<form:input path="firstName" class="form-control"></form:input>
</div>
</div>
<div class="col-md-6 mb-4">
<div class="form-outline">
<form:label path="lastName" class="form-label">Apellido </form:label>
<form:input path="lastName" class="form-control"></form:input>
</div>
</div>
</div>
<div class="mb-4">
<form:label path="password" class="form-label">Contrasena</form:label>
<form:input type="password" path="password" class="form-control" required="required"></form:input>
</div>
<div class="row mb-4 pb-2 pb-md-0 mb-md-5">
<div class="col-md-6">
<div class="form-outline">
<input type="text" id="form3Example1w" class="form-control" name="registrationCode" required/>
<label class="form-label" for="form3Example1w">Registration code</label>
</div>
</div>
</div>
<button type="submit" class="btn btn-success btn-lg mb-1">Submit</button>
</form:form>
</div>
</div>
</div>
</div>
</div>
</section>
</body>
</html>
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment