Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 14 additions & 4 deletions pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -34,12 +34,12 @@
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-web</artifactId>
</dependency>

<!-- TOOLS -->
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
Expand All @@ -50,12 +50,22 @@
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt</artifactId>
<version>0.9.0</version>
</dependency>

<!-- TEST -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
</dependencies>

<build>
Expand Down
16 changes: 16 additions & 0 deletions src/main/java/it/myti/academy/backend/config/CryptConfig.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
package it.myti.academy.backend.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

@Configuration
public class CryptConfig {

@Bean
public BCryptPasswordEncoder bCryptPasswordEncoder() {
return new BCryptPasswordEncoder();
}


}
43 changes: 43 additions & 0 deletions src/main/java/it/myti/academy/backend/config/WebSecurity.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
package it.myti.academy.backend.config;

import it.myti.academy.backend.filter.JWTAuthenticationFilter;
import it.myti.academy.backend.filter.JWTAuthorizationFilter;
import it.myti.academy.backend.filter.SecurityConstants;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.http.HttpMethod;
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;


@EnableWebSecurity
public class WebSecurity extends WebSecurityConfigurerAdapter implements SecurityConstants {
private UserDetailsService userDetailsService;
private BCryptPasswordEncoder bCryptPasswordEncoder;

@Autowired
public WebSecurity(@Qualifier("userDetailsServiceImpl") UserDetailsService userDetailsService, BCryptPasswordEncoder bCryptPasswordEncoder) {
this.userDetailsService = userDetailsService;
this.bCryptPasswordEncoder = bCryptPasswordEncoder;
}
@Override
protected void configure(HttpSecurity http) throws Exception {

http.csrf().disable().authorizeRequests()
.antMatchers("/h2-console/**").permitAll()
.antMatchers(HttpMethod.POST, "/registrazione").permitAll()
.anyRequest().authenticated()
.and()
.addFilter(new JWTAuthenticationFilter(authenticationManager()))
.addFilter(new JWTAuthorizationFilter(authenticationManager()));
http.headers().frameOptions().disable();
}
@Override
public void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userDetailsService).passwordEncoder(bCryptPasswordEncoder);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,9 @@

import it.myti.academy.backend.model.Collo;
import it.myti.academy.backend.model.Utente;
import it.myti.academy.backend.repository.UtenteRepository;
import it.myti.academy.backend.model.errori.eccezioni.UtenteNonTrovatoException;
import it.myti.academy.backend.service.ColloService;
import it.myti.academy.backend.service.UtenteService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
Expand All @@ -14,20 +15,22 @@
/**
* Created by david at 2019-03-07
*/
@RestController("/collo")
@RestController
public class ColliController {

@Autowired
ColloService colloService;

@Autowired
UtenteRepository utenteRepository;
UtenteService utenteService;

@GetMapping("/collo/utente/{id}")
public List<Collo> getByUtente(@PathVariable("id") long id) throws UtenteNonTrovatoException {


@GetMapping("/utente/{id}")
public List<Collo> getByUtente(@PathVariable("id") long id) {
List<Collo> returnValue = null;

final Utente utente = utenteRepository.findById(id).get();
final Utente utente = utenteService.getById(id);
if(utente!=null) {
returnValue = colloService.getSpedizioniAttiveByUtente(utente);
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
package it.myti.academy.backend.controller;

import it.myti.academy.backend.model.entitaRisposte.DettagliUnitaLogisticaUtente;
import it.myti.academy.backend.model.errori.*;
import it.myti.academy.backend.model.errori.eccezioni.*;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler;

@ControllerAdvice
@RestController
public class EccezioniController extends ResponseEntityExceptionHandler {

@ExceptionHandler(UnitaLogisticaNonTrovataException.class)
public final DettagliErrore gestisciErrore(UnitaLogisticaNonTrovataException e) {
return new DettagliErrore(HttpStatus.NOT_FOUND.value(), "Unità logistica non trovata");
}

@ExceptionHandler(UtenteNonTrovatoException.class)
public final DettagliErrore gestisciErrore(UtenteNonTrovatoException e) {
return new DettagliErrore(HttpStatus.NOT_FOUND.value(), "Utente non trovato.");
}


@ExceptionHandler(UtenteNonAutorizzatoException.class)
public final DettagliErrore gestisciErrore(UtenteNonAutorizzatoException e){
return new DettagliErrore(HttpStatus.UNAUTHORIZED.value(), "Utente non autorizzato");
}

@ExceptionHandler(RegistrazioneException.class)
public final DettagliErrore gestisciErrore(RegistrazioneException e){
return new DettagliErrore(HttpStatus.INTERNAL_SERVER_ERROR.value(), "Errore durante la registrazione");
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
package it.myti.academy.backend.controller;

import it.myti.academy.backend.model.Evento;
import it.myti.academy.backend.model.Utente;
import it.myti.academy.backend.model.errori.eccezioni.UtenteNonAutorizzatoException;
import it.myti.academy.backend.model.errori.eccezioni.UtenteNonTrovatoException;
import it.myti.academy.backend.service.EventoService;
import it.myti.academy.backend.service.UtenteService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
public class EventiController {
@Autowired
EventoService eventoService;

@Autowired
UtenteService utenteService;

@GetMapping("/eventi/utente/{idUtente}")
public List<Evento> getEventiByCollo(@PathVariable("idUtente") Long idUtente) throws UtenteNonTrovatoException, UtenteNonAutorizzatoException {
String username = SecurityContextHolder.getContext().getAuthentication().getName();
Utente utente = utenteService.getByUsername(username);
if(utente.getId().equals(idUtente) || username == null)
return eventoService.findEventiAttiviByUtente(utenteService.getById(idUtente));
throw new UtenteNonAutorizzatoException();

}
}

This file was deleted.

Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
package it.myti.academy.backend.controller;

import it.myti.academy.backend.model.Utente;
import it.myti.academy.backend.model.entitaRisposte.DettagliUnitaLogisticaUtente;
import it.myti.academy.backend.model.errori.eccezioni.UnitaLogisticaNonTrovataException;
import it.myti.academy.backend.model.errori.eccezioni.UtenteNonAutorizzatoException;
import it.myti.academy.backend.model.errori.eccezioni.UtenteNonTrovatoException;
import it.myti.academy.backend.service.UnitaLogisticaService;
import it.myti.academy.backend.service.UtenteService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;

@RestController
public class UnitaLogisticheController {

@Autowired
UnitaLogisticaService unitaLogisticaService;

@Autowired
UtenteService utenteService;

@GetMapping("unitalogistiche/utente/{idUtente}")
public List<DettagliUnitaLogisticaUtente> getUnitaLogisticheByUtente(@PathVariable("idUtente") Long idUtente) throws UtenteNonAutorizzatoException, UnitaLogisticaNonTrovataException, UtenteNonTrovatoException {
String username = SecurityContextHolder.getContext().getAuthentication().getName();
Utente utente = utenteService.getByUsername(username);
if(utente.getId().equals(idUtente) || username == null)
return unitaLogisticaService.getByUtente(idUtente);
throw new UtenteNonAutorizzatoException();
}

@GetMapping("unitalogistiche/{idUnitaLogistica}/utente/{idUtente}")
public DettagliUnitaLogisticaUtente geUnitaLogisticaByIdAndUtente(@PathVariable("idUnitaLogistica") Long idUnitaLogistica, @PathVariable("idUtente") Long idUtente) throws UnitaLogisticaNonTrovataException, UtenteNonTrovatoException, UtenteNonAutorizzatoException {
String username = SecurityContextHolder.getContext().getAuthentication().getName();
Utente utente = utenteService.getByUsername(username);
if(utente.getId().equals(idUtente) || username == null)
return unitaLogisticaService.getByIdAndUtente(idUnitaLogistica, idUtente);
throw new UtenteNonAutorizzatoException();
}


}
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
package it.myti.academy.backend.controller;

import it.myti.academy.backend.model.Utente;
import it.myti.academy.backend.model.UtenteRichiesta;
import it.myti.academy.backend.model.errori.eccezioni.RegistrazioneException;
import it.myti.academy.backend.repository.UtenteRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;


@RestController
public class UtenteController {

private UtenteRepository applicationUserRepository;
private BCryptPasswordEncoder bCryptPasswordEncoder;

@Autowired
public UtenteController(UtenteRepository applicationUserRepository,
BCryptPasswordEncoder bCryptPasswordEncoder) {
this.applicationUserRepository = applicationUserRepository;
this.bCryptPasswordEncoder = bCryptPasswordEncoder;
}

@PostMapping("/registrazione")
public Utente registrazione(@RequestBody UtenteRichiesta utenteRichiesta) throws RegistrazioneException {
Utente utente = new Utente();
utente.setNome(utenteRichiesta.getNome());
utente.setUsername(utenteRichiesta.getUsername());
utente.setPassword(bCryptPasswordEncoder.encode(utenteRichiesta.getPassword()));
try {
applicationUserRepository.save(utente);
}catch(Exception e){
throw new RegistrazioneException();
}

return utente;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
package it.myti.academy.backend.filter;

import com.fasterxml.jackson.databind.ObjectMapper;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import it.myti.academy.backend.model.Utente;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;

public class JWTAuthenticationFilter extends UsernamePasswordAuthenticationFilter implements SecurityConstants {


private AuthenticationManager authenticationManager;
public JWTAuthenticationFilter(AuthenticationManager authenticationManager) {
this.authenticationManager = authenticationManager;
}
@Override
public Authentication attemptAuthentication(HttpServletRequest req, HttpServletResponse res) throws AuthenticationException {
try {
Utente creds = new ObjectMapper().readValue(req.getInputStream(), Utente.class);
return authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(creds.getUsername(), creds.getPassword(), new ArrayList<>()) );
} catch (IOException e) {
throw new RuntimeException(e);
}
}
@Override
protected void successfulAuthentication(HttpServletRequest req, HttpServletResponse res, FilterChain chain, Authentication auth){
String token = Jwts.builder()
.setSubject(((User) auth.getPrincipal()).getUsername())
.setExpiration(new Date(System.currentTimeMillis() + EXPIRATION_TIME))
.signWith(SignatureAlgorithm.HS512, SECRET)
.compact();
res.addHeader(HEADER_STRING, TOKEN_PREFIX + token);
}
}
Loading