├── start-app.sh ├── .mvn └── wrapper │ ├── maven-wrapper.jar │ └── maven-wrapper.properties ├── src ├── main │ ├── java │ │ └── com │ │ │ └── montanha │ │ │ ├── gerenciador │ │ │ ├── enums │ │ │ │ └── PerfilEnum.java │ │ │ ├── dtos │ │ │ │ ├── TokenDto.java │ │ │ │ ├── JwtAuthenticationDto.java │ │ │ │ ├── ViagemDto.java │ │ │ │ └── ViagemDtoResponse.java │ │ │ ├── repositories │ │ │ │ ├── UsuarioRepository.java │ │ │ │ └── ViagemRepository.java │ │ │ ├── services │ │ │ │ ├── exceptions │ │ │ │ │ └── ViagemServiceException.java │ │ │ │ └── ViagemServices.java │ │ │ ├── responses │ │ │ │ └── Response.java │ │ │ ├── controller │ │ │ │ ├── StatusAplicacaoController.java │ │ │ │ ├── SegurancaController.java │ │ │ │ └── GerenciadorViagemController.java │ │ │ ├── utils │ │ │ │ └── Conversor.java │ │ │ ├── entities │ │ │ │ ├── Usuario.java │ │ │ │ └── Viagem.java │ │ │ ├── GerenciadorViagensMontanhaApplication.java │ │ │ └── filter │ │ │ │ └── JwtAuthenticationTokenFilter.java │ │ │ ├── security │ │ │ ├── services │ │ │ │ └── UsuarioService.java │ │ │ ├── service │ │ │ │ └── impl │ │ │ │ │ ├── UsuarioServiceImpl.java │ │ │ │ │ └── JwtUserDetailsServiceImpl.java │ │ │ ├── JwtAuthenticationEntryPoint.java │ │ │ ├── JwtUserFactory.java │ │ │ ├── utils │ │ │ │ ├── MyBasicAuthenticationEntryPoint.java │ │ │ │ └── JwtTokenUtil.java │ │ │ ├── JwtUser.java │ │ │ ├── config │ │ │ │ └── WebSecurityConfig.java │ │ │ └── controller │ │ │ │ └── AuthenticationController.java │ │ │ └── utils │ │ │ ├── SenhaUtils.java │ │ │ └── SpringFoxConfig.java │ └── resources │ │ └── application.properties └── test │ └── java │ └── com │ └── montanha │ └── gerenciador │ └── GerenciadorViagensMontanhaApplicationTests.java ├── README.md ├── .gitignore ├── Dockerfile ├── pom.xml ├── mvnw.cmd ├── mvnw └── swaggerfile.yml /start-app.sh: -------------------------------------------------------------------------------- 1 | cd /data/gerenciador-viagens && mvn spring-boot:run 2 | -------------------------------------------------------------------------------- /.mvn/wrapper/maven-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AntonioMontanha/gerenciador-viagens/HEAD/.mvn/wrapper/maven-wrapper.jar -------------------------------------------------------------------------------- /.mvn/wrapper/maven-wrapper.properties: -------------------------------------------------------------------------------- 1 | distributionUrl=https://repo1.maven.org/maven2/org/apache/maven/apache-maven/3.5.2/apache-maven-3.5.2-bin.zip 2 | -------------------------------------------------------------------------------- /src/main/java/com/montanha/gerenciador/enums/PerfilEnum.java: -------------------------------------------------------------------------------- 1 | package com.montanha.gerenciador.enums; 2 | 3 | public enum PerfilEnum { 4 | ROLE_ADMIN, 5 | ROLE_USUARIO; 6 | } 7 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | Este é um repositório para aprender um pouco mais sobre APIs REST. 2 | 3 | Nele existem vários problemas e más práticas para serem utilizadas como exemplo do que não fazer. 4 | -------------------------------------------------------------------------------- /src/main/resources/application.properties: -------------------------------------------------------------------------------- 1 | server.port=8089 2 | spring.jackson.serialization.WRITE_DATES_AS_TIMESTAMPS = false 3 | jwt.secret=istoehapenasumteste 4 | jwt.expiration=99999 5 | previsaoDoTempoUri=http://demo5966266.mockable.io/ 6 | server.servlet-path=/api 7 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | target/ 2 | !.mvn/wrapper/maven-wrapper.jar 3 | 4 | ### STS ### 5 | .apt_generated 6 | .classpath 7 | .factorypath 8 | .project 9 | .settings 10 | .springBeans 11 | 12 | ### IntelliJ IDEA ### 13 | .idea 14 | *.iws 15 | *.iml 16 | *.ipr 17 | 18 | ### NetBeans ### 19 | nbproject/private/ 20 | build/ 21 | nbbuild/ 22 | dist/ 23 | nbdist/ 24 | .nb-gradle/ -------------------------------------------------------------------------------- /src/main/java/com/montanha/gerenciador/dtos/TokenDto.java: -------------------------------------------------------------------------------- 1 | package com.montanha.gerenciador.dtos; 2 | 3 | public class TokenDto { 4 | 5 | private String token; 6 | 7 | public TokenDto() { 8 | } 9 | 10 | public TokenDto(String token) { 11 | this.token = token; 12 | } 13 | 14 | public String getToken() { 15 | return token; 16 | } 17 | 18 | public void setToken(String token) { 19 | this.token = token; 20 | } 21 | 22 | } 23 | -------------------------------------------------------------------------------- /src/main/java/com/montanha/security/services/UsuarioService.java: -------------------------------------------------------------------------------- 1 | package com.montanha.security.services; 2 | 3 | import java.util.Optional; 4 | 5 | import com.montanha.gerenciador.entities.Usuario; 6 | 7 | public interface UsuarioService { 8 | 9 | /** 10 | * Busca e retorna um usuário dado um email. 11 | * 12 | * @param email 13 | * @return Optional 14 | */ 15 | Optional buscarPorEmail(String email); 16 | 17 | } 18 | -------------------------------------------------------------------------------- /src/main/java/com/montanha/gerenciador/repositories/UsuarioRepository.java: -------------------------------------------------------------------------------- 1 | package com.montanha.gerenciador.repositories; 2 | 3 | import org.springframework.data.jpa.repository.JpaRepository; 4 | import org.springframework.transaction.annotation.Transactional; 5 | 6 | import com.montanha.gerenciador.entities.Usuario; 7 | 8 | @Transactional(readOnly = true) 9 | public interface UsuarioRepository extends JpaRepository { 10 | Usuario findByEmail(String email); 11 | } 12 | -------------------------------------------------------------------------------- /src/main/java/com/montanha/gerenciador/services/exceptions/ViagemServiceException.java: -------------------------------------------------------------------------------- 1 | package com.montanha.gerenciador.services.exceptions; 2 | 3 | public class ViagemServiceException extends RuntimeException { 4 | 5 | private static final long serialVersionUID = -1402677565107062800L; 6 | 7 | public ViagemServiceException(String mensagem) { 8 | super(mensagem); 9 | } 10 | 11 | public ViagemServiceException(String mensagem, Throwable causa) { 12 | super(mensagem, causa); 13 | } 14 | 15 | } 16 | -------------------------------------------------------------------------------- /src/test/java/com/montanha/gerenciador/GerenciadorViagensMontanhaApplicationTests.java: -------------------------------------------------------------------------------- 1 | package com.montanha.gerenciador; 2 | 3 | import org.junit.Test; 4 | import org.junit.runner.RunWith; 5 | import org.springframework.boot.test.context.SpringBootTest; 6 | import org.springframework.test.context.junit4.SpringRunner; 7 | 8 | @RunWith(SpringRunner.class) 9 | @SpringBootTest 10 | public class GerenciadorViagensMontanhaApplicationTests { 11 | 12 | @Test 13 | public void contextLoads() { 14 | } 15 | 16 | } 17 | -------------------------------------------------------------------------------- /src/main/java/com/montanha/gerenciador/repositories/ViagemRepository.java: -------------------------------------------------------------------------------- 1 | package com.montanha.gerenciador.repositories; 2 | 3 | import org.springframework.data.jpa.repository.JpaRepository; 4 | import org.springframework.stereotype.Repository; 5 | 6 | import com.montanha.gerenciador.entities.Viagem; 7 | 8 | import java.util.List; 9 | 10 | @Repository 11 | public interface ViagemRepository extends JpaRepository { 12 | 13 | Viagem findByLocalDeDestino(String localDeDestino); 14 | 15 | List findAllByRegiao(String regiao); 16 | 17 | 18 | } 19 | -------------------------------------------------------------------------------- /Dockerfile: -------------------------------------------------------------------------------- 1 | FROM ubuntu:18.04 2 | 3 | RUN apt-get update 4 | 5 | COPY . /data/gerenciador-viagens 6 | WORKDIR /data/gerenciador-viagens 7 | 8 | RUN chmod +x /data/gerenciador-viagens/start-app.sh 9 | RUN ls -la /data/gerenciador-viagens 10 | 11 | RUN apt-get install curl -y 12 | RUN apt-get install software-properties-common -y 13 | RUN add-apt-repository ppa:webupd8team/java 14 | RUN echo "oracle-java8-installer shared/accepted-oracle-license-v1-1 select true" | debconf-set-selections 15 | RUN apt-get install oracle-java8-installer -y 16 | RUN apt-get install maven -y 17 | 18 | EXPOSE 8089 19 | 20 | RUN ls -la /data/gerenciador-viagens 21 | 22 | CMD [ "bash", "/data/gerenciador-viagens/start-app.sh" ] 23 | -------------------------------------------------------------------------------- /src/main/java/com/montanha/gerenciador/responses/Response.java: -------------------------------------------------------------------------------- 1 | package com.montanha.gerenciador.responses; 2 | 3 | import java.util.ArrayList; 4 | import java.util.List; 5 | 6 | public class Response { 7 | 8 | private T data; 9 | private List errors; 10 | 11 | public T getData() { 12 | return data; 13 | } 14 | 15 | public void setData(T data) { 16 | this.data = data; 17 | } 18 | 19 | public List getErrors() { 20 | if (this.errors == null) { 21 | this.errors = new ArrayList(); 22 | } 23 | return errors; 24 | } 25 | 26 | public void setErrors(List errors) { 27 | this.errors = errors; 28 | } 29 | 30 | public Response() { 31 | 32 | } 33 | 34 | } 35 | -------------------------------------------------------------------------------- /src/main/java/com/montanha/security/service/impl/UsuarioServiceImpl.java: -------------------------------------------------------------------------------- 1 | package com.montanha.security.service.impl; 2 | 3 | import java.util.Optional; 4 | 5 | import org.springframework.beans.factory.annotation.Autowired; 6 | import org.springframework.stereotype.Service; 7 | 8 | import com.montanha.gerenciador.entities.Usuario; 9 | import com.montanha.gerenciador.repositories.UsuarioRepository; 10 | import com.montanha.security.services.UsuarioService; 11 | 12 | @Service 13 | public class UsuarioServiceImpl implements UsuarioService { 14 | 15 | @Autowired 16 | private UsuarioRepository usuarioRepository; 17 | 18 | public Optional buscarPorEmail(String email) { 19 | return Optional.ofNullable(this.usuarioRepository.findByEmail(email)); 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /src/main/java/com/montanha/gerenciador/controller/StatusAplicacaoController.java: -------------------------------------------------------------------------------- 1 | package com.montanha.gerenciador.controller; 2 | 3 | import io.swagger.annotations.Api; 4 | import io.swagger.annotations.ApiOperation; 5 | import org.springframework.web.bind.annotation.GetMapping; 6 | import org.springframework.web.bind.annotation.RequestMapping; 7 | import org.springframework.web.bind.annotation.RestController; 8 | 9 | @RestController 10 | @RequestMapping("v1/status") 11 | @ApiOperation(value = "Verifica se a Aplicação está no ar") 12 | @Api("StatusAplicacaoController") 13 | public class StatusAplicacaoController { 14 | 15 | @GetMapping() 16 | public String verificaStatusAplicacao() { 17 | 18 | return "Aplicação está funcionando corretamente"; 19 | } 20 | 21 | 22 | } 23 | -------------------------------------------------------------------------------- /src/main/java/com/montanha/gerenciador/controller/SegurancaController.java: -------------------------------------------------------------------------------- 1 | //package com.montanha.gerenciador.controller; 2 | // 3 | //import io.swagger.annotations.Api; 4 | //import org.springframework.security.access.prepost.PreAuthorize; 5 | //import org.springframework.web.bind.annotation.GetMapping; 6 | //import org.springframework.web.bind.annotation.PathVariable; 7 | //import org.springframework.web.bind.annotation.RequestMapping; 8 | //import org.springframework.web.bind.annotation.RestController; 9 | // 10 | //@RestController 11 | //@RequestMapping("/api/login") 12 | //@Api("SegurancaController") 13 | //public class SegurancaController { 14 | // 15 | // @GetMapping(value = "/{nome}") 16 | // @PreAuthorize("hasAnyRole('ADMIN')") 17 | // public String exemplo(@PathVariable("nome") String nome) { 18 | // return "Seja bem vindo " + nome; 19 | // } 20 | // 21 | //} 22 | -------------------------------------------------------------------------------- /src/main/java/com/montanha/security/JwtAuthenticationEntryPoint.java: -------------------------------------------------------------------------------- 1 | package com.montanha.security; 2 | 3 | import java.io.IOException; 4 | 5 | import javax.servlet.http.HttpServletRequest; 6 | import javax.servlet.http.HttpServletResponse; 7 | 8 | import org.springframework.security.core.AuthenticationException; 9 | import org.springframework.security.web.AuthenticationEntryPoint; 10 | import org.springframework.stereotype.Component; 11 | 12 | @Component 13 | public class JwtAuthenticationEntryPoint implements AuthenticationEntryPoint { 14 | 15 | @Override 16 | public void commence(HttpServletRequest request, HttpServletResponse response, 17 | AuthenticationException authException) throws IOException { 18 | response.sendError(HttpServletResponse.SC_UNAUTHORIZED, 19 | "Acesso negado. Você deve estar autenticado no sistema para acessar a URL solicitada."); 20 | } 21 | 22 | } 23 | -------------------------------------------------------------------------------- /src/main/java/com/montanha/utils/SenhaUtils.java: -------------------------------------------------------------------------------- 1 | package com.montanha.utils; 2 | 3 | import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; 4 | 5 | public class SenhaUtils { 6 | 7 | /** 8 | * Gera um hash utilizando o BCrypt. 9 | * 10 | * @param senha 11 | * @return String 12 | */ 13 | public static String gerarBCrypt(String senha) { 14 | if (senha == null) { 15 | return senha; 16 | } 17 | 18 | BCryptPasswordEncoder bCryptEncoder = new BCryptPasswordEncoder(); 19 | return bCryptEncoder.encode(senha); 20 | } 21 | 22 | /** 23 | * Verifica se a senha é válida. 24 | * 25 | * @param senha 26 | * @param senhaEncoded 27 | * @return boolean 28 | */ 29 | public static boolean senhaValida(String senha, String senhaEncoded) { 30 | BCryptPasswordEncoder bCryptEncoder = new BCryptPasswordEncoder(); 31 | return bCryptEncoder.matches(senha, senhaEncoded); 32 | } 33 | 34 | } 35 | -------------------------------------------------------------------------------- /src/main/java/com/montanha/utils/SpringFoxConfig.java: -------------------------------------------------------------------------------- 1 | package com.montanha.utils; 2 | 3 | import org.springframework.context.annotation.Bean; 4 | import org.springframework.context.annotation.Configuration; 5 | 6 | import springfox.documentation.builders.PathSelectors; 7 | import springfox.documentation.builders.RequestHandlerSelectors; 8 | import springfox.documentation.spi.DocumentationType; 9 | import springfox.documentation.spring.web.plugins.Docket; 10 | import springfox.documentation.swagger2.annotations.EnableSwagger2; 11 | 12 | import javax.servlet.ServletContext; 13 | 14 | @Configuration 15 | @EnableSwagger2 16 | public class SpringFoxConfig { 17 | @Bean 18 | public Docket api(ServletContext servletContext) { 19 | return new Docket(DocumentationType.SWAGGER_2) 20 | .select() 21 | .apis(RequestHandlerSelectors.basePackage("com.montanha")) 22 | .paths(PathSelectors.any()) 23 | .build(); 24 | } 25 | 26 | } -------------------------------------------------------------------------------- /src/main/java/com/montanha/gerenciador/dtos/JwtAuthenticationDto.java: -------------------------------------------------------------------------------- 1 | package com.montanha.gerenciador.dtos; 2 | 3 | import org.hibernate.validator.constraints.Email; 4 | import org.hibernate.validator.constraints.NotEmpty; 5 | 6 | public class JwtAuthenticationDto { 7 | 8 | private String email; 9 | private String senha; 10 | 11 | public JwtAuthenticationDto() { 12 | } 13 | 14 | @NotEmpty(message = "Email não pode ser vazio.") 15 | @Email(message = "Email inválido.") 16 | public String getEmail() { 17 | return email; 18 | } 19 | 20 | public void setEmail(String email) { 21 | this.email = email; 22 | } 23 | 24 | @NotEmpty(message = "Senha não pode ser vazia.") 25 | public String getSenha() { 26 | return senha; 27 | } 28 | 29 | public void setSenha(String senha) { 30 | this.senha = senha; 31 | } 32 | 33 | @Override 34 | public String toString() { 35 | return "JwtAuthenticationRequestDto [email=" + email + ", senha=" + senha + "]"; 36 | } 37 | 38 | } 39 | -------------------------------------------------------------------------------- /src/main/java/com/montanha/gerenciador/utils/Conversor.java: -------------------------------------------------------------------------------- 1 | package com.montanha.gerenciador.utils; 2 | 3 | import com.montanha.gerenciador.dtos.ViagemDtoResponse; 4 | import com.montanha.gerenciador.entities.Viagem; 5 | 6 | public abstract class Conversor { 7 | 8 | public static ViagemDtoResponse converterViagemToViagemDtoResponse(Viagem viagem) { 9 | 10 | ViagemDtoResponse viagemDtoResponse = new ViagemDtoResponse(); 11 | viagemDtoResponse.setId(viagem.getId()); 12 | viagemDtoResponse.setAcompanhante(viagem.getAcompanhante()); 13 | viagemDtoResponse.setDataPartida(viagem.getDataPartida()); 14 | if (viagem.getDataRetorno() != null) { 15 | viagemDtoResponse.setDataRetorno(viagem.getDataRetorno()); 16 | } 17 | if (viagem.getLocalDeDestino() != null) { 18 | viagemDtoResponse.setLocalDeDestino(viagem.getLocalDeDestino()); 19 | } 20 | 21 | if (viagem.getRegiao() != null) { 22 | viagemDtoResponse.setRegiao(viagem.getRegiao()); 23 | } 24 | 25 | 26 | return viagemDtoResponse; 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /src/main/java/com/montanha/security/service/impl/JwtUserDetailsServiceImpl.java: -------------------------------------------------------------------------------- 1 | package com.montanha.security.service.impl; 2 | 3 | import java.util.Optional; 4 | 5 | import org.springframework.beans.factory.annotation.Autowired; 6 | import org.springframework.security.core.userdetails.UserDetails; 7 | import org.springframework.security.core.userdetails.UserDetailsService; 8 | import org.springframework.security.core.userdetails.UsernameNotFoundException; 9 | import org.springframework.stereotype.Service; 10 | 11 | import com.montanha.security.JwtUserFactory; 12 | import com.montanha.gerenciador.entities.Usuario; 13 | import com.montanha.security.services.UsuarioService; 14 | 15 | @Service 16 | public class JwtUserDetailsServiceImpl implements UserDetailsService { 17 | 18 | @Autowired 19 | private UsuarioService usuarioService; 20 | 21 | @Override 22 | public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { 23 | Optional usuario = usuarioService.buscarPorEmail(username); 24 | 25 | if (usuario.isPresent()) { 26 | return JwtUserFactory.create(usuario.get()); 27 | } 28 | 29 | throw new UsernameNotFoundException("Email não encontrado."); 30 | } 31 | 32 | } 33 | -------------------------------------------------------------------------------- /src/main/java/com/montanha/security/JwtUserFactory.java: -------------------------------------------------------------------------------- 1 | package com.montanha.security; 2 | 3 | import java.util.ArrayList; 4 | import java.util.List; 5 | 6 | import org.springframework.security.core.GrantedAuthority; 7 | import org.springframework.security.core.authority.SimpleGrantedAuthority; 8 | 9 | import com.montanha.gerenciador.entities.Usuario; 10 | import com.montanha.gerenciador.enums.PerfilEnum; 11 | 12 | public class JwtUserFactory { 13 | 14 | private JwtUserFactory() { 15 | } 16 | 17 | /** 18 | * Converte e gera um JwtUser com base nos dados de um funcionário. 19 | * 20 | * @param funcionario 21 | * @return JwtUser 22 | */ 23 | public static JwtUser create(Usuario usuario) { 24 | return new JwtUser(usuario.getId(), usuario.getEmail(), usuario.getSenha(), 25 | mapToGrantedAuthorities(usuario.getPerfil())); 26 | } 27 | 28 | /** 29 | * Converte o perfil do usuário para o formato utilizado pelo Spring Security. 30 | * 31 | * @param perfilEnum 32 | * @return List 33 | */ 34 | private static List mapToGrantedAuthorities(PerfilEnum perfilEnum) { 35 | List authorities = new ArrayList(); 36 | authorities.add(new SimpleGrantedAuthority(perfilEnum.toString())); 37 | return authorities; 38 | } 39 | 40 | } 41 | -------------------------------------------------------------------------------- /src/main/java/com/montanha/security/utils/MyBasicAuthenticationEntryPoint.java: -------------------------------------------------------------------------------- 1 | package com.montanha.security.utils; 2 | 3 | import java.io.IOException; 4 | import java.io.PrintWriter; 5 | 6 | import javax.servlet.ServletException; 7 | import javax.servlet.http.HttpServletRequest; 8 | import javax.servlet.http.HttpServletResponse; 9 | 10 | import org.springframework.security.core.AuthenticationException; 11 | import org.springframework.security.web.authentication.www.BasicAuthenticationEntryPoint; 12 | import org.springframework.stereotype.Component; 13 | 14 | @Component 15 | public class MyBasicAuthenticationEntryPoint extends BasicAuthenticationEntryPoint { 16 | 17 | @Override 18 | public void commence 19 | (HttpServletRequest request, HttpServletResponse response, AuthenticationException authEx) 20 | throws IOException, ServletException { 21 | response.addHeader("WWW-Authenticate", "Basic realm=" + getRealmName() + ""); 22 | response.setStatus(HttpServletResponse.SC_UNAUTHORIZED); 23 | PrintWriter writer = response.getWriter(); 24 | writer.println("HTTP Status 401 - " + authEx.getMessage()); 25 | } 26 | 27 | @Override 28 | public void afterPropertiesSet() throws Exception { 29 | setRealmName("Baeldung"); 30 | super.afterPropertiesSet(); 31 | } 32 | } -------------------------------------------------------------------------------- /src/main/java/com/montanha/security/JwtUser.java: -------------------------------------------------------------------------------- 1 | package com.montanha.security; 2 | 3 | import java.util.Collection; 4 | 5 | import org.springframework.security.core.GrantedAuthority; 6 | import org.springframework.security.core.userdetails.UserDetails; 7 | 8 | public class JwtUser implements UserDetails { 9 | 10 | private static final long serialVersionUID = -268046329085485932L; 11 | 12 | private Long id; 13 | private String username; 14 | private String password; 15 | private Collection authorities; 16 | 17 | public JwtUser(Long id, String username, String password, Collection authorities) { 18 | this.id = id; 19 | this.username = username; 20 | this.password = password; 21 | this.authorities = authorities; 22 | } 23 | 24 | public Long getId() { 25 | return id; 26 | } 27 | 28 | @Override 29 | public String getUsername() { 30 | return username; 31 | } 32 | 33 | @Override 34 | public boolean isAccountNonExpired() { 35 | return true; 36 | } 37 | 38 | @Override 39 | public boolean isAccountNonLocked() { 40 | return true; 41 | } 42 | 43 | @Override 44 | public boolean isCredentialsNonExpired() { 45 | return true; 46 | } 47 | 48 | @Override 49 | public String getPassword() { 50 | return password; 51 | } 52 | 53 | @Override 54 | public Collection getAuthorities() { 55 | return authorities; 56 | } 57 | 58 | @Override 59 | public boolean isEnabled() { 60 | return true; 61 | } 62 | 63 | } 64 | -------------------------------------------------------------------------------- /src/main/java/com/montanha/gerenciador/entities/Usuario.java: -------------------------------------------------------------------------------- 1 | package com.montanha.gerenciador.entities; 2 | 3 | import java.io.Serializable; 4 | 5 | import javax.persistence.Column; 6 | import javax.persistence.Entity; 7 | import javax.persistence.EnumType; 8 | import javax.persistence.Enumerated; 9 | import javax.persistence.GeneratedValue; 10 | import javax.persistence.GenerationType; 11 | import javax.persistence.Id; 12 | import javax.persistence.Table; 13 | 14 | import com.montanha.gerenciador.enums.PerfilEnum; 15 | 16 | @Entity 17 | @Table(name = "usuario") 18 | public class Usuario implements Serializable { 19 | 20 | private static final long serialVersionUID = 306411570471828345L; 21 | 22 | private Long id; 23 | private String email; 24 | private String senha; 25 | private PerfilEnum perfil; 26 | 27 | public Usuario() { 28 | } 29 | 30 | @Id 31 | @GeneratedValue(strategy = GenerationType.AUTO) 32 | public Long getId() { 33 | return id; 34 | } 35 | 36 | public void setId(Long id) { 37 | this.id = id; 38 | } 39 | 40 | @Column(name = "email", nullable = false) 41 | public String getEmail() { 42 | return email; 43 | } 44 | 45 | public void setEmail(String email) { 46 | this.email = email; 47 | } 48 | 49 | @Enumerated(EnumType.STRING) 50 | @Column(name = "perfil", nullable = false) 51 | public PerfilEnum getPerfil() { 52 | return perfil; 53 | } 54 | 55 | public void setPerfil(PerfilEnum perfil) { 56 | this.perfil = perfil; 57 | } 58 | 59 | @Column(name = "senha", nullable = false) 60 | public String getSenha() { 61 | return senha; 62 | } 63 | 64 | public void setSenha(String senha) { 65 | this.senha = senha; 66 | } 67 | 68 | } 69 | -------------------------------------------------------------------------------- /src/main/java/com/montanha/gerenciador/GerenciadorViagensMontanhaApplication.java: -------------------------------------------------------------------------------- 1 | package com.montanha.gerenciador; 2 | 3 | import org.springframework.beans.factory.annotation.Autowired; 4 | import org.springframework.boot.CommandLineRunner; 5 | import org.springframework.boot.SpringApplication; 6 | import org.springframework.boot.autoconfigure.SpringBootApplication; 7 | import org.springframework.context.annotation.Bean; 8 | import org.springframework.context.annotation.ComponentScan; 9 | import org.springframework.context.annotation.Configuration; 10 | 11 | import com.montanha.gerenciador.entities.Usuario; 12 | import com.montanha.gerenciador.enums.PerfilEnum; 13 | import com.montanha.gerenciador.repositories.UsuarioRepository; 14 | import com.montanha.utils.SenhaUtils; 15 | 16 | @SpringBootApplication 17 | @Configuration 18 | @ComponentScan("com.montanha") 19 | public class GerenciadorViagensMontanhaApplication { 20 | 21 | @Autowired 22 | private UsuarioRepository usuarioRepository; 23 | 24 | public static void main(String[] args) { 25 | SpringApplication.run(GerenciadorViagensMontanhaApplication.class, args); 26 | } 27 | 28 | @Bean 29 | public CommandLineRunner commandLineRunner() { 30 | return args -> { 31 | 32 | Usuario usuario = new Usuario(); 33 | usuario.setEmail("usuario@email.com"); 34 | usuario.setPerfil(PerfilEnum.ROLE_USUARIO); 35 | usuario.setSenha(SenhaUtils.gerarBCrypt("123456")); 36 | this.usuarioRepository.save(usuario); 37 | 38 | Usuario admin = new Usuario(); 39 | admin.setEmail("admin@email.com"); 40 | admin.setPerfil(PerfilEnum.ROLE_ADMIN); 41 | admin.setSenha(SenhaUtils.gerarBCrypt("654321")); 42 | this.usuarioRepository.save(admin); 43 | 44 | }; 45 | } 46 | 47 | } 48 | -------------------------------------------------------------------------------- /src/main/java/com/montanha/gerenciador/filter/JwtAuthenticationTokenFilter.java: -------------------------------------------------------------------------------- 1 | package com.montanha.gerenciador.filter; 2 | 3 | import java.io.IOException; 4 | 5 | import javax.servlet.FilterChain; 6 | import javax.servlet.ServletException; 7 | import javax.servlet.http.HttpServletRequest; 8 | import javax.servlet.http.HttpServletResponse; 9 | 10 | import org.springframework.beans.factory.annotation.Autowired; 11 | import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; 12 | import org.springframework.security.core.context.SecurityContextHolder; 13 | import org.springframework.security.core.userdetails.UserDetails; 14 | import org.springframework.security.core.userdetails.UserDetailsService; 15 | import org.springframework.security.web.authentication.WebAuthenticationDetailsSource; 16 | import org.springframework.web.filter.OncePerRequestFilter; 17 | 18 | import com.montanha.security.utils.JwtTokenUtil; 19 | 20 | public class JwtAuthenticationTokenFilter extends OncePerRequestFilter { 21 | 22 | private static final String AUTH_HEADER = "Authorization"; 23 | private static final String BEARER_PREFIX = "Bearer "; 24 | 25 | @Autowired 26 | private UserDetailsService userDetailsService; 27 | 28 | @Autowired 29 | private JwtTokenUtil jwtTokenUtil; 30 | 31 | @Override 32 | protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) 33 | throws ServletException, IOException { 34 | String token = request.getHeader(AUTH_HEADER); 35 | if (token != null && token.startsWith(BEARER_PREFIX)) { 36 | token = token.substring(7); 37 | } 38 | String username = jwtTokenUtil.getUsernameFromToken(token); 39 | 40 | if (username != null && SecurityContextHolder.getContext().getAuthentication() == null) { 41 | UserDetails userDetails = this.userDetailsService.loadUserByUsername(username); 42 | 43 | if (jwtTokenUtil.tokenValido(token)) { 44 | UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken( 45 | userDetails, null, userDetails.getAuthorities()); 46 | authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request)); 47 | SecurityContextHolder.getContext().setAuthentication(authentication); 48 | } 49 | } 50 | 51 | chain.doFilter(request, response); 52 | } 53 | 54 | } 55 | -------------------------------------------------------------------------------- /src/main/java/com/montanha/gerenciador/dtos/ViagemDto.java: -------------------------------------------------------------------------------- 1 | package com.montanha.gerenciador.dtos; 2 | 3 | import java.io.Serializable; 4 | import java.util.Date; 5 | 6 | import javax.validation.constraints.NotNull; 7 | import javax.validation.constraints.Size; 8 | import com.fasterxml.jackson.annotation.JsonFormat; 9 | import io.swagger.annotations.ApiModelProperty; 10 | 11 | public class ViagemDto implements Serializable { 12 | 13 | private static final long serialVersionUID = -8105241933692707649L; 14 | 15 | 16 | 17 | @ApiModelProperty(value = "Local de destino da viagem") 18 | private String localDeDestino; 19 | 20 | @ApiModelProperty(value = "Data de partida da viagem (yyyy-MM-dd)") 21 | @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd") 22 | private Date dataPartida; 23 | 24 | @ApiModelProperty(value = "Data de retorno da viagem (yyyy-MM-dd)") 25 | @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd") 26 | private Date dataRetorno; 27 | 28 | @ApiModelProperty(value = "Nome do acompanhante da viagem") 29 | private String acompanhante; 30 | 31 | @ApiModelProperty(value = "Região de destino da viagem [Norte, Sul, Leste, Oeste]") 32 | private String regiao; 33 | 34 | 35 | public ViagemDto() { 36 | 37 | } 38 | 39 | @NotNull(message = "Local de Destino é uma informação obrigatória") 40 | @Size(min = 3, max = 40, message = "Local de Destino deve estar entre 3 e 40 caracteres") 41 | public String getLocalDeDestino() { 42 | return localDeDestino; 43 | } 44 | 45 | public void setLocalDeDestino(String localDeDestino) { 46 | this.localDeDestino = localDeDestino; 47 | } 48 | 49 | @NotNull(message = "Data da Partida é uma informação obrigatória") 50 | public Date getDataPartida() { 51 | return dataPartida; 52 | } 53 | 54 | public void setDataPartida(Date dataPartida) { 55 | this.dataPartida = dataPartida; 56 | } 57 | 58 | public Date getDataRetorno() { 59 | return dataRetorno; 60 | } 61 | 62 | public void setDataRetorno(Date dataRetorno) { 63 | this.dataRetorno = dataRetorno; 64 | } 65 | 66 | public String getAcompanhante() { 67 | return acompanhante; 68 | } 69 | 70 | public void setAcompanhante(String acompanhante) { 71 | this.acompanhante = acompanhante; 72 | } 73 | 74 | public String getRegiao() { 75 | return regiao; 76 | } 77 | 78 | public void setRegiao(String regiao) { 79 | this.regiao = regiao; 80 | } 81 | 82 | @Override 83 | public String toString() { 84 | return "ViagemDto [id=" + ", localDeDestino=" + localDeDestino + ", dataPartida=" + dataPartida 85 | + ", dataRetorno=" + dataRetorno + ", acompanhante=" + acompanhante + "]"; 86 | } 87 | } 88 | -------------------------------------------------------------------------------- /pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 4.0.0 5 | 6 | com.montanha 7 | gerenciador-viagens-montanha 8 | 0.0.1-SNAPSHOT 9 | jar 10 | 11 | GerenciadorViagensMontanha 12 | Gerenciador de Viagens 13 | 14 | 15 | org.springframework.boot 16 | spring-boot-starter-parent 17 | 1.5.10.RELEASE 18 | 19 | 20 | 21 | 22 | UTF-8 23 | UTF-8 24 | 1.8 25 | 26 | 27 | 28 | 29 | com.h2database 30 | h2 31 | runtime 32 | 33 | 34 | org.springframework.boot 35 | spring-boot-starter-data-jpa 36 | 37 | 38 | org.springframework.boot 39 | spring-boot-starter-security 40 | 41 | 42 | org.springframework.boot 43 | spring-boot-starter-web 44 | 45 | 46 | org.springframework.boot 47 | spring-boot-devtools 48 | runtime 49 | 50 | 51 | org.springframework.boot 52 | spring-boot-starter-test 53 | test 54 | 55 | 56 | com.fasterxml.jackson.core 57 | jackson-databind 58 | 59 | 60 | org.springframework.security 61 | spring-security-test 62 | test 63 | 64 | 65 | org.springframework.boot 66 | spring-boot-starter-data-jpa 67 | 68 | 69 | io.jsonwebtoken 70 | jjwt 71 | 0.7.0 72 | 73 | 74 | io.springfox 75 | springfox-swagger2 76 | 2.9.2 77 | 78 | 79 | io.springfox 80 | springfox-swagger-ui 81 | 2.9.2 82 | 83 | 84 | 85 | 86 | 87 | 88 | 89 | org.springframework.boot 90 | spring-boot-maven-plugin 91 | 92 | 93 | 94 | 95 | -------------------------------------------------------------------------------- /src/main/java/com/montanha/gerenciador/dtos/ViagemDtoResponse.java: -------------------------------------------------------------------------------- 1 | package com.montanha.gerenciador.dtos; 2 | 3 | import java.io.Serializable; 4 | import java.util.Date; 5 | import javax.validation.constraints.NotNull; 6 | 7 | import org.hibernate.validator.constraints.Length; 8 | 9 | import com.fasterxml.jackson.annotation.JsonFormat; 10 | 11 | import io.swagger.annotations.ApiModelProperty; 12 | 13 | public class ViagemDtoResponse implements Serializable { 14 | 15 | private static final long serialVersionUID = -8105241933692707649L; 16 | 17 | @ApiModelProperty(value = "Id da viagem") 18 | private Long id; 19 | 20 | @ApiModelProperty(value = "Local de destino da viagem") 21 | private String localDeDestino; 22 | 23 | @ApiModelProperty(value = "Data de partida da viagem") 24 | @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd") 25 | private Date dataPartida; 26 | 27 | @ApiModelProperty(value = "Data de retorno da viagem") 28 | @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd") 29 | private Date dataRetorno; 30 | 31 | @ApiModelProperty(value = "Nome do acompanhante da viagem") 32 | private String acompanhante; 33 | 34 | @ApiModelProperty(value = "Região de destino da viagem [Norte, Sul, Leste, Oeste]") 35 | private String regiao; 36 | 37 | @ApiModelProperty(value = "Temperatura prevista da região de destino") 38 | private Float temperatura; 39 | 40 | 41 | public ViagemDtoResponse() { 42 | 43 | } 44 | 45 | @NotNull(message = "Local de Destino é uma informação obrigatória") 46 | @Length(min = 3, max = 40, message = "Local de Destino deve estar entre 3 e 40 caracteres") 47 | public String getLocalDeDestino() { 48 | return localDeDestino; 49 | } 50 | 51 | public void setLocalDeDestino(String localDeDestino) { 52 | this.localDeDestino = localDeDestino; 53 | } 54 | 55 | @NotNull(message = "Data da Partida é uma informação obrigatória") 56 | public Date getDataPartida() { 57 | return dataPartida; 58 | } 59 | 60 | public void setDataPartida(Date dataPartida) { 61 | this.dataPartida = dataPartida; 62 | } 63 | 64 | public Date getDataRetorno() { 65 | return dataRetorno; 66 | } 67 | 68 | public void setDataRetorno(Date dataRetorno) { 69 | this.dataRetorno = dataRetorno; 70 | } 71 | 72 | public String getAcompanhante() { 73 | return acompanhante; 74 | } 75 | 76 | public void setAcompanhante(String acompanhante) { 77 | this.acompanhante = acompanhante; 78 | } 79 | 80 | public String getRegiao() { 81 | return regiao; 82 | } 83 | 84 | public void setRegiao(String regiao) { 85 | this.regiao = regiao; 86 | } 87 | 88 | public Long getId() { 89 | return id; 90 | } 91 | 92 | public void setId(Long id) { 93 | this.id = id; 94 | } 95 | 96 | public Float getTemperatura() { 97 | return temperatura; 98 | } 99 | 100 | public void setTemperatura(Float temperatura) { 101 | this.temperatura = temperatura; 102 | } 103 | 104 | 105 | @Override 106 | public String toString() { 107 | return "ViagemDto [id=" + ", localDeDestino=" + localDeDestino + ", dataPartida=" + dataPartida 108 | + ", dataRetorno=" + dataRetorno + ", acompanhante=" + acompanhante + "]"; 109 | } 110 | } 111 | -------------------------------------------------------------------------------- /src/main/java/com/montanha/gerenciador/entities/Viagem.java: -------------------------------------------------------------------------------- 1 | package com.montanha.gerenciador.entities; 2 | 3 | import java.io.Serializable; 4 | import java.util.Date; 5 | 6 | import javax.persistence.Column; 7 | import javax.persistence.Entity; 8 | import javax.persistence.GeneratedValue; 9 | import javax.persistence.GenerationType; 10 | import javax.persistence.Id; 11 | import javax.persistence.Table; 12 | 13 | import org.springframework.stereotype.Component; 14 | 15 | import com.fasterxml.jackson.annotation.JsonFormat; 16 | import com.fasterxml.jackson.databind.annotation.JsonSerialize; 17 | import com.fasterxml.jackson.databind.ser.std.DateSerializer; 18 | 19 | import io.swagger.annotations.ApiModelProperty; 20 | 21 | @Entity 22 | @Component 23 | @Table(name = "viagem") 24 | public class Viagem implements Serializable { 25 | 26 | private static final long serialVersionUID = -6888542263201514002L; 27 | 28 | @Id 29 | @GeneratedValue(strategy = GenerationType.AUTO) 30 | @ApiModelProperty(value = "Id da viagem") 31 | private Long id; 32 | 33 | @Column(name = "local_destino", nullable = false) 34 | @ApiModelProperty(value = "Local de destino da viagem") 35 | private String localDeDestino; 36 | 37 | @JsonSerialize(using = DateSerializer.class) 38 | @Column(name = "data_partida", nullable = false) 39 | @ApiModelProperty(value = "Data de partida da viagem (yyyy-MM-dd)") 40 | private Date dataPartida; 41 | 42 | @JsonSerialize(using = DateSerializer.class) 43 | @ApiModelProperty(value = "Data de retorno da viagem (yyyy-MM-dd)") 44 | @Column(name = "data_retorno", nullable = true) 45 | private Date dataRetorno; 46 | 47 | @Column(name = "acompanhante", nullable = true) 48 | @ApiModelProperty(value = "Nome do acompanhante da viagem") 49 | private String acompanhante; 50 | 51 | @Column(name = "regiao", nullable = true) 52 | @ApiModelProperty(value = "Região de destino da viagem [Norte, Sul, Leste, Oeste]") 53 | private String regiao; 54 | 55 | public Viagem() { 56 | 57 | } 58 | 59 | public Viagem(Long id, String localDeDestino, Date dataPartida, Date dataRetorno, String acompanhante) { 60 | this.id = id; 61 | this.localDeDestino = localDeDestino; 62 | this.dataPartida = dataPartida; 63 | this.dataRetorno = dataRetorno; 64 | this.acompanhante = acompanhante; 65 | } 66 | 67 | @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd") 68 | public Date getDataPartida() { 69 | return dataPartida; 70 | } 71 | 72 | public void setDataPartida(Date dataPartida) { 73 | this.dataPartida = dataPartida; 74 | } 75 | 76 | @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd") 77 | public Date getDataRetorno() { 78 | return dataRetorno; 79 | } 80 | 81 | public void setDataRetorno(Date dataRetorno) { 82 | this.dataRetorno = dataRetorno; 83 | } 84 | 85 | public String getAcompanhante() { 86 | return acompanhante; 87 | } 88 | 89 | public void setAcompanhante(String acompanhante) { 90 | this.acompanhante = acompanhante; 91 | } 92 | 93 | public Long getId() { 94 | return id; 95 | } 96 | 97 | public void setId(Long id) { 98 | this.id = id; 99 | } 100 | 101 | public String getLocalDeDestino() { 102 | return localDeDestino; 103 | } 104 | 105 | public void setLocalDeDestino(String localDeDestino) { 106 | this.localDeDestino = localDeDestino; 107 | } 108 | 109 | public String getRegiao() { 110 | return regiao; 111 | } 112 | 113 | public void setRegiao(String regiao) { 114 | this.regiao = regiao; 115 | } 116 | 117 | @Override 118 | public String toString() { 119 | return "Viagem [id=" + id + ", localDeDestino=" + localDeDestino + ", dataPartida=" + dataPartida 120 | + ", dataRetorno=" + dataRetorno + ", acompanhante=" + acompanhante + "]"; 121 | } 122 | 123 | } -------------------------------------------------------------------------------- /src/main/java/com/montanha/security/config/WebSecurityConfig.java: -------------------------------------------------------------------------------- 1 | package com.montanha.security.config; 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.security.authentication.AuthenticationManager; 7 | import org.springframework.security.config.BeanIds; 8 | import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; 9 | import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity; 10 | import org.springframework.security.config.annotation.web.builders.HttpSecurity; 11 | import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; 12 | import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; 13 | import org.springframework.security.config.http.SessionCreationPolicy; 14 | import org.springframework.security.core.userdetails.UserDetailsService; 15 | import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; 16 | import org.springframework.security.crypto.password.PasswordEncoder; 17 | import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter; 18 | import com.montanha.gerenciador.filter.JwtAuthenticationTokenFilter; 19 | import com.montanha.security.JwtAuthenticationEntryPoint; 20 | import com.montanha.security.utils.JwtTokenUtil; 21 | 22 | @Configuration 23 | @EnableWebSecurity 24 | @EnableGlobalMethodSecurity(prePostEnabled = true) 25 | public class WebSecurityConfig extends WebSecurityConfigurerAdapter { 26 | 27 | @Autowired 28 | private JwtAuthenticationEntryPoint unauthorizedHandler; 29 | 30 | @Autowired 31 | private UserDetailsService userDetailsService; 32 | 33 | @Autowired 34 | public void configureAuthentication(AuthenticationManagerBuilder authenticationManagerBuilder) throws Exception { 35 | authenticationManagerBuilder.userDetailsService(this.userDetailsService).passwordEncoder(passwordEncoder()); 36 | } 37 | 38 | @Bean 39 | public PasswordEncoder passwordEncoder() { 40 | return new BCryptPasswordEncoder(); 41 | } 42 | 43 | @Bean 44 | public JwtAuthenticationTokenFilter authenticationTokenFilterBean() throws Exception { 45 | return new JwtAuthenticationTokenFilter(); 46 | } 47 | 48 | @Bean 49 | public JwtTokenUtil jwtTokenUtilBean() throws Exception { 50 | return new JwtTokenUtil(); 51 | } 52 | 53 | @Bean(name = BeanIds.AUTHENTICATION_MANAGER) 54 | @Override 55 | public AuthenticationManager authenticationManagerBean() throws Exception { 56 | return super.authenticationManagerBean(); 57 | } 58 | 59 | 60 | @Override 61 | protected void configure(HttpSecurity httpSecurity) throws Exception { 62 | httpSecurity.csrf().disable().exceptionHandling().authenticationEntryPoint(unauthorizedHandler).and() 63 | .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and().authorizeRequests() 64 | .antMatchers("/api/v1/auth/**","/api/v1/status/**","/**/swagger-ui.html","/**/webjars/**", "/**/v2/api-docs/**", "/v2/api-docs", "/**/swagger-resources/**", "/swagger-resources").permitAll().anyRequest().authenticated(); 65 | httpSecurity.addFilterBefore(authenticationTokenFilterBean(), UsernamePasswordAuthenticationFilter.class); 66 | httpSecurity.headers().cacheControl(); 67 | 68 | } 69 | 70 | // 71 | // @Override 72 | // protected void configure(HttpSecurity httpSecurity) throws Exception { 73 | // httpSecurity.csrf().disable().exceptionHandling().authenticationEntryPoint(unauthorizedHandler).and() 74 | // .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and().authorizeRequests() 75 | // .antMatchers("/**").permitAll().anyRequest().authenticated(); 76 | // httpSecurity.addFilterBefore(authenticationTokenFilterBean(), UsernamePasswordAuthenticationFilter.class); 77 | // httpSecurity.headers().cacheControl(); 78 | // 79 | // } 80 | 81 | 82 | } 83 | -------------------------------------------------------------------------------- /src/main/java/com/montanha/security/utils/JwtTokenUtil.java: -------------------------------------------------------------------------------- 1 | package com.montanha.security.utils; 2 | 3 | import java.util.Date; 4 | import java.util.HashMap; 5 | import java.util.Map; 6 | 7 | import org.springframework.beans.factory.annotation.Value; 8 | import org.springframework.security.core.userdetails.UserDetails; 9 | import org.springframework.stereotype.Component; 10 | 11 | import io.jsonwebtoken.Claims; 12 | import io.jsonwebtoken.Jwts; 13 | import io.jsonwebtoken.SignatureAlgorithm; 14 | 15 | @Component 16 | public class JwtTokenUtil { 17 | 18 | static final String CLAIM_KEY_USERNAME = "sub"; 19 | static final String CLAIM_KEY_ROLE = "role"; 20 | static final String CLAIM_KEY_CREATED = "created"; 21 | 22 | @Value("${jwt.secret}") 23 | private String secret; 24 | 25 | @Value("${jwt.expiration}") 26 | private Long expiration; 27 | 28 | /** 29 | * Obtém o username (email) contido no token JWT. 30 | * 31 | * @param token 32 | * @return String 33 | */ 34 | public String getUsernameFromToken(String token) { 35 | String username; 36 | try { 37 | Claims claims = getClaimsFromToken(token); 38 | username = claims.getSubject(); 39 | } catch (Exception e) { 40 | username = null; 41 | } 42 | return username; 43 | } 44 | 45 | /** 46 | * Retorna a data de expiração de um token JWT. 47 | * 48 | * @param token 49 | * @return Date 50 | */ 51 | public Date getExpirationDateFromToken(String token) { 52 | Date expiration; 53 | try { 54 | Claims claims = getClaimsFromToken(token); 55 | expiration = claims.getExpiration(); 56 | } catch (Exception e) { 57 | expiration = null; 58 | } 59 | return expiration; 60 | } 61 | 62 | /** 63 | * Cria um novo token (refresh). 64 | * 65 | * @param token 66 | * @return String 67 | */ 68 | public String refreshToken(String token) { 69 | String refreshedToken; 70 | try { 71 | Claims claims = getClaimsFromToken(token); 72 | claims.put(CLAIM_KEY_CREATED, new Date()); 73 | refreshedToken = gerarToken(claims); 74 | } catch (Exception e) { 75 | refreshedToken = null; 76 | } 77 | return refreshedToken; 78 | } 79 | 80 | /** 81 | * Verifica e retorna se um token JWT é válido. 82 | * 83 | * @param token 84 | * @return boolean 85 | */ 86 | public boolean tokenValido(String token) { 87 | return !tokenExpirado(token); 88 | } 89 | 90 | /** 91 | * Retorna um novo token JWT com base nos dados do usuários. 92 | * 93 | * @param userDetails 94 | * @return String 95 | */ 96 | public String obterToken(UserDetails userDetails) { 97 | Map claims = new HashMap<>(); 98 | claims.put(CLAIM_KEY_USERNAME, userDetails.getUsername()); 99 | userDetails.getAuthorities().forEach(authority -> claims.put(CLAIM_KEY_ROLE, authority.getAuthority())); 100 | claims.put(CLAIM_KEY_CREATED, new Date()); 101 | 102 | return gerarToken(claims); 103 | } 104 | 105 | /** 106 | * Realiza o parse do token JWT para extrair as informações contidas no corpo 107 | * dele. 108 | * 109 | * @param token 110 | * @return Claims 111 | */ 112 | private Claims getClaimsFromToken(String token) { 113 | Claims claims; 114 | try { 115 | claims = Jwts.parser().setSigningKey(secret).parseClaimsJws(token).getBody(); 116 | } catch (Exception e) { 117 | claims = null; 118 | } 119 | return claims; 120 | } 121 | 122 | /** 123 | * Retorna a data de expiração com base na data atual. 124 | * 125 | * @return Date 126 | */ 127 | private Date gerarDataExpiracao() { 128 | return new Date(System.currentTimeMillis() + expiration * 1000); 129 | } 130 | 131 | /** 132 | * Verifica se um token JTW está expirado. 133 | * 134 | * @param token 135 | * @return boolean 136 | */ 137 | private boolean tokenExpirado(String token) { 138 | Date dataExpiracao = this.getExpirationDateFromToken(token); 139 | if (dataExpiracao == null) { 140 | return false; 141 | } 142 | return dataExpiracao.before(new Date()); 143 | } 144 | 145 | /** 146 | * Gera um novo token JWT contendo os dados (claims) fornecidos. 147 | * 148 | * @param claims 149 | * @return String 150 | */ 151 | private String gerarToken(Map claims) { 152 | return Jwts.builder().setClaims(claims).setExpiration(gerarDataExpiracao()) 153 | .signWith(SignatureAlgorithm.HS512, secret).compact(); 154 | } 155 | 156 | } 157 | -------------------------------------------------------------------------------- /src/main/java/com/montanha/security/controller/AuthenticationController.java: -------------------------------------------------------------------------------- 1 | package com.montanha.security.controller; 2 | 3 | import java.util.Optional; 4 | 5 | import javax.servlet.http.HttpServletRequest; 6 | import javax.validation.Valid; 7 | 8 | import io.swagger.annotations.ApiOperation; 9 | import org.slf4j.Logger; 10 | import org.slf4j.LoggerFactory; 11 | import org.springframework.beans.factory.annotation.Autowired; 12 | import org.springframework.http.HttpStatus; 13 | import org.springframework.http.ResponseEntity; 14 | import org.springframework.security.access.prepost.PreAuthorize; 15 | import org.springframework.security.authentication.AuthenticationManager; 16 | import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; 17 | import org.springframework.security.core.Authentication; 18 | import org.springframework.security.core.AuthenticationException; 19 | import org.springframework.security.core.context.SecurityContextHolder; 20 | import org.springframework.security.core.userdetails.UserDetails; 21 | import org.springframework.security.core.userdetails.UserDetailsService; 22 | import org.springframework.validation.BindingResult; 23 | import org.springframework.web.bind.annotation.*; 24 | 25 | import com.montanha.gerenciador.responses.Response; 26 | import com.montanha.gerenciador.dtos.JwtAuthenticationDto; 27 | import com.montanha.gerenciador.dtos.TokenDto; 28 | import com.montanha.security.utils.JwtTokenUtil; 29 | 30 | @RestController 31 | @CrossOrigin(origins = "*") 32 | public class AuthenticationController { 33 | 34 | private static final Logger log = LoggerFactory.getLogger(AuthenticationController.class); 35 | private static final String TOKEN_HEADER = "Authorization"; 36 | private static final String BEARER_PREFIX = "Bearer "; 37 | 38 | @Autowired 39 | private AuthenticationManager authenticationManager; 40 | 41 | @Autowired 42 | private JwtTokenUtil jwtTokenUtil; 43 | 44 | @Autowired 45 | private UserDetailsService userDetailsService; 46 | 47 | /** 48 | * Gera e retorna um novo token JWT. 49 | * 50 | * @param authenticationDto 51 | * @param result 52 | * @return ResponseEntity> 53 | * @throws AuthenticationException 54 | */ 55 | @PostMapping("/v1/auth") 56 | @ApiOperation(value = "Gera um Token de acesso") 57 | public ResponseEntity> gerarTokenJwt(@Valid @RequestBody JwtAuthenticationDto authenticationDto, 58 | BindingResult result) throws AuthenticationException { 59 | Response response = new Response(); 60 | 61 | if (result.hasErrors()) { 62 | log.error("Erro: {}", result.getAllErrors()); 63 | result.getAllErrors().forEach(error -> response.getErrors().add(error.getDefaultMessage())); 64 | return ResponseEntity.badRequest().body(response); 65 | } 66 | 67 | log.info("Gerando token para o email {}.", authenticationDto.getEmail()); 68 | Authentication authentication = authenticationManager.authenticate( 69 | new UsernamePasswordAuthenticationToken(authenticationDto.getEmail(), authenticationDto.getSenha())); 70 | SecurityContextHolder.getContext().setAuthentication(authentication); 71 | 72 | UserDetails userDetails = userDetailsService.loadUserByUsername(authenticationDto.getEmail()); 73 | String token = jwtTokenUtil.obterToken(userDetails); 74 | response.setData(new TokenDto(token)); 75 | 76 | return ResponseEntity.ok(response); 77 | } 78 | 79 | /** 80 | * Gera um novo token com uma nova data de expiração. 81 | * 82 | * @param request 83 | * @return ResponseEntity> 84 | */ 85 | // @PostMapping(value = "/refresh") 86 | // public ResponseEntity> gerarRefreshTokenJwt(HttpServletRequest request) { 87 | // log.info("Gerando refresh token JWT."); 88 | // Response response = new Response(); 89 | // Optional token = Optional.ofNullable(request.getHeader(TOKEN_HEADER)); 90 | // 91 | // if (token.isPresent() && token.get().startsWith(BEARER_PREFIX)) { 92 | // token = Optional.of(token.get().substring(7)); 93 | // } 94 | // 95 | // if (!token.isPresent()) { 96 | // response.getErrors().add("Token não informado."); 97 | // } else if (!jwtTokenUtil.tokenValido(token.get())) { 98 | // response.getErrors().add("Token inválido ou expirado."); 99 | // } 100 | // 101 | // if (!response.getErrors().isEmpty()) { 102 | // return ResponseEntity.badRequest().body(response); 103 | // } 104 | // 105 | // String refreshedToken = jwtTokenUtil.refreshToken(token.get()); 106 | // response.setData(new TokenDto(refreshedToken)); 107 | // 108 | // return ResponseEntity.ok(response); 109 | // } 110 | 111 | } 112 | -------------------------------------------------------------------------------- /src/main/java/com/montanha/gerenciador/services/ViagemServices.java: -------------------------------------------------------------------------------- 1 | package com.montanha.gerenciador.services; 2 | 3 | import java.io.IOException; 4 | import java.util.List; 5 | 6 | import com.montanha.gerenciador.dtos.ViagemDtoResponse; 7 | import com.montanha.gerenciador.utils.Conversor; 8 | import javassist.NotFoundException; 9 | import org.springframework.beans.factory.annotation.Autowired; 10 | import org.springframework.beans.factory.annotation.Value; 11 | import org.springframework.http.HttpStatus; 12 | import org.springframework.stereotype.Service; 13 | import org.springframework.web.client.HttpClientErrorException; 14 | import org.springframework.web.client.RestTemplate; 15 | 16 | import com.fasterxml.jackson.core.JsonParseException; 17 | import com.fasterxml.jackson.databind.JsonMappingException; 18 | import com.fasterxml.jackson.databind.ObjectMapper; 19 | import com.fasterxml.jackson.databind.node.ObjectNode; 20 | import com.montanha.gerenciador.dtos.ViagemDto; 21 | import com.montanha.gerenciador.entities.Viagem; 22 | import com.montanha.gerenciador.repositories.ViagemRepository; 23 | import com.montanha.gerenciador.services.exceptions.ViagemServiceException; 24 | 25 | import static java.lang.String.format; 26 | 27 | @Service 28 | public class ViagemServices { 29 | 30 | @Value("${previsaoDoTempoUri}") 31 | String previsaoDoTempoUri; 32 | 33 | @Autowired 34 | private ViagemRepository viagemRepository; 35 | 36 | @Autowired 37 | private ObjectMapper mapper; 38 | 39 | public List listar() { 40 | return viagemRepository.findAll(); 41 | } 42 | 43 | public Viagem salvar(ViagemDto viagemDto) { 44 | 45 | Viagem viagem = new Viagem(); 46 | 47 | viagem.setLocalDeDestino(viagemDto.getLocalDeDestino()); 48 | viagem.setDataPartida(viagemDto.getDataPartida()); 49 | viagem.setDataRetorno(viagemDto.getDataRetorno()); 50 | viagem.setAcompanhante(viagemDto.getAcompanhante()); 51 | viagem.setRegiao(viagemDto.getRegiao()); 52 | return viagemRepository.save(viagem); 53 | } 54 | 55 | public ViagemDtoResponse buscar(Long id) throws IOException, NotFoundException { 56 | Viagem viagem = viagemRepository.findOne(id); 57 | 58 | if (viagem == null) { 59 | throw new NotFoundException(format("Viagem com id: [%s] não encontrada", id)); 60 | 61 | } 62 | 63 | ViagemDtoResponse viagemDtoResponse = Conversor.converterViagemToViagemDtoResponse(viagem); 64 | String regiao = viagem.getRegiao(); 65 | 66 | if (regiao != null) { 67 | final String uri = previsaoDoTempoUri + "tempo-api/temperatura?regiao=" + regiao; 68 | RestTemplate restTemplate = new RestTemplate(); 69 | 70 | String previsaoJson = ""; 71 | 72 | try { 73 | previsaoJson = restTemplate.getForObject(uri, String.class); 74 | } catch (HttpClientErrorException hcee) { 75 | throw new HttpClientErrorException(HttpStatus.UNPROCESSABLE_ENTITY, "A API do Tempo não está online"); 76 | } 77 | 78 | ObjectNode node = mapper.readValue(previsaoJson, ObjectNode.class); 79 | viagemDtoResponse.setTemperatura((node.get("data").get("temperatura")).floatValue()); 80 | 81 | System.out.println(previsaoDoTempoUri); 82 | 83 | } 84 | 85 | return viagemDtoResponse; 86 | } 87 | 88 | public Viagem buscarPorLocalDeDestino(String localDeDestino) { 89 | Viagem viagem = viagemRepository.findByLocalDeDestino(localDeDestino); 90 | 91 | if (viagem == null) { 92 | throw new ViagemServiceException("Não existe esta viagem cadastrada"); 93 | } 94 | 95 | return viagem; 96 | } 97 | 98 | // Erro 500 porém com mensagem tratada. 99 | public List buscarViagensPorRegiao(String regiao) { 100 | List viagens = viagemRepository.findAllByRegiao(regiao); 101 | 102 | if (viagens.isEmpty()) { 103 | throw new ViagemServiceException("Não existem viagens cadastradas para esta Região"); 104 | } 105 | return viagens; 106 | } 107 | 108 | public List deletar(Viagem viagem) { 109 | 110 | viagemRepository.delete(viagem); 111 | 112 | return viagemRepository.findAll(); 113 | 114 | } 115 | 116 | public Viagem buscarSemTratativa(Long id) { 117 | Viagem viagem = viagemRepository.findOne(id); 118 | 119 | return viagem; 120 | } 121 | 122 | public Viagem alterar(ViagemDto viagemDto, Long id) { 123 | 124 | Viagem viagemExistente = viagemRepository.findOne(id); 125 | 126 | // iremos ter um nullPointerException aqui. 127 | viagemExistente.setLocalDeDestino(viagemDto.getLocalDeDestino()); 128 | viagemExistente.setDataPartida(viagemDto.getDataPartida()); 129 | viagemExistente.setDataRetorno(viagemDto.getDataRetorno()); 130 | viagemExistente.setAcompanhante(viagemDto.getAcompanhante()); 131 | viagemExistente.setRegiao(viagemDto.getRegiao()); 132 | return viagemRepository.save(viagemExistente); 133 | } 134 | 135 | } 136 | -------------------------------------------------------------------------------- /src/main/java/com/montanha/gerenciador/controller/GerenciadorViagemController.java: -------------------------------------------------------------------------------- 1 | package com.montanha.gerenciador.controller; 2 | 3 | import java.io.IOException; 4 | import java.net.URI; 5 | import java.util.Collections; 6 | import java.util.List; 7 | import javax.validation.Valid; 8 | 9 | import com.montanha.gerenciador.dtos.ViagemDtoResponse; 10 | import io.swagger.annotations.Api; 11 | import javassist.NotFoundException; 12 | import org.springframework.beans.factory.annotation.Autowired; 13 | import org.springframework.http.HttpStatus; 14 | import org.springframework.http.ResponseEntity; 15 | import org.springframework.security.access.prepost.PreAuthorize; 16 | import org.springframework.validation.BindingResult; 17 | import org.springframework.web.bind.annotation.*; 18 | import org.springframework.web.client.HttpClientErrorException; 19 | import org.springframework.web.servlet.support.ServletUriComponentsBuilder; 20 | 21 | 22 | import com.montanha.gerenciador.dtos.ViagemDto; 23 | import com.montanha.gerenciador.entities.Viagem; 24 | import com.montanha.gerenciador.responses.Response; 25 | import com.montanha.gerenciador.services.ViagemServices; 26 | 27 | import io.swagger.annotations.ApiOperation; 28 | 29 | @RestController 30 | @Api("GerenciadorViagensController") 31 | public class GerenciadorViagemController { 32 | 33 | @Autowired 34 | private ViagemServices viagemService; 35 | 36 | @ApiOperation(value = "Cadastra uma viagem") 37 | @PreAuthorize("hasAnyRole('ADMIN')") 38 | @RequestMapping(value = "/v1/viagens", method = RequestMethod.POST, produces = "application/json" ) 39 | @ResponseStatus(HttpStatus.CREATED) 40 | @ResponseBody 41 | public ResponseEntity> cadastrar(@Valid @RequestBody ViagemDto viagemDto, @RequestHeader String Authorization, BindingResult result) { 42 | 43 | // Não devemos expor entidades na resposta. 44 | Response response = new Response(); 45 | 46 | if (result.hasErrors()) { 47 | result.getAllErrors().forEach(error -> response.getErrors().add(error.getDefaultMessage())); 48 | return ResponseEntity.badRequest().body(response); 49 | } 50 | 51 | Viagem viagemSalva = this.viagemService.salvar(viagemDto); 52 | URI location = ServletUriComponentsBuilder.fromCurrentRequest().path("/{id}").buildAndExpand(viagemSalva.getId()) 53 | .toUri(); 54 | 55 | response.setData(viagemSalva); 56 | 57 | return ResponseEntity.created(location).body(response); 58 | } 59 | 60 | @ApiOperation(value = "Retorna todas as viagens") 61 | @RequestMapping(value = "/v1/viagens", method = RequestMethod.GET, produces = "application/json") 62 | @PreAuthorize("hasAnyRole('USUARIO')") 63 | public ResponseEntity>> listar(@RequestParam(value = "regiao", required = false) String regiao, @RequestHeader String Authorization) { 64 | List viagens = null; 65 | 66 | if (regiao == null) { 67 | viagens = viagemService.listar(); 68 | } else { 69 | viagens = viagemService.buscarViagensPorRegiao(regiao); 70 | } 71 | 72 | Response> viagensResponse = new Response<>(); 73 | viagensResponse.setData(viagens); 74 | return ResponseEntity.status(HttpStatus.OK).body(viagensResponse); 75 | } 76 | 77 | @ApiOperation(value = "Retorna uma viagem específica") 78 | @RequestMapping(value = "/v1/viagens/{id}", method = RequestMethod.GET, produces = "application/json") 79 | @PreAuthorize("hasAnyRole('USUARIO')") 80 | public ResponseEntity> buscar(@PathVariable("id") Long id, @RequestHeader String Authorization) throws IOException { 81 | Response response = new Response(); 82 | ViagemDtoResponse viagemDtoResponse; 83 | try { 84 | viagemDtoResponse = viagemService.buscar(id); 85 | 86 | } 87 | 88 | catch (NotFoundException e) { 89 | response.setErrors(Collections.singletonList(e.getMessage())); 90 | return ResponseEntity.status(HttpStatus.NOT_FOUND).body(response); 91 | } 92 | 93 | catch (HttpClientErrorException hce) { 94 | response.setErrors(Collections.singletonList(hce.getStatusText())); 95 | return ResponseEntity.status(HttpStatus.UNPROCESSABLE_ENTITY).body(response); 96 | } 97 | 98 | response.setData(viagemDtoResponse); 99 | 100 | return ResponseEntity.status(HttpStatus.OK).body(response); 101 | } 102 | 103 | 104 | 105 | @ApiOperation(value = "Apaga uma viagem específica") 106 | @RequestMapping(value = "/v1/viagens/{id}", method = RequestMethod.DELETE, produces = "application/json") 107 | @PreAuthorize("hasAnyRole('ADMIN')") 108 | @ResponseStatus(value = HttpStatus.NO_CONTENT) 109 | public void delete(@PathVariable("id") Long id, @RequestHeader String Authorization) { 110 | 111 | Viagem viagem = viagemService.buscarSemTratativa(id); 112 | viagemService.deletar(viagem); 113 | 114 | } 115 | 116 | @ApiOperation(value = "Atualiza uma viagem específica") 117 | @RequestMapping(value = "/v1/viagens/{id}", method = RequestMethod.PUT, produces = "application/json") 118 | @PreAuthorize("hasAnyRole('ADMIN')") 119 | public ResponseEntity> alterar(@PathVariable("id") Long id,@Valid @RequestBody ViagemDto viagemDto, @RequestHeader String Authorization) { 120 | 121 | 122 | viagemService.alterar(viagemDto, id); 123 | 124 | Response response = new Response<>(); 125 | 126 | return ResponseEntity.status(HttpStatus.NO_CONTENT).body(response); 127 | } 128 | 129 | 130 | } 131 | -------------------------------------------------------------------------------- /mvnw.cmd: -------------------------------------------------------------------------------- 1 | @REM ---------------------------------------------------------------------------- 2 | @REM Licensed to the Apache Software Foundation (ASF) under one 3 | @REM or more contributor license agreements. See the NOTICE file 4 | @REM distributed with this work for additional information 5 | @REM regarding copyright ownership. The ASF licenses this file 6 | @REM to you under the Apache License, Version 2.0 (the 7 | @REM "License"); you may not use this file except in compliance 8 | @REM with the License. You may obtain a copy of the License at 9 | @REM 10 | @REM http://www.apache.org/licenses/LICENSE-2.0 11 | @REM 12 | @REM Unless required by applicable law or agreed to in writing, 13 | @REM software distributed under the License is distributed on an 14 | @REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 15 | @REM KIND, either express or implied. See the License for the 16 | @REM specific language governing permissions and limitations 17 | @REM under the License. 18 | @REM ---------------------------------------------------------------------------- 19 | 20 | @REM ---------------------------------------------------------------------------- 21 | @REM Maven2 Start Up Batch script 22 | @REM 23 | @REM Required ENV vars: 24 | @REM JAVA_HOME - location of a JDK home dir 25 | @REM 26 | @REM Optional ENV vars 27 | @REM M2_HOME - location of maven2's installed home dir 28 | @REM MAVEN_BATCH_ECHO - set to 'on' to enable the echoing of the batch commands 29 | @REM MAVEN_BATCH_PAUSE - set to 'on' to wait for a key stroke before ending 30 | @REM MAVEN_OPTS - parameters passed to the Java VM when running Maven 31 | @REM e.g. to debug Maven itself, use 32 | @REM set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 33 | @REM MAVEN_SKIP_RC - flag to disable loading of mavenrc files 34 | @REM ---------------------------------------------------------------------------- 35 | 36 | @REM Begin all REM lines with '@' in case MAVEN_BATCH_ECHO is 'on' 37 | @echo off 38 | @REM enable echoing my setting MAVEN_BATCH_ECHO to 'on' 39 | @if "%MAVEN_BATCH_ECHO%" == "on" echo %MAVEN_BATCH_ECHO% 40 | 41 | @REM set %HOME% to equivalent of $HOME 42 | if "%HOME%" == "" (set "HOME=%HOMEDRIVE%%HOMEPATH%") 43 | 44 | @REM Execute a user defined script before this one 45 | if not "%MAVEN_SKIP_RC%" == "" goto skipRcPre 46 | @REM check for pre script, once with legacy .bat ending and once with .cmd ending 47 | if exist "%HOME%\mavenrc_pre.bat" call "%HOME%\mavenrc_pre.bat" 48 | if exist "%HOME%\mavenrc_pre.cmd" call "%HOME%\mavenrc_pre.cmd" 49 | :skipRcPre 50 | 51 | @setlocal 52 | 53 | set ERROR_CODE=0 54 | 55 | @REM To isolate internal variables from possible post scripts, we use another setlocal 56 | @setlocal 57 | 58 | @REM ==== START VALIDATION ==== 59 | if not "%JAVA_HOME%" == "" goto OkJHome 60 | 61 | echo. 62 | echo Error: JAVA_HOME not found in your environment. >&2 63 | echo Please set the JAVA_HOME variable in your environment to match the >&2 64 | echo location of your Java installation. >&2 65 | echo. 66 | goto error 67 | 68 | :OkJHome 69 | if exist "%JAVA_HOME%\bin\java.exe" goto init 70 | 71 | echo. 72 | echo Error: JAVA_HOME is set to an invalid directory. >&2 73 | echo JAVA_HOME = "%JAVA_HOME%" >&2 74 | echo Please set the JAVA_HOME variable in your environment to match the >&2 75 | echo location of your Java installation. >&2 76 | echo. 77 | goto error 78 | 79 | @REM ==== END VALIDATION ==== 80 | 81 | :init 82 | 83 | @REM Find the project base dir, i.e. the directory that contains the folder ".mvn". 84 | @REM Fallback to current working directory if not found. 85 | 86 | set MAVEN_PROJECTBASEDIR=%MAVEN_BASEDIR% 87 | IF NOT "%MAVEN_PROJECTBASEDIR%"=="" goto endDetectBaseDir 88 | 89 | set EXEC_DIR=%CD% 90 | set WDIR=%EXEC_DIR% 91 | :findBaseDir 92 | IF EXIST "%WDIR%"\.mvn goto baseDirFound 93 | cd .. 94 | IF "%WDIR%"=="%CD%" goto baseDirNotFound 95 | set WDIR=%CD% 96 | goto findBaseDir 97 | 98 | :baseDirFound 99 | set MAVEN_PROJECTBASEDIR=%WDIR% 100 | cd "%EXEC_DIR%" 101 | goto endDetectBaseDir 102 | 103 | :baseDirNotFound 104 | set MAVEN_PROJECTBASEDIR=%EXEC_DIR% 105 | cd "%EXEC_DIR%" 106 | 107 | :endDetectBaseDir 108 | 109 | IF NOT EXIST "%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config" goto endReadAdditionalConfig 110 | 111 | @setlocal EnableExtensions EnableDelayedExpansion 112 | for /F "usebackq delims=" %%a in ("%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config") do set JVM_CONFIG_MAVEN_PROPS=!JVM_CONFIG_MAVEN_PROPS! %%a 113 | @endlocal & set JVM_CONFIG_MAVEN_PROPS=%JVM_CONFIG_MAVEN_PROPS% 114 | 115 | :endReadAdditionalConfig 116 | 117 | SET MAVEN_JAVA_EXE="%JAVA_HOME%\bin\java.exe" 118 | 119 | set WRAPPER_JAR="%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.jar" 120 | set WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain 121 | 122 | %MAVEN_JAVA_EXE% %JVM_CONFIG_MAVEN_PROPS% %MAVEN_OPTS% %MAVEN_DEBUG_OPTS% -classpath %WRAPPER_JAR% "-Dmaven.multiModuleProjectDirectory=%MAVEN_PROJECTBASEDIR%" %WRAPPER_LAUNCHER% %MAVEN_CONFIG% %* 123 | if ERRORLEVEL 1 goto error 124 | goto end 125 | 126 | :error 127 | set ERROR_CODE=1 128 | 129 | :end 130 | @endlocal & set ERROR_CODE=%ERROR_CODE% 131 | 132 | if not "%MAVEN_SKIP_RC%" == "" goto skipRcPost 133 | @REM check for post script, once with legacy .bat ending and once with .cmd ending 134 | if exist "%HOME%\mavenrc_post.bat" call "%HOME%\mavenrc_post.bat" 135 | if exist "%HOME%\mavenrc_post.cmd" call "%HOME%\mavenrc_post.cmd" 136 | :skipRcPost 137 | 138 | @REM pause the script if MAVEN_BATCH_PAUSE is set to 'on' 139 | if "%MAVEN_BATCH_PAUSE%" == "on" pause 140 | 141 | if "%MAVEN_TERMINATE_CMD%" == "on" exit %ERROR_CODE% 142 | 143 | exit /B %ERROR_CODE% 144 | -------------------------------------------------------------------------------- /mvnw: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | # ---------------------------------------------------------------------------- 3 | # Licensed to the Apache Software Foundation (ASF) under one 4 | # or more contributor license agreements. See the NOTICE file 5 | # distributed with this work for additional information 6 | # regarding copyright ownership. The ASF licenses this file 7 | # to you under the Apache License, Version 2.0 (the 8 | # "License"); you may not use this file except in compliance 9 | # with the License. You may obtain a copy of the License at 10 | # 11 | # http://www.apache.org/licenses/LICENSE-2.0 12 | # 13 | # Unless required by applicable law or agreed to in writing, 14 | # software distributed under the License is distributed on an 15 | # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 16 | # KIND, either express or implied. See the License for the 17 | # specific language governing permissions and limitations 18 | # under the License. 19 | # ---------------------------------------------------------------------------- 20 | 21 | # ---------------------------------------------------------------------------- 22 | # Maven2 Start Up Batch script 23 | # 24 | # Required ENV vars: 25 | # ------------------ 26 | # JAVA_HOME - location of a JDK home dir 27 | # 28 | # Optional ENV vars 29 | # ----------------- 30 | # M2_HOME - location of maven2's installed home dir 31 | # MAVEN_OPTS - parameters passed to the Java VM when running Maven 32 | # e.g. to debug Maven itself, use 33 | # set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 34 | # MAVEN_SKIP_RC - flag to disable loading of mavenrc files 35 | # ---------------------------------------------------------------------------- 36 | 37 | if [ -z "$MAVEN_SKIP_RC" ] ; then 38 | 39 | if [ -f /etc/mavenrc ] ; then 40 | . /etc/mavenrc 41 | fi 42 | 43 | if [ -f "$HOME/.mavenrc" ] ; then 44 | . "$HOME/.mavenrc" 45 | fi 46 | 47 | fi 48 | 49 | # OS specific support. $var _must_ be set to either true or false. 50 | cygwin=false; 51 | darwin=false; 52 | mingw=false 53 | case "`uname`" in 54 | CYGWIN*) cygwin=true ;; 55 | MINGW*) mingw=true;; 56 | Darwin*) darwin=true 57 | # Use /usr/libexec/java_home if available, otherwise fall back to /Library/Java/Home 58 | # See https://developer.apple.com/library/mac/qa/qa1170/_index.html 59 | if [ -z "$JAVA_HOME" ]; then 60 | if [ -x "/usr/libexec/java_home" ]; then 61 | export JAVA_HOME="`/usr/libexec/java_home`" 62 | else 63 | export JAVA_HOME="/Library/Java/Home" 64 | fi 65 | fi 66 | ;; 67 | esac 68 | 69 | if [ -z "$JAVA_HOME" ] ; then 70 | if [ -r /etc/gentoo-release ] ; then 71 | JAVA_HOME=`java-config --jre-home` 72 | fi 73 | fi 74 | 75 | if [ -z "$M2_HOME" ] ; then 76 | ## resolve links - $0 may be a link to maven's home 77 | PRG="$0" 78 | 79 | # need this for relative symlinks 80 | while [ -h "$PRG" ] ; do 81 | ls=`ls -ld "$PRG"` 82 | link=`expr "$ls" : '.*-> \(.*\)$'` 83 | if expr "$link" : '/.*' > /dev/null; then 84 | PRG="$link" 85 | else 86 | PRG="`dirname "$PRG"`/$link" 87 | fi 88 | done 89 | 90 | saveddir=`pwd` 91 | 92 | M2_HOME=`dirname "$PRG"`/.. 93 | 94 | # make it fully qualified 95 | M2_HOME=`cd "$M2_HOME" && pwd` 96 | 97 | cd "$saveddir" 98 | # echo Using m2 at $M2_HOME 99 | fi 100 | 101 | # For Cygwin, ensure paths are in UNIX format before anything is touched 102 | if $cygwin ; then 103 | [ -n "$M2_HOME" ] && 104 | M2_HOME=`cygpath --unix "$M2_HOME"` 105 | [ -n "$JAVA_HOME" ] && 106 | JAVA_HOME=`cygpath --unix "$JAVA_HOME"` 107 | [ -n "$CLASSPATH" ] && 108 | CLASSPATH=`cygpath --path --unix "$CLASSPATH"` 109 | fi 110 | 111 | # For Migwn, ensure paths are in UNIX format before anything is touched 112 | if $mingw ; then 113 | [ -n "$M2_HOME" ] && 114 | M2_HOME="`(cd "$M2_HOME"; pwd)`" 115 | [ -n "$JAVA_HOME" ] && 116 | JAVA_HOME="`(cd "$JAVA_HOME"; pwd)`" 117 | # TODO classpath? 118 | fi 119 | 120 | if [ -z "$JAVA_HOME" ]; then 121 | javaExecutable="`which javac`" 122 | if [ -n "$javaExecutable" ] && ! [ "`expr \"$javaExecutable\" : '\([^ ]*\)'`" = "no" ]; then 123 | # readlink(1) is not available as standard on Solaris 10. 124 | readLink=`which readlink` 125 | if [ ! `expr "$readLink" : '\([^ ]*\)'` = "no" ]; then 126 | if $darwin ; then 127 | javaHome="`dirname \"$javaExecutable\"`" 128 | javaExecutable="`cd \"$javaHome\" && pwd -P`/javac" 129 | else 130 | javaExecutable="`readlink -f \"$javaExecutable\"`" 131 | fi 132 | javaHome="`dirname \"$javaExecutable\"`" 133 | javaHome=`expr "$javaHome" : '\(.*\)/bin'` 134 | JAVA_HOME="$javaHome" 135 | export JAVA_HOME 136 | fi 137 | fi 138 | fi 139 | 140 | if [ -z "$JAVACMD" ] ; then 141 | if [ -n "$JAVA_HOME" ] ; then 142 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 143 | # IBM's JDK on AIX uses strange locations for the executables 144 | JAVACMD="$JAVA_HOME/jre/sh/java" 145 | else 146 | JAVACMD="$JAVA_HOME/bin/java" 147 | fi 148 | else 149 | JAVACMD="`which java`" 150 | fi 151 | fi 152 | 153 | if [ ! -x "$JAVACMD" ] ; then 154 | echo "Error: JAVA_HOME is not defined correctly." >&2 155 | echo " We cannot execute $JAVACMD" >&2 156 | exit 1 157 | fi 158 | 159 | if [ -z "$JAVA_HOME" ] ; then 160 | echo "Warning: JAVA_HOME environment variable is not set." 161 | fi 162 | 163 | CLASSWORLDS_LAUNCHER=org.codehaus.plexus.classworlds.launcher.Launcher 164 | 165 | # traverses directory structure from process work directory to filesystem root 166 | # first directory with .mvn subdirectory is considered project base directory 167 | find_maven_basedir() { 168 | 169 | if [ -z "$1" ] 170 | then 171 | echo "Path not specified to find_maven_basedir" 172 | return 1 173 | fi 174 | 175 | basedir="$1" 176 | wdir="$1" 177 | while [ "$wdir" != '/' ] ; do 178 | if [ -d "$wdir"/.mvn ] ; then 179 | basedir=$wdir 180 | break 181 | fi 182 | # workaround for JBEAP-8937 (on Solaris 10/Sparc) 183 | if [ -d "${wdir}" ]; then 184 | wdir=`cd "$wdir/.."; pwd` 185 | fi 186 | # end of workaround 187 | done 188 | echo "${basedir}" 189 | } 190 | 191 | # concatenates all lines of a file 192 | concat_lines() { 193 | if [ -f "$1" ]; then 194 | echo "$(tr -s '\n' ' ' < "$1")" 195 | fi 196 | } 197 | 198 | BASE_DIR=`find_maven_basedir "$(pwd)"` 199 | if [ -z "$BASE_DIR" ]; then 200 | exit 1; 201 | fi 202 | 203 | export MAVEN_PROJECTBASEDIR=${MAVEN_BASEDIR:-"$BASE_DIR"} 204 | echo $MAVEN_PROJECTBASEDIR 205 | MAVEN_OPTS="$(concat_lines "$MAVEN_PROJECTBASEDIR/.mvn/jvm.config") $MAVEN_OPTS" 206 | 207 | # For Cygwin, switch paths to Windows format before running java 208 | if $cygwin; then 209 | [ -n "$M2_HOME" ] && 210 | M2_HOME=`cygpath --path --windows "$M2_HOME"` 211 | [ -n "$JAVA_HOME" ] && 212 | JAVA_HOME=`cygpath --path --windows "$JAVA_HOME"` 213 | [ -n "$CLASSPATH" ] && 214 | CLASSPATH=`cygpath --path --windows "$CLASSPATH"` 215 | [ -n "$MAVEN_PROJECTBASEDIR" ] && 216 | MAVEN_PROJECTBASEDIR=`cygpath --path --windows "$MAVEN_PROJECTBASEDIR"` 217 | fi 218 | 219 | WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain 220 | 221 | exec "$JAVACMD" \ 222 | $MAVEN_OPTS \ 223 | -classpath "$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.jar" \ 224 | "-Dmaven.home=${M2_HOME}" "-Dmaven.multiModuleProjectDirectory=${MAVEN_PROJECTBASEDIR}" \ 225 | ${WRAPPER_LAUNCHER} $MAVEN_CONFIG "$@" 226 | -------------------------------------------------------------------------------- /swaggerfile.yml: -------------------------------------------------------------------------------- 1 | swagger: "2.0" 2 | info: 3 | description: "Encontre aqui toda a documentação referente a API Gerenciador de Viagem de Antonio Montanha" 4 | version: "1.0.0" 5 | title: "Gerenciador de Viagens" 6 | termsOfService: "https://github.com/AntonioMontanha/gerenciador-viagens" 7 | contact: 8 | email: "ammontanha@gmail.com" 9 | license: 10 | name: "Apache 2.0" 11 | url: "http://www.apache.org/licenses/LICENSE-2.0.html" 12 | host: "localhost:8089" 13 | basePath: "/" 14 | tags: 15 | - name: "auth" 16 | description: "Mecanismos de autenticação" 17 | schemes: 18 | - "http" 19 | paths: 20 | /api/auth: 21 | post: 22 | tags: 23 | - "auth" 24 | summary: "Logar como Usuário ou Administrador" 25 | description: "Através deste endpoint podemos fazer login para capturar o token e utilizar a API" 26 | operationId: "authenticacao" 27 | produces: 28 | - "application/json" 29 | parameters: 30 | - in: "body" 31 | name: "body" 32 | description: "Dados para fazer login" 33 | required: true 34 | schema: 35 | $ref: "#/definitions/Auth" 36 | responses: 37 | 200: 38 | description: "Sucesso" 39 | schema: 40 | $ref: "#/definitions/AuthResponse" 41 | /api/viagem: 42 | post: 43 | tags: 44 | - "viagem" 45 | summary: "Inserir uma nova viagem" 46 | description: "Inserir uma nova viagem que será utilizada pelo sistema" 47 | operationId: "post_viagem" 48 | produces: 49 | - "application/json" 50 | parameters: 51 | - name: "Authorization" 52 | in: "header" 53 | description: "Token para autenticação" 54 | required: true 55 | type: "string" 56 | - name: "body" 57 | in: "body" 58 | description: "Dados para fazer login" 59 | required: true 60 | schema: 61 | $ref: "#/definitions/Viagem" 62 | responses: 63 | 201: 64 | description: "Sucesso" 65 | schema: 66 | $ref: '#/definitions/ViagemResponse' 67 | 400: 68 | description: "Erros de negócio" 69 | schema: 70 | $ref: '#/definitions/ErroResponse' 71 | get: 72 | tags: 73 | - "viagem" 74 | summary: "Procurar viagem" 75 | description: "Retorna uma lista de viagem" 76 | operationId: "getViagem" 77 | produces: 78 | - "application/json" 79 | parameters: 80 | - name: "Authorization" 81 | in: "header" 82 | description: "Token para autenticação" 83 | required: true 84 | type: "string" 85 | - name: "localDeDestino" 86 | in: query 87 | description: "Filtro para busca de viagens por sua localização" 88 | required: false 89 | type: "string" 90 | responses: 91 | 200: 92 | description: "Sucesso" 93 | schema: 94 | $ref: "#/definitions/ListaViagemResponse" 95 | /api/viagem/{viagemId}: 96 | get: 97 | tags: 98 | - "viagem" 99 | summary: "Procurar uma viagem pelo ID" 100 | description: "Retorna uma única viagem" 101 | operationId: "getViagemPeloID" 102 | produces: 103 | - "application/json" 104 | parameters: 105 | - name: "Authorization" 106 | in: "header" 107 | description: "Token para autenticação" 108 | required: true 109 | type: "string" 110 | - name: "viagemId" 111 | in: "path" 112 | description: "ID de uma viagem" 113 | required: true 114 | type: "integer" 115 | format: "int64" 116 | responses: 117 | 200: 118 | description: "Sucesso" 119 | schema: 120 | $ref: "#/definitions/ViagemResponse" 121 | 400: 122 | description: "ID inválido" 123 | 404: 124 | description: "Viagem não encontrada" 125 | put: 126 | tags: 127 | - "viagem" 128 | summary: "Alterar uma viagem" 129 | description: "Alterar uma viagem" 130 | operationId: "update_viagem" 131 | produces: 132 | - "application/json" 133 | parameters: 134 | - name: "Authorization" 135 | in: "header" 136 | description: "Token para autenticação" 137 | required: true 138 | type: "string" 139 | - name: "viagemId" 140 | in: "path" 141 | description: "ID de uma viagem" 142 | required: true 143 | type: "integer" 144 | format: "int64" 145 | - name: "body" 146 | in: "body" 147 | description: "Dados para fazer login" 148 | required: true 149 | schema: 150 | $ref: "#/definitions/Viagem" 151 | responses: 152 | 200: 153 | description: "Sucesso" 154 | schema: 155 | $ref: '#/definitions/ViagemResponse' 156 | 400: 157 | description: "Erros de negócio" 158 | schema: 159 | $ref: '#/definitions/ErroResponse' 160 | delete: 161 | tags: 162 | - "viagem" 163 | summary: "Remover uma viagem pelo ID" 164 | description: "Remove uma única viagem" 165 | operationId: "deleteViagemPeloID" 166 | produces: 167 | - "application/json" 168 | parameters: 169 | - name: "Authorization" 170 | in: "header" 171 | description: "Token para autenticação" 172 | required: true 173 | type: "string" 174 | - name: "viagemId" 175 | in: "path" 176 | description: "ID de uma viagem" 177 | required: true 178 | type: "integer" 179 | format: "int64" 180 | responses: 181 | 204: 182 | description: "Sucesso" 183 | 400: 184 | description: "ID inválido" 185 | 404: 186 | description: "Viagem não encontrada" 187 | 188 | definitions: 189 | Auth: 190 | type: "object" 191 | properties: 192 | email: 193 | type: "string" 194 | senha: 195 | type: "string" 196 | AuthResponse: 197 | type: "object" 198 | properties: 199 | data: 200 | type: "object" 201 | properties: 202 | token: 203 | type: "string" 204 | errors: 205 | type: "array" 206 | items: {} 207 | Viagem: 208 | type: "object" 209 | properties: 210 | localDeDestino: 211 | type: "string" 212 | dataPartida: 213 | type: "string" 214 | format: "full-date" 215 | dataRetorno: 216 | type: "string" 217 | format: "full-date" 218 | acompanhante: 219 | type: "string" 220 | regiao: 221 | type: "string" 222 | ViagemResponse: 223 | type: "object" 224 | properties: 225 | data: 226 | type: "object" 227 | properties: 228 | id: 229 | type: "integer" 230 | localDeDestino: 231 | type: "string" 232 | dataPartida: 233 | type: "string" 234 | format: "full-date" 235 | dataRetorno: 236 | type: "string" 237 | format: "full-date" 238 | acompanhante: 239 | type: "string" 240 | regiao: 241 | type: "string" 242 | temperatura: 243 | type: "number" 244 | errors: 245 | type: "array" 246 | items: {} 247 | ListaViagemResponse: 248 | type: "array" 249 | items: { 250 | $ref: "#/definitions/ViagemResponse" 251 | } 252 | ErroResponse: 253 | type: "object" 254 | properties: 255 | data: 256 | type: "object" 257 | errors: 258 | type: "array" 259 | items: {} 260 | externalDocs: 261 | description: "Find out more about Swagger" 262 | url: "http://swagger.io" 263 | --------------------------------------------------------------------------------