Skip to content

Fine corso #6

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 10 commits into
base: develop
Choose a base branch
from
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
Binary file removed mvn-repository-exported.zip
Binary file not shown.
15 changes: 15 additions & 0 deletions pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,10 @@
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>

<!-- TOOLS -->
<dependency>
Expand All @@ -46,12 +50,23 @@
<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.security</groupId>
<artifactId>spring-security-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>

<build>
Expand Down
19 changes: 19 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,19 @@
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;

/**
* Created by david at 2019-03-20
*/
@Configuration
public class CryptConfig {

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


}
51 changes: 51 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,51 @@
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.http.HttpStatus;
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 org.springframework.security.web.authentication.HttpStatusEntryPoint;


/**
* Created by david at 2019-03-20
*/
@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, "/utente/sign-up", "/unitalogistiche/utente/*").permitAll()
.anyRequest().authenticated()
.and()
.addFilter(new JWTAuthenticationFilter(authenticationManager()))
.addFilter(new JWTAuthorizationFilter(authenticationManager()))
.exceptionHandling()
.authenticationEntryPoint(new HttpStatusEntryPoint(HttpStatus.UNAUTHORIZED));
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
@@ -0,0 +1,29 @@
package it.myti.academy.backend.controller;

import it.myti.academy.backend.model.Evento;
import it.myti.academy.backend.service.EventoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
* Created by david at 2019-03-11
*/
@RestController
public class EventiController {

@Autowired
public EventoService eventoService;

@GetMapping("/eventi/utente/{id}")
public List<Evento> getEventiByUtente(@PathVariable("id") Long idUtente, @RequestParam(value = "idSpedizione", required = false) Long idSpedizione, @RequestParam(value = "idUnitaLogistica", required = false) Long idUnitaLogistica) {

final List<Evento> eventiSpedizioniAttiveByUtente = eventoService.getEventiByUtenteAndSpedizioneAndUnitaLogistica(idUtente, idSpedizione, idUnitaLogistica);

return eventiSpedizioniAttiveByUtente;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -3,17 +3,19 @@
import it.myti.academy.backend.model.Collo;
import it.myti.academy.backend.model.EventoParticle;
import it.myti.academy.backend.model.UnitaLogistica;
import it.myti.academy.backend.model.Utente;
import it.myti.academy.backend.model.resp.UnitaLogisticheDettaglio;
import it.myti.academy.backend.repository.EventiParticleRepository;
import it.myti.academy.backend.repository.UtenteRepository;
import it.myti.academy.backend.service.ColloService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
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.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
Expand All @@ -24,15 +26,18 @@ public class UnitaLogisticheController {

@Autowired
public ColloService colloService;

@Autowired
public EventiParticleRepository eventiParticleRepository;
private Function<Collo, UnitaLogisticheDettaglio> colloToDetail;
@Autowired
private UtenteRepository utenteRepository;

@GetMapping("/unitalogistiche/utente/{id}")
public List<UnitaLogisticheDettaglio> getDettagliByUtente(@PathVariable("id") long id) {
@GetMapping("/unitalogistiche")
public List<UnitaLogisticheDettaglio> getDettagliByUtente() {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
String currentPrincipalName = authentication.getName();
Utente user = utenteRepository.findByUsername(currentPrincipalName);

final List<Collo> spedizioniAttiveByUtente = colloService.getSpedizioniAttiveByUtente(id);
final List<Collo> spedizioniAttiveByUtente = colloService.getSpedizioniAttiveByUtente(user.getId());

final List<UnitaLogisticheDettaglio> collect = spedizioniAttiveByUtente.stream()
.map(c -> colloToDetails(c))
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
package it.myti.academy.backend.controller;

import it.myti.academy.backend.model.Utente;
import it.myti.academy.backend.model.req.NewUtente;
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;

/**
* Created by david at 2019-03-20
*/

@RestController
public class UtenteController {

private UtenteRepository applicationUserRepository;
private BCryptPasswordEncoder bCryptPasswordEncoder;

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

@PostMapping("/utente/sign-up")
public String signUp(@RequestBody NewUtente newUtente) {
Utente utente = new Utente();
utente.setNome(newUtente.getNome());
utente.setUsername(newUtente.getUsername());
utente.setPassword(bCryptPasswordEncoder.encode(newUtente.getPassword()));
applicationUserRepository.save(utente);
return "OK!";
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
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;

/**
* Created by david at 2019-03-20
*/
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) throws IOException, ServletException {
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);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
package it.myti.academy.backend.filter;

import io.jsonwebtoken.Jwts;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.www.BasicAuthenticationFilter;

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;

/**
* Created by david at 2019-03-20
*/
public class JWTAuthorizationFilter extends BasicAuthenticationFilter implements SecurityConstants {
public JWTAuthorizationFilter(AuthenticationManager authManager) {
super(authManager);
}

@Override
protected void doFilterInternal(HttpServletRequest req,
HttpServletResponse res,
FilterChain chain) throws IOException, ServletException {
String header = req.getHeader(HEADER_STRING);
if (header == null || !header.startsWith(TOKEN_PREFIX)) {
chain.doFilter(req, res);
return;
}
UsernamePasswordAuthenticationToken authentication = getAuthentication(req);
SecurityContextHolder.getContext().setAuthentication(authentication);
chain.doFilter(req, res);
}

private UsernamePasswordAuthenticationToken getAuthentication(HttpServletRequest request) {
String token = request.getHeader(HEADER_STRING);
if (token != null) {
// parse the token.
String user = Jwts.parser()
.setSigningKey(SECRET)
.parseClaimsJws(token.replace(TOKEN_PREFIX, ""))
.getBody()
.getSubject();
if (user != null) {
return new UsernamePasswordAuthenticationToken(user, null, new ArrayList<>());
}
return null;
}
return null;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
package it.myti.academy.backend.filter;

/**
* Created by david at 2019-03-20
*/
public interface SecurityConstants {
final static Long EXPIRATION_TIME = 3600000L;
final static String TOKEN_PREFIX = "Bearer ";
final static String HEADER_STRING = "Authorization";
final static String SECRET = "this-is-a-secret";
final static String SIGN_UP_URL = "/utente/sign-up";
}
10 changes: 1 addition & 9 deletions src/main/java/it/myti/academy/backend/model/Collo.java
Original file line number Diff line number Diff line change
Expand Up @@ -3,15 +3,7 @@
import com.fasterxml.jackson.annotation.JsonIgnore;
import lombok.Data;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.persistence.*;
import java.util.List;

/**
Expand Down
9 changes: 1 addition & 8 deletions src/main/java/it/myti/academy/backend/model/Contenuto.java
Original file line number Diff line number Diff line change
Expand Up @@ -3,14 +3,7 @@
import com.fasterxml.jackson.annotation.JsonIgnore;
import lombok.Data;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
import javax.persistence.*;

/**
* Created by david at 2019-02-13
Expand Down
Loading