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

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
.settings
.DS_Store
.classpath
.factorypath
target/
.project
38 changes: 38 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,43 @@
# Show me the code

### # Instruções para rodar a Api.

<p>1- Primeiramente, ir na pasta raiz do projeto e compile com o maven</p>

./mvnw clean install

<p>2- Na pasta Targat Clique 2x no TestBackJava-1.jar</p>
<p>3- A api está usando segurança Oauth 2
Então é necessario fazer um POST primeiro no endpoint:</p>

http://localhost:8000/gasto/oauth/token

Como Authorization basic, deve-se passar o username e passaword que nesse caso é "cliente".
No Body da requisição deve se passar;
chave Valor
client cliente
username admin
password admin
grant_type password
na resposta existe um access_token o qual deve ser copiado e passado no header do http para as outras requisições.
4- A api responde os seguinte endPoonts;

```
POST http://localhost:8000/gasto/ --> Para a inclusão de gastos, exemplo.
{
"descricao" : "teste",
"codigoUsuario" : 1,
"valor" : "200.00",
"data" : "2019-09-20T18:54:10",
"categoria": ""
}
GET http://localhost:8000/gasto/{idUsuario}/listagemGasto e http://localhost:8000/gasto/{idUsuario}/listagemGasto?data={2019-09-20} --> Para consulta de gastos
PUT http://localhost:8000/gasto/{idGasto}/categoria --> Altera uma categoria caso ela possa ser alterada
GET http://localhost:8000/gasto/categoria/filtro?categoria={caracter} --> lista categorias que iniciam com um caracter
```
*O banco de Dados ultilizado foi o H2, um banco em memoria.


### # DESAFIO:

API REST para Gestão de Gastos!
Expand Down
75 changes: 75 additions & 0 deletions pom.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.7.RELEASE</version>
<relativePath /> <!-- lookup parent from repository -->
</parent>
<groupId>com.santander</groupId>
<artifactId>TestBackJava</artifactId>
<version>1</version>
<name>TestBackJava</name>
<description>Demo project for Spring Boot</description>

<properties>
<java.version>1.8</java.version>
</properties>

<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>

<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>

<dependency>
<groupId>com.fasterxml.jackson.datatype</groupId>
<artifactId>jackson-datatype-jsr310</artifactId>
</dependency>

<dependency>
<groupId>org.springframework.security.oauth</groupId>
<artifactId>spring-security-oauth2</artifactId>
<version>2.3.5.RELEASE</version>
</dependency>

<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-jwt</artifactId>
<version>1.0.10.RELEASE</version>
</dependency>
</dependencies>

<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>

</project>
13 changes: 13 additions & 0 deletions src/main/java/com/santander/TestBackJavaApplication.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
package com.santander;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class TestBackJavaApplication {

public static void main(String[] args) {
SpringApplication.run(TestBackJavaApplication.class, args);
}

}
46 changes: 46 additions & 0 deletions src/main/java/com/santander/config/AuthorizationServerConfig.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
package com.santander.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;
import org.springframework.security.oauth2.provider.token.store.JwtTokenStore;

@Configuration
@EnableAuthorizationServer
public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {

@Autowired
private AuthenticationManager authenticationManager;

@Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
clients.inMemory().withClient("cliente").secret("cliente").scopes("read", "write")
.authorizedGrantTypes("password").accessTokenValiditySeconds(1800);
}

@Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
endpoints.tokenStore(tokenStore()).accessTokenConverter(accessTokenConverter())
.authenticationManager(authenticationManager);
}

@Bean
public JwtAccessTokenConverter accessTokenConverter() {
JwtAccessTokenConverter accessTokenConverter = new JwtAccessTokenConverter();
accessTokenConverter.setSigningKey("algaworks");
return accessTokenConverter;
}

@Bean
public TokenStore tokenStore() {
return new JwtTokenStore(accessTokenConverter());
}

}
25 changes: 25 additions & 0 deletions src/main/java/com/santander/config/OAuthSecurityConfig.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
package com.santander.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.password.NoOpPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

@Configuration
@EnableWebSecurity
public class OAuthSecurityConfig extends WebSecurityConfigurerAdapter {

@Bean
@Override
public AuthenticationManager authenticationManager() throws Exception {
return super.authenticationManager();
}

@Bean
public PasswordEncoder passwordEncoder() {
return NoOpPasswordEncoder.getInstance();
}
}
39 changes: 39 additions & 0 deletions src/main/java/com/santander/config/ResourceServerConfig.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
package com.santander.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
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.http.SessionCreationPolicy;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer;

@Configuration
@EnableWebSecurity
@EnableResourceServer
public class ResourceServerConfig extends ResourceServerConfigurerAdapter {

@Autowired
public void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication()
.withUser("admin").password("admin").roles("ROLE");
}

@Override
public void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/categorias").permitAll()
.anyRequest().authenticated()
.and()
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and()
.csrf().disable();
}

@Override
public void configure(ResourceServerSecurityConfigurer resources) throws Exception {
resources.stateless(true);
}

}
122 changes: 122 additions & 0 deletions src/main/java/com/santander/model/Gasto.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,122 @@
package com.santander.model;

import java.math.BigDecimal;
import java.time.LocalDateTime;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.Size;

@Entity
public class Gasto {

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;

@NotBlank
@Size(min = 3, max = 250)
@Column(name = "descricao")
private String descricao;

@Column(name = "valor")
private BigDecimal valor;

@Column(name = "codigoUsuario")
private int codigoUsuario;

@Column(name = "data")
private LocalDateTime data;

@Column(name = "categoria")
private String categoria;

public Long getId() {
return id;
}

public void setId(Long id) {
this.id = id;
}

public String getDescricao() {
return descricao;
}

public void setDescricao(String descricao) {
this.descricao = descricao;
}

public BigDecimal getValor() {
return valor;
}

public void setValor(BigDecimal valor) {
this.valor = valor;
}

public int getCodigoUsuario() {
return codigoUsuario;
}

public void setCodigoUsuario(int codigoUsuario) {
this.codigoUsuario = codigoUsuario;
}

public LocalDateTime getData() {
return data;
}

public void setData(LocalDateTime data) {
this.data = data;
}

public boolean temCategoria() {
return false;

}

public String getCategoria() {
return categoria;
}

public void setCategoria(String categoria) {
this.categoria = categoria;
}

@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((data == null) ? 0 : data.hashCode());
result = prime * result + ((id == null) ? 0 : id.hashCode());
return result;
}

@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Gasto other = (Gasto) obj;
if (data == null) {
if (other.data != null)
return false;
} else if (!data.equals(other.data))
return false;
if (id == null) {
if (other.id != null)
return false;
} else if (!id.equals(other.id))
return false;
return true;
}

}
18 changes: 18 additions & 0 deletions src/main/java/com/santander/model/dto/GastoDTO.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
package com.santander.model.dto;

public class GastoDTO {
private String categoria;

public GastoDTO(String categoria) {
this.setCategoria(categoria);
}

public String getCategoria() {
return categoria;
}

public void setCategoria(String categoria) {
this.categoria = categoria;
}

}
Loading