diff --git a/.attach_pid4179 b/.attach_pid4179 new file mode 100644 index 00000000..e69de29b diff --git a/.gitignore b/.gitignore new file mode 100644 index 00000000..a2a3040a --- /dev/null +++ b/.gitignore @@ -0,0 +1,31 @@ +HELP.md +target/ +!.mvn/wrapper/maven-wrapper.jar +!**/src/main/** +!**/src/test/** + +### STS ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans +.sts4-cache + +### IntelliJ IDEA ### +.idea +*.iws +*.iml +*.ipr + +### NetBeans ### +/nbproject/private/ +/nbbuild/ +/dist/ +/nbdist/ +/.nb-gradle/ +build/ + +### VS Code ### +.vscode/ diff --git a/.mvn/wrapper/MavenWrapperDownloader.java b/.mvn/wrapper/MavenWrapperDownloader.java new file mode 100644 index 00000000..72308aa4 --- /dev/null +++ b/.mvn/wrapper/MavenWrapperDownloader.java @@ -0,0 +1,114 @@ +/* +Licensed to the Apache Software Foundation (ASF) under one +or more contributor license agreements. See the NOTICE file +distributed with this work for additional information +regarding copyright ownership. The ASF licenses this file +to you under the Apache License, Version 2.0 (the +"License"); you may not use this file except in compliance +with the License. You may obtain a copy of the License at + + https://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, +software distributed under the License is distributed on an +"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +KIND, either express or implied. See the License for the +specific language governing permissions and limitations +under the License. +*/ + +import java.io.File; +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.io.IOException; +import java.net.URL; +import java.nio.channels.Channels; +import java.nio.channels.ReadableByteChannel; +import java.util.Properties; + +public class MavenWrapperDownloader { + + /** + * Default URL to download the maven-wrapper.jar from, if no 'downloadUrl' is provided. + */ + private static final String DEFAULT_DOWNLOAD_URL = + "https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.4.2/maven-wrapper-0.4.2.jar"; + + /** + * Path to the maven-wrapper.properties file, which might contain a downloadUrl property to + * use instead of the default one. + */ + private static final String MAVEN_WRAPPER_PROPERTIES_PATH = + ".mvn/wrapper/maven-wrapper.properties"; + + /** + * Path where the maven-wrapper.jar will be saved to. + */ + private static final String MAVEN_WRAPPER_JAR_PATH = + ".mvn/wrapper/maven-wrapper.jar"; + + /** + * Name of the property which should be used to override the default download url for the wrapper. + */ + private static final String PROPERTY_NAME_WRAPPER_URL = "wrapperUrl"; + + public static void main(String args[]) { + System.out.println("- Downloader started"); + File baseDirectory = new File(args[0]); + System.out.println("- Using base directory: " + baseDirectory.getAbsolutePath()); + + // If the maven-wrapper.properties exists, read it and check if it contains a custom + // wrapperUrl parameter. + File mavenWrapperPropertyFile = new File(baseDirectory, MAVEN_WRAPPER_PROPERTIES_PATH); + String url = DEFAULT_DOWNLOAD_URL; + if(mavenWrapperPropertyFile.exists()) { + FileInputStream mavenWrapperPropertyFileInputStream = null; + try { + mavenWrapperPropertyFileInputStream = new FileInputStream(mavenWrapperPropertyFile); + Properties mavenWrapperProperties = new Properties(); + mavenWrapperProperties.load(mavenWrapperPropertyFileInputStream); + url = mavenWrapperProperties.getProperty(PROPERTY_NAME_WRAPPER_URL, url); + } catch (IOException e) { + System.out.println("- ERROR loading '" + MAVEN_WRAPPER_PROPERTIES_PATH + "'"); + } finally { + try { + if(mavenWrapperPropertyFileInputStream != null) { + mavenWrapperPropertyFileInputStream.close(); + } + } catch (IOException e) { + // Ignore ... + } + } + } + System.out.println("- Downloading from: : " + url); + + File outputFile = new File(baseDirectory.getAbsolutePath(), MAVEN_WRAPPER_JAR_PATH); + if(!outputFile.getParentFile().exists()) { + if(!outputFile.getParentFile().mkdirs()) { + System.out.println( + "- ERROR creating output direcrory '" + outputFile.getParentFile().getAbsolutePath() + "'"); + } + } + System.out.println("- Downloading to: " + outputFile.getAbsolutePath()); + try { + downloadFileFromURL(url, outputFile); + System.out.println("Done"); + System.exit(0); + } catch (Throwable e) { + System.out.println("- Error downloading"); + e.printStackTrace(); + System.exit(1); + } + } + + private static void downloadFileFromURL(String urlString, File destination) throws Exception { + URL website = new URL(urlString); + ReadableByteChannel rbc; + rbc = Channels.newChannel(website.openStream()); + FileOutputStream fos = new FileOutputStream(destination); + fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE); + fos.close(); + rbc.close(); + } + +} diff --git a/.mvn/wrapper/maven-wrapper.jar b/.mvn/wrapper/maven-wrapper.jar new file mode 100644 index 00000000..01e67997 Binary files /dev/null and b/.mvn/wrapper/maven-wrapper.jar differ diff --git a/.mvn/wrapper/maven-wrapper.properties b/.mvn/wrapper/maven-wrapper.properties new file mode 100644 index 00000000..cd0d451c --- /dev/null +++ b/.mvn/wrapper/maven-wrapper.properties @@ -0,0 +1 @@ +distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.6.0/apache-maven-3.6.0-bin.zip diff --git a/README.md b/README.md index 15d8f685..8b2142a3 100644 --- a/README.md +++ b/README.md @@ -1,76 +1,39 @@ -# Show me the code +## IMPORTANTE +Devido a falta de inteligência minha(Mais conhecida como burrice) acabei fazendo o projeto sem fazer o Fork com o repositório do teste. Então estou publicando apenas o resultado final do teste. Para visualizar todo o histórico de commits por favor acesse o repositório https://github.com/ValdeciJunior/santander +Desculpe-me a burrice. -### # DESAFIO: +### PROJETO PARA SELEÇÃO SANTANDER -API REST para Gestão de Gastos! +#### Antes de executar o projeto você precisa: +1. Ter um banco de dados postgres sendo executado localmente na porta 5432(Pode ser via docker) -``` -Funcionalidade: Integração de gastos por cartão - Apenas sistemas credenciados poderão incluir novos gastos - É esperado um volume de 100.000 inclusões por segundo - Os gastos, serão informados atraves do protoloco JSON, seguindo padrão: - { "descricao": "alfanumerico", "valor": double americano, "codigousuario": numerico, "data": Data dem formato UTC } -``` -``` -Funcionalidade: Listagem de gastos* - Dado que acesso como um cliente autenticado que pode visualizar os gastos do cartão - Quando acesso a interface de listagem de gastos - Então gostaria de ver meus gastos mais atuais. - -*Para esta funcionalidade é esperado 2.000 acessos por segundo. -*O cliente espera ver gastos realizados a 5 segundos atrás. -``` -``` -Funcionalidade: Filtro de gastos - Dado que acesso como um cliente autenticado - E acessei a interface de listagem de gastos - E configure o filtro de data igual a 27/03/1992 - Então gostaria de ver meus gastos apenas deste dia. -``` -``` -Funcionalidade: Categorização de gastos - Dado que acesso como um cliente autenticado - Quando acesso o detalhe de um gasto - E este não possui uma categoria - Então devo conseguir incluir uma categoria para este -``` -``` -Funcionalidade: Sugestão de categoria - Dado que acesso como um cliente autenticado - Quando acesso o detalhe do gasto que não possui categoria - E começo a digitar a categoria que desejo - Então uma lista de sugestões de categoria deve ser exibida, estas baseadas em categorias já informadas por outro usuários. -``` -``` -Funcionalidade: Categorização automatica de gasto - No processo de integração de gastos, a categoria deve ser incluida automaticamente - caso a descrição de um gasto seja igual a descrição de qualquer outro gasto já categorizado pelo cliente - o mesmo deve receber esta categoria no momento da inclusão do mesmo -``` -### # Avaliação +#### Url para autenticar o usuário e receber o token: +http://localhost:8081/login -Você será avaliado pela usabilidade, por respeitar o design e pela arquitetura da API. -É esperado que você consiga explicar as decisões que tomou durante o desenvolvimento através de commits. +#### Json para autenticar +{ + "username": "email@email.com", + "password": "123" +} +OU +{ + "username": "dev@email.com", + "password": "123" +} -* Springboot - Java - Maven (preferêncialmente) ([https://projects.spring.io/spring-boot/](https://projects.spring.io/spring-boot/)) -* RESTFul ([https://blog.mwaysolutions.com/2014/06/05/10-best-practices-for-better-restful-api/](https://blog.mwaysolutions.com/2014/06/05/10-best-practices-for-better-restful-api/)) -* DDD ([https://airbrake.io/blog/software-design/domain-driven-design](https://airbrake.io/blog/software-design/domain-driven-design)) -* Microservices ([https://martinfowler.com/microservices/](https://martinfowler.com/microservices/)) -* Testes unitários, teste o que achar importante (De preferência JUnit + Mockito). Mas pode usar o que você tem mais experiência, só nos explique o que ele tem de bom. -* SOAPUI para testes de carga ([https://www.soapui.org/load-testing/concept.html](https://www.soapui.org/load-testing/concept.html)) -* Uso de diferentes formas de armazenamento de dados (REDIS, Cassandra, Solr/Lucene) -* Uso do git -* Diferencial: Criptografia de comunicação, com troca de chaves. ([http://noiseprotocol.org/](http://noiseprotocol.org/)) -* Diferencial: CQRS ([https://martinfowler.com/bliki/CQRS.html](https://martinfowler.com/bliki/CQRS.html)) -* Diferencial: Docker File + Docker Compose (com dbs) para rodar seus jars. +#### Comando para executar o projeto: +mvn spring-boot:run -### # Observações gerais +#### Utilize o token recebido no Authorization das requisições para poder realiza-las. -Adicione um arquivo [README.md](http://README.md) com os procedimentos para executar o projeto. -Pedimos que trabalhe sozinho e não divulgue o resultado na internet. +#### ENDPOINTS: -Faça um fork desse desse repositório em seu Github e nos envie um Pull Request com o resultado, por favor informe por qual empresa você esta se candidatando. +1. POST http://localhost:8081/gastos {"valor": 0.00, "descricao":"Descrição do gasto", "data":"01/01/2019 00:00"} obs: Data é opcional, caso ela não seja informada automanticamente será setada a data atual +2. GET http://localhost:8081/gastos +3. GET http://localhost:8081/gastos/{uuid} +4. GET http://localhost:8081/gastos/por-data?data=01/01/2019 +5. GET http://localhost:8081/gastos/alterar-categoria/{uuid}?categoria=categoria do gasto +6. GET http://localhost:8081/gastos/pesquisar-categoria/{categoria} -### # Importante: não há prazo de entrega, faça com qualidade! - -# BOA SORTE! +##### Obs: O projeto tem testes unitários e migration para poder auxiliar nas execuções dos métodos +##### Obs2: O não é necessário passar o codigousuario em nenhuma requisição, ele já é recuperado automaticamente no back-end através das informações advindas do token. diff --git a/mvnw b/mvnw new file mode 100755 index 00000000..8b9da3b8 --- /dev/null +++ b/mvnw @@ -0,0 +1,286 @@ +#!/bin/sh +# ---------------------------------------------------------------------------- +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. +# ---------------------------------------------------------------------------- + +# ---------------------------------------------------------------------------- +# Maven2 Start Up Batch script +# +# Required ENV vars: +# ------------------ +# JAVA_HOME - location of a JDK home dir +# +# Optional ENV vars +# ----------------- +# M2_HOME - location of maven2's installed home dir +# MAVEN_OPTS - parameters passed to the Java VM when running Maven +# e.g. to debug Maven itself, use +# set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 +# MAVEN_SKIP_RC - flag to disable loading of mavenrc files +# ---------------------------------------------------------------------------- + +if [ -z "$MAVEN_SKIP_RC" ] ; then + + if [ -f /etc/mavenrc ] ; then + . /etc/mavenrc + fi + + if [ -f "$HOME/.mavenrc" ] ; then + . "$HOME/.mavenrc" + fi + +fi + +# OS specific support. $var _must_ be set to either true or false. +cygwin=false; +darwin=false; +mingw=false +case "`uname`" in + CYGWIN*) cygwin=true ;; + MINGW*) mingw=true;; + Darwin*) darwin=true + # Use /usr/libexec/java_home if available, otherwise fall back to /Library/Java/Home + # See https://developer.apple.com/library/mac/qa/qa1170/_index.html + if [ -z "$JAVA_HOME" ]; then + if [ -x "/usr/libexec/java_home" ]; then + export JAVA_HOME="`/usr/libexec/java_home`" + else + export JAVA_HOME="/Library/Java/Home" + fi + fi + ;; +esac + +if [ -z "$JAVA_HOME" ] ; then + if [ -r /etc/gentoo-release ] ; then + JAVA_HOME=`java-config --jre-home` + fi +fi + +if [ -z "$M2_HOME" ] ; then + ## resolve links - $0 may be a link to maven's home + PRG="$0" + + # need this for relative symlinks + while [ -h "$PRG" ] ; do + ls=`ls -ld "$PRG"` + link=`expr "$ls" : '.*-> \(.*\)$'` + if expr "$link" : '/.*' > /dev/null; then + PRG="$link" + else + PRG="`dirname "$PRG"`/$link" + fi + done + + saveddir=`pwd` + + M2_HOME=`dirname "$PRG"`/.. + + # make it fully qualified + M2_HOME=`cd "$M2_HOME" && pwd` + + cd "$saveddir" + # echo Using m2 at $M2_HOME +fi + +# For Cygwin, ensure paths are in UNIX format before anything is touched +if $cygwin ; then + [ -n "$M2_HOME" ] && + M2_HOME=`cygpath --unix "$M2_HOME"` + [ -n "$JAVA_HOME" ] && + JAVA_HOME=`cygpath --unix "$JAVA_HOME"` + [ -n "$CLASSPATH" ] && + CLASSPATH=`cygpath --path --unix "$CLASSPATH"` +fi + +# For Mingw, ensure paths are in UNIX format before anything is touched +if $mingw ; then + [ -n "$M2_HOME" ] && + M2_HOME="`(cd "$M2_HOME"; pwd)`" + [ -n "$JAVA_HOME" ] && + JAVA_HOME="`(cd "$JAVA_HOME"; pwd)`" + # TODO classpath? +fi + +if [ -z "$JAVA_HOME" ]; then + javaExecutable="`which javac`" + if [ -n "$javaExecutable" ] && ! [ "`expr \"$javaExecutable\" : '\([^ ]*\)'`" = "no" ]; then + # readlink(1) is not available as standard on Solaris 10. + readLink=`which readlink` + if [ ! `expr "$readLink" : '\([^ ]*\)'` = "no" ]; then + if $darwin ; then + javaHome="`dirname \"$javaExecutable\"`" + javaExecutable="`cd \"$javaHome\" && pwd -P`/javac" + else + javaExecutable="`readlink -f \"$javaExecutable\"`" + fi + javaHome="`dirname \"$javaExecutable\"`" + javaHome=`expr "$javaHome" : '\(.*\)/bin'` + JAVA_HOME="$javaHome" + export JAVA_HOME + fi + fi +fi + +if [ -z "$JAVACMD" ] ; then + if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD="$JAVA_HOME/jre/sh/java" + else + JAVACMD="$JAVA_HOME/bin/java" + fi + else + JAVACMD="`which java`" + fi +fi + +if [ ! -x "$JAVACMD" ] ; then + echo "Error: JAVA_HOME is not defined correctly." >&2 + echo " We cannot execute $JAVACMD" >&2 + exit 1 +fi + +if [ -z "$JAVA_HOME" ] ; then + echo "Warning: JAVA_HOME environment variable is not set." +fi + +CLASSWORLDS_LAUNCHER=org.codehaus.plexus.classworlds.launcher.Launcher + +# traverses directory structure from process work directory to filesystem root +# first directory with .mvn subdirectory is considered project base directory +find_maven_basedir() { + + if [ -z "$1" ] + then + echo "Path not specified to find_maven_basedir" + return 1 + fi + + basedir="$1" + wdir="$1" + while [ "$wdir" != '/' ] ; do + if [ -d "$wdir"/.mvn ] ; then + basedir=$wdir + break + fi + # workaround for JBEAP-8937 (on Solaris 10/Sparc) + if [ -d "${wdir}" ]; then + wdir=`cd "$wdir/.."; pwd` + fi + # end of workaround + done + echo "${basedir}" +} + +# concatenates all lines of a file +concat_lines() { + if [ -f "$1" ]; then + echo "$(tr -s '\n' ' ' < "$1")" + fi +} + +BASE_DIR=`find_maven_basedir "$(pwd)"` +if [ -z "$BASE_DIR" ]; then + exit 1; +fi + +########################################################################################## +# Extension to allow automatically downloading the maven-wrapper.jar from Maven-central +# This allows using the maven wrapper in projects that prohibit checking in binary data. +########################################################################################## +if [ -r "$BASE_DIR/.mvn/wrapper/maven-wrapper.jar" ]; then + if [ "$MVNW_VERBOSE" = true ]; then + echo "Found .mvn/wrapper/maven-wrapper.jar" + fi +else + if [ "$MVNW_VERBOSE" = true ]; then + echo "Couldn't find .mvn/wrapper/maven-wrapper.jar, downloading it ..." + fi + jarUrl="https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.4.2/maven-wrapper-0.4.2.jar" + while IFS="=" read key value; do + case "$key" in (wrapperUrl) jarUrl="$value"; break ;; + esac + done < "$BASE_DIR/.mvn/wrapper/maven-wrapper.properties" + if [ "$MVNW_VERBOSE" = true ]; then + echo "Downloading from: $jarUrl" + fi + wrapperJarPath="$BASE_DIR/.mvn/wrapper/maven-wrapper.jar" + + if command -v wget > /dev/null; then + if [ "$MVNW_VERBOSE" = true ]; then + echo "Found wget ... using wget" + fi + wget "$jarUrl" -O "$wrapperJarPath" + elif command -v curl > /dev/null; then + if [ "$MVNW_VERBOSE" = true ]; then + echo "Found curl ... using curl" + fi + curl -o "$wrapperJarPath" "$jarUrl" + else + if [ "$MVNW_VERBOSE" = true ]; then + echo "Falling back to using Java to download" + fi + javaClass="$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.java" + if [ -e "$javaClass" ]; then + if [ ! -e "$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" ]; then + if [ "$MVNW_VERBOSE" = true ]; then + echo " - Compiling MavenWrapperDownloader.java ..." + fi + # Compiling the Java class + ("$JAVA_HOME/bin/javac" "$javaClass") + fi + if [ -e "$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" ]; then + # Running the downloader + if [ "$MVNW_VERBOSE" = true ]; then + echo " - Running MavenWrapperDownloader.java ..." + fi + ("$JAVA_HOME/bin/java" -cp .mvn/wrapper MavenWrapperDownloader "$MAVEN_PROJECTBASEDIR") + fi + fi + fi +fi +########################################################################################## +# End of extension +########################################################################################## + +export MAVEN_PROJECTBASEDIR=${MAVEN_BASEDIR:-"$BASE_DIR"} +if [ "$MVNW_VERBOSE" = true ]; then + echo $MAVEN_PROJECTBASEDIR +fi +MAVEN_OPTS="$(concat_lines "$MAVEN_PROJECTBASEDIR/.mvn/jvm.config") $MAVEN_OPTS" + +# For Cygwin, switch paths to Windows format before running java +if $cygwin; then + [ -n "$M2_HOME" ] && + M2_HOME=`cygpath --path --windows "$M2_HOME"` + [ -n "$JAVA_HOME" ] && + JAVA_HOME=`cygpath --path --windows "$JAVA_HOME"` + [ -n "$CLASSPATH" ] && + CLASSPATH=`cygpath --path --windows "$CLASSPATH"` + [ -n "$MAVEN_PROJECTBASEDIR" ] && + MAVEN_PROJECTBASEDIR=`cygpath --path --windows "$MAVEN_PROJECTBASEDIR"` +fi + +WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain + +exec "$JAVACMD" \ + $MAVEN_OPTS \ + -classpath "$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.jar" \ + "-Dmaven.home=${M2_HOME}" "-Dmaven.multiModuleProjectDirectory=${MAVEN_PROJECTBASEDIR}" \ + ${WRAPPER_LAUNCHER} $MAVEN_CONFIG "$@" diff --git a/mvnw.cmd b/mvnw.cmd new file mode 100644 index 00000000..fef5a8f7 --- /dev/null +++ b/mvnw.cmd @@ -0,0 +1,161 @@ +@REM ---------------------------------------------------------------------------- +@REM Licensed to the Apache Software Foundation (ASF) under one +@REM or more contributor license agreements. See the NOTICE file +@REM distributed with this work for additional information +@REM regarding copyright ownership. The ASF licenses this file +@REM to you under the Apache License, Version 2.0 (the +@REM "License"); you may not use this file except in compliance +@REM with the License. You may obtain a copy of the License at +@REM +@REM https://www.apache.org/licenses/LICENSE-2.0 +@REM +@REM Unless required by applicable law or agreed to in writing, +@REM software distributed under the License is distributed on an +@REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +@REM KIND, either express or implied. See the License for the +@REM specific language governing permissions and limitations +@REM under the License. +@REM ---------------------------------------------------------------------------- + +@REM ---------------------------------------------------------------------------- +@REM Maven2 Start Up Batch script +@REM +@REM Required ENV vars: +@REM JAVA_HOME - location of a JDK home dir +@REM +@REM Optional ENV vars +@REM M2_HOME - location of maven2's installed home dir +@REM MAVEN_BATCH_ECHO - set to 'on' to enable the echoing of the batch commands +@REM MAVEN_BATCH_PAUSE - set to 'on' to wait for a key stroke before ending +@REM MAVEN_OPTS - parameters passed to the Java VM when running Maven +@REM e.g. to debug Maven itself, use +@REM set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 +@REM MAVEN_SKIP_RC - flag to disable loading of mavenrc files +@REM ---------------------------------------------------------------------------- + +@REM Begin all REM lines with '@' in case MAVEN_BATCH_ECHO is 'on' +@echo off +@REM set title of command window +title %0 +@REM enable echoing my setting MAVEN_BATCH_ECHO to 'on' +@if "%MAVEN_BATCH_ECHO%" == "on" echo %MAVEN_BATCH_ECHO% + +@REM set %HOME% to equivalent of $HOME +if "%HOME%" == "" (set "HOME=%HOMEDRIVE%%HOMEPATH%") + +@REM Execute a user defined script before this one +if not "%MAVEN_SKIP_RC%" == "" goto skipRcPre +@REM check for pre script, once with legacy .bat ending and once with .cmd ending +if exist "%HOME%\mavenrc_pre.bat" call "%HOME%\mavenrc_pre.bat" +if exist "%HOME%\mavenrc_pre.cmd" call "%HOME%\mavenrc_pre.cmd" +:skipRcPre + +@setlocal + +set ERROR_CODE=0 + +@REM To isolate internal variables from possible post scripts, we use another setlocal +@setlocal + +@REM ==== START VALIDATION ==== +if not "%JAVA_HOME%" == "" goto OkJHome + +echo. +echo Error: JAVA_HOME not found in your environment. >&2 +echo Please set the JAVA_HOME variable in your environment to match the >&2 +echo location of your Java installation. >&2 +echo. +goto error + +:OkJHome +if exist "%JAVA_HOME%\bin\java.exe" goto init + +echo. +echo Error: JAVA_HOME is set to an invalid directory. >&2 +echo JAVA_HOME = "%JAVA_HOME%" >&2 +echo Please set the JAVA_HOME variable in your environment to match the >&2 +echo location of your Java installation. >&2 +echo. +goto error + +@REM ==== END VALIDATION ==== + +:init + +@REM Find the project base dir, i.e. the directory that contains the folder ".mvn". +@REM Fallback to current working directory if not found. + +set MAVEN_PROJECTBASEDIR=%MAVEN_BASEDIR% +IF NOT "%MAVEN_PROJECTBASEDIR%"=="" goto endDetectBaseDir + +set EXEC_DIR=%CD% +set WDIR=%EXEC_DIR% +:findBaseDir +IF EXIST "%WDIR%"\.mvn goto baseDirFound +cd .. +IF "%WDIR%"=="%CD%" goto baseDirNotFound +set WDIR=%CD% +goto findBaseDir + +:baseDirFound +set MAVEN_PROJECTBASEDIR=%WDIR% +cd "%EXEC_DIR%" +goto endDetectBaseDir + +:baseDirNotFound +set MAVEN_PROJECTBASEDIR=%EXEC_DIR% +cd "%EXEC_DIR%" + +:endDetectBaseDir + +IF NOT EXIST "%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config" goto endReadAdditionalConfig + +@setlocal EnableExtensions EnableDelayedExpansion +for /F "usebackq delims=" %%a in ("%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config") do set JVM_CONFIG_MAVEN_PROPS=!JVM_CONFIG_MAVEN_PROPS! %%a +@endlocal & set JVM_CONFIG_MAVEN_PROPS=%JVM_CONFIG_MAVEN_PROPS% + +:endReadAdditionalConfig + +SET MAVEN_JAVA_EXE="%JAVA_HOME%\bin\java.exe" +set WRAPPER_JAR="%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.jar" +set WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain + +set DOWNLOAD_URL="https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.4.2/maven-wrapper-0.4.2.jar" +FOR /F "tokens=1,2 delims==" %%A IN (%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.properties) DO ( + IF "%%A"=="wrapperUrl" SET DOWNLOAD_URL=%%B +) + +@REM Extension to allow automatically downloading the maven-wrapper.jar from Maven-central +@REM This allows using the maven wrapper in projects that prohibit checking in binary data. +if exist %WRAPPER_JAR% ( + echo Found %WRAPPER_JAR% +) else ( + echo Couldn't find %WRAPPER_JAR%, downloading it ... + echo Downloading from: %DOWNLOAD_URL% + powershell -Command "(New-Object Net.WebClient).DownloadFile('%DOWNLOAD_URL%', '%WRAPPER_JAR%')" + echo Finished downloading %WRAPPER_JAR% +) +@REM End of extension + +%MAVEN_JAVA_EXE% %JVM_CONFIG_MAVEN_PROPS% %MAVEN_OPTS% %MAVEN_DEBUG_OPTS% -classpath %WRAPPER_JAR% "-Dmaven.multiModuleProjectDirectory=%MAVEN_PROJECTBASEDIR%" %WRAPPER_LAUNCHER% %MAVEN_CONFIG% %* +if ERRORLEVEL 1 goto error +goto end + +:error +set ERROR_CODE=1 + +:end +@endlocal & set ERROR_CODE=%ERROR_CODE% + +if not "%MAVEN_SKIP_RC%" == "" goto skipRcPost +@REM check for post script, once with legacy .bat ending and once with .cmd ending +if exist "%HOME%\mavenrc_post.bat" call "%HOME%\mavenrc_post.bat" +if exist "%HOME%\mavenrc_post.cmd" call "%HOME%\mavenrc_post.cmd" +:skipRcPost + +@REM pause the script if MAVEN_BATCH_PAUSE is set to 'on' +if "%MAVEN_BATCH_PAUSE%" == "on" pause + +if "%MAVEN_TERMINATE_CMD%" == "on" exit %ERROR_CODE% + +exit /B %ERROR_CODE% diff --git a/pom.xml b/pom.xml new file mode 100644 index 00000000..9ea3f721 --- /dev/null +++ b/pom.xml @@ -0,0 +1,126 @@ + + + 4.0.0 + + br.com.santander + santander + 0.0.1-SNAPSHOT + jar + + santander + Sistema de gerenciamento de gastos + + + org.springframework.boot + spring-boot-starter-parent + 2.0.3.RELEASE + + + + + UTF-8 + UTF-8 + 1.8 + + + + + + org.springframework.boot + spring-boot-starter + + + org.springframework.boot + spring-boot-devtools + runtime + + + org.springframework.boot + spring-boot-starter-test + test + + + + org.flywaydb + flyway-core + 5.2.4 + + + + com.h2database + h2 + runtime + + + + io.jsonwebtoken + jjwt + 0.7.0 + + + + org.springframework.boot + spring-boot-starter-tomcat + provided + + + org.springframework.boot + spring-boot-starter-web + + + + org.springframework.boot + spring-boot-starter-data-jpa + + + + + org.springframework.boot + spring-boot-starter-security + + + + org.springframework.security + spring-security-test + + + + + org.postgresql + postgresql + 42.2.4 + + + + com.h2database + h2 + + + + + com.inversoft + prime-jwt + 1.3.1 + + + + + joda-time + joda-time + + + + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + + \ No newline at end of file diff --git a/src/main/java/META-INF/additional-spring-configuration-metadata.json b/src/main/java/META-INF/additional-spring-configuration-metadata.json new file mode 100644 index 00000000..f09e3bc9 --- /dev/null +++ b/src/main/java/META-INF/additional-spring-configuration-metadata.json @@ -0,0 +1 @@ +{"properties": []} \ No newline at end of file diff --git a/src/main/java/br/com/santander/SantanderApplication.java b/src/main/java/br/com/santander/SantanderApplication.java new file mode 100644 index 00000000..29781e5f --- /dev/null +++ b/src/main/java/br/com/santander/SantanderApplication.java @@ -0,0 +1,13 @@ +package br.com.santander; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class SantanderApplication { + + public static void main(String[] args) { + SpringApplication.run(SantanderApplication.class, args); + } + +} diff --git a/src/main/java/br/com/santander/config/WebSecurityConfig.java b/src/main/java/br/com/santander/config/WebSecurityConfig.java new file mode 100644 index 00000000..9a12dc5b --- /dev/null +++ b/src/main/java/br/com/santander/config/WebSecurityConfig.java @@ -0,0 +1,62 @@ +package br.com.santander.config; + +import java.util.Arrays; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Bean; +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.annotation.web.configuration.WebSecurityConfigurerAdapter; +import org.springframework.security.config.http.SessionCreationPolicy; +import org.springframework.security.core.userdetails.UserDetailsService; +import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; +import org.springframework.web.cors.CorsConfiguration; +import org.springframework.web.cors.CorsConfigurationSource; +import org.springframework.web.cors.UrlBasedCorsConfigurationSource; +import org.springframework.core.env.Environment; +import org.springframework.http.HttpMethod; + +import br.com.santander.security.JWTAuthenticationFilter; +import br.com.santander.security.JWTAuthorizationFilter; +import br.com.santander.security.JWTUtil; + +@Configuration +@EnableWebSecurity +public class WebSecurityConfig extends WebSecurityConfigurerAdapter { + + @Autowired + private UserDetailsService userDetailsService; + + @Autowired + private JWTUtil jwtUtil; + + + @Override + protected void configure(HttpSecurity http) throws Exception { + http.cors().and().csrf().disable(); + http. + authorizeRequests() + .anyRequest().authenticated().and().formLogin(); + http.addFilter(new JWTAuthenticationFilter(authenticationManager(), jwtUtil)); + http.addFilter(new JWTAuthorizationFilter(authenticationManager(), jwtUtil, userDetailsService)); + } + + @Override + public void configure(AuthenticationManagerBuilder auth) throws Exception { + auth.userDetailsService(userDetailsService).passwordEncoder(bCryptPasswordEncoder()); + } + + @Bean + CorsConfigurationSource corsConfigurationSource() { + final UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); + source.registerCorsConfiguration("/**", new CorsConfiguration().applyPermitDefaultValues()); + return source; + } + + @Bean + public BCryptPasswordEncoder bCryptPasswordEncoder() { + return new BCryptPasswordEncoder(); + } +} diff --git a/src/main/java/br/com/santander/controllers/GastoController.java b/src/main/java/br/com/santander/controllers/GastoController.java new file mode 100644 index 00000000..cda757ad --- /dev/null +++ b/src/main/java/br/com/santander/controllers/GastoController.java @@ -0,0 +1,131 @@ +package br.com.santander.controllers; + +import java.util.Date; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import javax.validation.constraints.NotBlank; +import javax.validation.constraints.NotNull; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.PutMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.RestController; + +import br.com.santander.dtos.GastoDTO; +import br.com.santander.entities.Gasto; +import br.com.santander.services.GastoService; +import br.com.santander.services.UserDetailsServiceImpl; + +@RestController +@RequestMapping("/gastos") +public class GastoController { + + //Dependência onde tem o método que trás o código do usuário corrente + @Autowired + private UserDetailsServiceImpl userDetails; + + @Autowired + private GastoService gastoService; + + /** + * Método responsável por cadastrar um gasto. Recebe um DTO de gasto pelo corpo da requisição e o código do usuário corrente + * @author valdeci + * @param gasto + * @return GastoDTO + */ + @PostMapping + public GastoDTO cadastrar(@RequestBody GastoDTO gasto) { + return gastoService.cadastrar(gasto, userDetails.get().getCodigoUsuario()); + } + + /** + * Responsável por recuperar um gasto pelo uuid dele. Recebe o uuid pela url e o código do usuário corrente + * @author valdeci + * @param uuid + * @return GastoDTO + */ + @GetMapping("/{uuid}") + public GastoDTO get(@NotBlank(message = "Uuid de gasto não pode ser nulo") @PathVariable("uuid") String uuid) { + return gastoService.getDTO(uuid, userDetails.get().getCodigoUsuario()); + } + + /** + * Responsável por listar todos os gastos do usuário. Recebe apenas o código do usuário corrente + * @author valdeci + * @return List + */ + @GetMapping + public List gastos(){ + return gastoService.listar(userDetails.get().getCodigoUsuario()); + } + + /** + * Responsável por listar os gastos de uma data em específico. + * Recebe uma data no padrão brasilero(dd/MM/yyyy) pelo request params e o código do usuário corrente + * @author valdeci + * @param data(padrão BR) + * @return + */ + @GetMapping("/por-data") + public List gastosPorData(@NotNull(message = "Data não pode ser nula") @RequestParam("data") String data){ + return gastoService.listarPorData(data, userDetails.get().getCodigoUsuario()); + } + + /** + * Responsável por alterar uma categoria de um gasto em específico. Recebe o uuid de um gasto pela url, + * recebe a nova categora pelo request params e recebe o código do usuário corrente. + * @author valdeci + * @param categoria + * @param uuid + * @return GastoDTO + */ + @PutMapping("/altera-categoria/{uuid}") + public GastoDTO alterarCategoria(@NotBlank(message = "Categoria não pode ser nula ou ficar em branco") @RequestParam("categoria") String categoria, + @NotBlank(message = "Uuid não pode ser nulo ou ficar em branco") @PathVariable("uuid") String uuid) { + return gastoService.alterarCategoria(categoria, uuid, userDetails.get().getCodigoUsuario()); + } + + /** + * Responsável por pesquisar as categorias de a cordo com o que o usuário pessar nos parâmetros. + * Recebe os carácteres da categorias que o usuário quer pesqusar e recebe o código do usuário corrente + * @author valdeci + * @param categoria + * @return List + */ + @GetMapping("/pesquisar-categoria/{categoria}") + public List pesquisarCategorias(@NotNull(message = "Categoria não pode ser nula") @PathVariable("categoria")String categoria){ + return gastoService.pesquisarCategorias(categoria, userDetails.get().getCodigoUsuario()); + } + + +} + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/main/java/br/com/santander/dtos/Credenciais.java b/src/main/java/br/com/santander/dtos/Credenciais.java new file mode 100644 index 00000000..5d2a7619 --- /dev/null +++ b/src/main/java/br/com/santander/dtos/Credenciais.java @@ -0,0 +1,26 @@ +package br.com.santander.dtos; + +import java.io.Serializable; + +public class Credenciais implements Serializable { + private static final long serialVersionUID = 1L; + + + private String username; + private String password; + + public String getUsername() { + return username; + } + public void setUsername(String username) { + this.username = username; + } + public String getPassword() { + return password; + } + public void setPassword(String password) { + this.password = password; + } + + +} diff --git a/src/main/java/br/com/santander/dtos/GastoDTO.java b/src/main/java/br/com/santander/dtos/GastoDTO.java new file mode 100644 index 00000000..0a66eb2c --- /dev/null +++ b/src/main/java/br/com/santander/dtos/GastoDTO.java @@ -0,0 +1,60 @@ +package br.com.santander.dtos; + +import java.io.Serializable; +import java.math.BigDecimal; +import java.util.Date; + +import javax.validation.constraints.NotBlank; +import javax.validation.constraints.NotNull; + +import com.fasterxml.jackson.annotation.JsonFormat; + +public class GastoDTO implements Serializable{ + private static final long serialVersionUID = 1L; + + private String uuid; + + @NotBlank(message = "Descrição de gasto não pode ser vazio ou nulo") + private String descricao; + + @NotNull(message = "Valor de gasto não pode ser nulo") + private BigDecimal valor; + + @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "dd/MM/yyyy HH:mm", locale = "pt-BR", timezone = "Brazil/East") + private Date data; + + public String getUuid() { + return uuid; + } + + public void setUuid(String uuid) { + this.uuid = uuid; + } + + 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 Date getData() { + return data; + } + + public void setData(Date data) { + this.data = data; + } + + + +} diff --git a/src/main/java/br/com/santander/entities/Gasto.java b/src/main/java/br/com/santander/entities/Gasto.java new file mode 100644 index 00000000..6763ae5d --- /dev/null +++ b/src/main/java/br/com/santander/entities/Gasto.java @@ -0,0 +1,116 @@ +package br.com.santander.entities; + +import java.math.BigDecimal; +import java.util.Date; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.Id; +import javax.persistence.Table; +import javax.persistence.Temporal; +import javax.persistence.TemporalType; + +import org.hibernate.annotations.GenericGenerator; + +@Entity +@Table(name="gastos") +public class Gasto { + + @Id + @GeneratedValue(generator = "UUID") + @GenericGenerator(name = "UUID", strategy = "org.hibernate.id.UUIDGenerator") + @Column(name = "id", nullable = false, unique = true) + private String uuid; + + @Column(name = "descricao") + private String descricao; + + @Column(name = "categoria") + private String categoria; + + @Column(name="valor", columnDefinition="Decimal(10,2) default '0.00'") + private BigDecimal valor; + + @Column(name = "codigo_usuario") + private Integer codigousuario; + + @Column(name = "data") + @Temporal(TemporalType.TIMESTAMP) + private Date data; + + public String getUuid() { + return uuid; + } + + public void setUuid(String uuid) { + this.uuid = uuid; + } + + 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 Integer getCodigousuario() { + return codigousuario; + } + + public void setCodigousuario(Integer codigousuario) { + this.codigousuario = codigousuario; + } + + public Date getData() { + return data; + } + + public void setData(Date data) { + this.data = data; + } + + 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 + ((uuid == null) ? 0 : uuid.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 (uuid == null) { + if (other.uuid != null) + return false; + } else if (!uuid.equals(other.uuid)) + return false; + return true; + } + + +} diff --git a/src/main/java/br/com/santander/entities/Usuario.java b/src/main/java/br/com/santander/entities/Usuario.java new file mode 100644 index 00000000..6d2eeb1c --- /dev/null +++ b/src/main/java/br/com/santander/entities/Usuario.java @@ -0,0 +1,96 @@ +package br.com.santander.entities; + +import java.util.HashSet; +import java.util.Set; +import java.util.stream.Collectors; + +import javax.persistence.CollectionTable; +import javax.persistence.Column; +import javax.persistence.ElementCollection; +import javax.persistence.Entity; +import javax.persistence.FetchType; +import javax.persistence.GeneratedValue; +import javax.persistence.Id; +import javax.persistence.Table; + +import org.hibernate.annotations.GenericGenerator; + +import com.fasterxml.jackson.annotation.JsonIgnore; + +import br.com.santander.enums.Perfil; + +@Entity +@Table(name= "usuarios") +public class Usuario { + + @Id + @GeneratedValue(generator = "UUID") + @GenericGenerator(name = "UUID", strategy = "org.hibernate.id.UUIDGenerator") + @Column(name = "id", nullable = false, unique = true) + private String uuid; + + @GeneratedValue + @Column(name="codigo") + private Integer codigo; + + @Column(name="username", nullable = false) + private String username; + + @JsonIgnore + @Column(name="password", nullable = false) + private String password; + + @ElementCollection(fetch = FetchType.EAGER) + @CollectionTable(name="PERFIS") + private Set perfis = new HashSet<>(); + + public Usuario() { + addPerfil(Perfil.CLIENTE); + } + + public Set getPerfis(){ + return perfis.stream().map(x -> Perfil.toEnum(x)).collect(Collectors.toSet()); + } + + public void addPerfil(Perfil perfil) { + perfis.add(perfil.getCodigo()); + } + + public String getUuid() { + return uuid; + } + + public void setUuid(String uuid) { + this.uuid = uuid; + } + + public String getUsername() { + return username; + } + + public void setUsername(String username) { + this.username = username; + } + + public String getPassword() { + return password; + } + + public void setPassword(String password) { + this.password = password; + } + + public void setPerfis(Set perfis) { + this.perfis = perfis; + } + + public Integer getCodigo() { + return codigo; + } + + public void setCodigo(Integer codigo) { + this.codigo = codigo; + } + + +} diff --git a/src/main/java/br/com/santander/enums/Perfil.java b/src/main/java/br/com/santander/enums/Perfil.java new file mode 100644 index 00000000..93fcbedc --- /dev/null +++ b/src/main/java/br/com/santander/enums/Perfil.java @@ -0,0 +1,36 @@ +package br.com.santander.enums; + +public enum Perfil { + + ADMIN(1, "ROLE_ADMIN"), + CLIENTE(2, "ROLE_CLIENTE"); + + private Integer codigo; + + private String descricao; + + private Perfil(Integer codigo, String descricao) { + this.codigo = codigo; + this.descricao = descricao; + } + + public Integer getCodigo() { + return codigo; + } + + public String getDescricao() { + return descricao; + } + + public static Perfil toEnum(Integer codigo) { + if(codigo == null) { + return null; + } + for (Perfil x : Perfil.values()) { + if(codigo.equals(x.getCodigo())) { + return x; + } + } + throw new IllegalArgumentException("Código inválido " + codigo); + } +} diff --git a/src/main/java/br/com/santander/repositories/GastoRepository.java b/src/main/java/br/com/santander/repositories/GastoRepository.java new file mode 100644 index 00000000..42338418 --- /dev/null +++ b/src/main/java/br/com/santander/repositories/GastoRepository.java @@ -0,0 +1,28 @@ +package br.com.santander.repositories; + +import java.util.Date; +import java.util.List; +import java.util.Optional; + +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.data.jpa.repository.Query; +import org.springframework.stereotype.Repository; + +import br.com.santander.entities.Gasto; + +@Repository +public interface GastoRepository extends JpaRepository { + + List findAllByCodigousuario(Integer codigo); + + @Query("select g from Gasto as g where g.data between ?1 and ?2 and g.codigousuario = ?3") + List findAllByDataBetweenAndCodigousuario(Date dataInicio, Date dataFim, Integer codigo); + + Optional findByUuidAndCodigousuario(String uuid, Integer codigoUsuario); + + @Query("select g.categoria from Gasto as g where g.codigousuario = ?1 and g.categoria like ?2") + List findCategoraiasByCodigousuarioAndLikeCategoria(Integer codigousuario, String categoria); + + @Query("select g from Gasto as g where g.descricao like ?1 AND g.codigousuario = ?2") + List findAllByLikeDescricaoAndCodigousuario(String descricao, Integer codigoUsuario); +} diff --git a/src/main/java/br/com/santander/repositories/UsuarioRepository.java b/src/main/java/br/com/santander/repositories/UsuarioRepository.java new file mode 100644 index 00000000..81fe9d11 --- /dev/null +++ b/src/main/java/br/com/santander/repositories/UsuarioRepository.java @@ -0,0 +1,15 @@ +package br.com.santander.repositories; + +import java.util.Optional; + +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.stereotype.Repository; + +import br.com.santander.entities.Usuario; + +@Repository +public interface UsuarioRepository extends JpaRepository { + + Optional findByUsername(String username); + +} diff --git a/src/main/java/br/com/santander/security/JWTAuthenticationFilter.java b/src/main/java/br/com/santander/security/JWTAuthenticationFilter.java new file mode 100644 index 00000000..2887ae15 --- /dev/null +++ b/src/main/java/br/com/santander/security/JWTAuthenticationFilter.java @@ -0,0 +1,85 @@ +package br.com.santander.security; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.Date; + +import javax.servlet.FilterChain; +import javax.servlet.ServletException; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.springframework.security.authentication.AuthenticationManager; +import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; +import org.springframework.security.core.Authentication; +import org.springframework.security.core.AuthenticationException; +import org.springframework.security.web.authentication.AuthenticationFailureHandler; +import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter; + +import com.fasterxml.jackson.databind.ObjectMapper; + +import br.com.santander.dtos.Credenciais; + + +public class JWTAuthenticationFilter extends UsernamePasswordAuthenticationFilter { + + private AuthenticationManager authenticationManager; + + private JWTUtil jwtUtil; + + public JWTAuthenticationFilter(AuthenticationManager authenticationManager, JWTUtil jwtUtil) { + setAuthenticationFailureHandler(new JWTAuthenticationFailureHandler()); + this.authenticationManager = authenticationManager; + this.jwtUtil = jwtUtil; + } + + @Override + public Authentication attemptAuthentication(HttpServletRequest req, + HttpServletResponse res) throws AuthenticationException { + + try { + Credenciais creds = new ObjectMapper() + .readValue(req.getInputStream(), Credenciais.class); + + UsernamePasswordAuthenticationToken authToken = new UsernamePasswordAuthenticationToken(creds.getUsername(), creds.getPassword(), new ArrayList<>()); + + Authentication auth = authenticationManager.authenticate(authToken); + return auth; + } + catch (IOException e) { + throw new RuntimeException(e); + } + } + + @Override + protected void successfulAuthentication(HttpServletRequest req, + HttpServletResponse res, + FilterChain chain, + Authentication auth) throws IOException, ServletException { + + String username = ((UserSecurity) auth.getPrincipal()).getUsername(); + + String token = jwtUtil.generateToken(username); + res.addHeader("Authorization", "Bearer " + token); + } + + private class JWTAuthenticationFailureHandler implements AuthenticationFailureHandler { + + @Override + public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) + throws IOException, ServletException { + response.setStatus(401); + response.setContentType("application/json"); + response.getWriter().append(json()); + } + + private String json() { + long date = new Date().getTime(); + return "{\"timestamp\": " + date + ", " + + "\"status\": 401, " + + "\"error\": \"Não autorizado\", " + + "\"message\": \"Email ou senha inválidos\", " + + "\"path\": \"/login\"}"; + } + } +} \ No newline at end of file diff --git a/src/main/java/br/com/santander/security/JWTAuthorizationFilter.java b/src/main/java/br/com/santander/security/JWTAuthorizationFilter.java new file mode 100644 index 00000000..2adb12c1 --- /dev/null +++ b/src/main/java/br/com/santander/security/JWTAuthorizationFilter.java @@ -0,0 +1,81 @@ +package br.com.santander.security; + +import java.io.IOException; + +import javax.servlet.FilterChain; +import javax.servlet.ServletException; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import javax.xml.ws.http.HTTPException; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.security.authentication.AuthenticationManager; +import org.springframework.security.authentication.BadCredentialsException; +import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; +import org.springframework.security.core.context.SecurityContextHolder; +import org.springframework.security.core.userdetails.UserDetails; +import org.springframework.security.core.userdetails.UserDetailsService; +import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter; +import org.springframework.security.web.authentication.www.BasicAuthenticationFilter; + +public class JWTAuthorizationFilter extends BasicAuthenticationFilter { + + private static Logger logger = LoggerFactory.getLogger(JWTAuthorizationFilter.class); + + private JWTUtil jwtUtil; + + private UserDetailsService userDetailsService; + + public JWTAuthorizationFilter(AuthenticationManager authenticationManager, JWTUtil jwtUtil, UserDetailsService userDetailsService) { + super(authenticationManager); + this.jwtUtil = jwtUtil; + this.userDetailsService = userDetailsService; + // TODO Auto-generated constructor stub + } + + @Override + protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) + throws IOException, ServletException { + String header = request.getHeader("Authorization"); + if(header != null && header.startsWith("Bearer")) { + UsernamePasswordAuthenticationToken auth = getAuthentication(header.substring(7)); + if(auth != null) { + SecurityContextHolder.getContext().setAuthentication(auth); + chain.doFilter(request, response); + } + } +// throw new BadCredentialsException("Invalid token"); + + } + + private UsernamePasswordAuthenticationToken getAuthentication(String token) { + if(jwtUtil.tokenValido(token)) { + String username = jwtUtil.getUsername(token); + UserDetails user = userDetailsService.loadUserByUsername(username); + return new UsernamePasswordAuthenticationToken(user, null, user.getAuthorities()); + } + return null; + } + +} + + + + + + + + + + + + + + + + + + + + diff --git a/src/main/java/br/com/santander/security/JWTUtil.java b/src/main/java/br/com/santander/security/JWTUtil.java new file mode 100644 index 00000000..33b6cf91 --- /dev/null +++ b/src/main/java/br/com/santander/security/JWTUtil.java @@ -0,0 +1,58 @@ +package br.com.santander.security; + +import java.util.Date; + +import org.springframework.beans.factory.annotation.Value; +import org.springframework.stereotype.Component; + +import io.jsonwebtoken.Claims; +import io.jsonwebtoken.Jwts; +import io.jsonwebtoken.SignatureAlgorithm; + +@Component +public class JWTUtil { + @Value("${jwt.secret}") + private String secret; + + @Value("${jwt.expire}") + private long expire; + + public String generateToken(String username) { + System.out.println(secret); + return Jwts.builder() + .setSubject(username) + .setExpiration(new Date(System.currentTimeMillis() + expire)) + .signWith(SignatureAlgorithm.HS512, secret.getBytes()) + .compact(); + } + + public boolean tokenValido(String token) { + Claims claims = getClaims(token); + if (claims != null) { + String username = claims.getSubject(); + Date expirationDate = claims.getExpiration(); + Date now = new Date(System.currentTimeMillis()); + if(username != null && expirationDate != null && now.before(expirationDate)) { + return true; + } + } + return false; + } + + public String getUsername(String token) { + Claims claims = getClaims(token); + if (claims != null) { + return claims.getSubject(); + } + return null; + } + + private Claims getClaims(String token) { + try { + return Jwts.parser().setSigningKey(secret.getBytes()).parseClaimsJws(token).getBody(); + } + catch (Exception e) { + return null; + } + } +} diff --git a/src/main/java/br/com/santander/security/UserSecurity.java b/src/main/java/br/com/santander/security/UserSecurity.java new file mode 100644 index 00000000..6b4a70a7 --- /dev/null +++ b/src/main/java/br/com/santander/security/UserSecurity.java @@ -0,0 +1,88 @@ +package br.com.santander.security; + +import java.util.Collection; +import java.util.Set; +import java.util.stream.Collectors; + +import org.springframework.security.core.GrantedAuthority; +import org.springframework.security.core.authority.SimpleGrantedAuthority; +import org.springframework.security.core.userdetails.UserDetails; + +import br.com.santander.enums.Perfil; + +public class UserSecurity implements UserDetails { + private static final long serialVersionUID = 1L; + + private String uuid; + private String username; + private String password; + private Integer codigoUsuario; + private Collection authorities; + + public UserSecurity() { + } + + + + public UserSecurity(String uuid, String username, String password, Set perfis, Integer codigousuario) { + this.uuid = uuid; + this.username = username; + this.password = password; + this.codigoUsuario = codigousuario; + this.authorities = perfis.stream().map(x -> new SimpleGrantedAuthority(x.getDescricao())).collect(Collectors.toList()); + } + + + + @Override + public Collection getAuthorities() { + return authorities; + } + + @Override + public String getPassword() { + return password; + } + + @Override + public String getUsername() { + return username; + } + + @Override + public boolean isAccountNonExpired() { + return true; + } + + @Override + public boolean isAccountNonLocked() { + return true; + } + + @Override + public boolean isCredentialsNonExpired() { + return true; + } + + @Override + public boolean isEnabled() { + return true; + } + + public String getUuid() { + return uuid; + } + + + + public Integer getCodigoUsuario() { + return codigoUsuario; + } + + + + public void setCodigoUsuario(Integer codigoUsuario) { + this.codigoUsuario = codigoUsuario; + } + +} diff --git a/src/main/java/br/com/santander/services/GastoService.java b/src/main/java/br/com/santander/services/GastoService.java new file mode 100644 index 00000000..cc80bad5 --- /dev/null +++ b/src/main/java/br/com/santander/services/GastoService.java @@ -0,0 +1,202 @@ +package br.com.santander.services; + +import java.util.ArrayList; +import java.util.Calendar; +import java.util.Date; +import java.util.GregorianCalendar; +import java.util.List; +import java.util.Optional; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.BeanUtils; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +import br.com.santander.dtos.GastoDTO; +import br.com.santander.entities.Gasto; +import br.com.santander.repositories.GastoRepository; + +@Service +public class GastoService { + +// Integer codigoCliente = 1; + @Autowired + private static Logger logger = LoggerFactory.getLogger(GastoService.class); + + @Autowired + private GastoRepository gastoRepository; + + public GastoDTO cadastrar(GastoDTO gastoDTO, Integer codigousuario) { + Gasto gasto = new Gasto(); + BeanUtils.copyProperties(gastoDTO, gasto, "uuid"); + gasto.setCodigousuario(codigousuario); + List gastosSalvos = gastosPorDescricao(gasto.getDescricao(), codigousuario); + if(gastosSalvos.size() > 0) { + if(gastosSalvos.get(0).getCategoria() != null) { + gasto.setCategoria(gastosSalvos.get(0).getCategoria()); + } + } + if(gasto.getData() == null) { + gasto.setData(new Date()); + } + BeanUtils.copyProperties(gastoRepository.save(gasto), gastoDTO); + return gastoDTO; + } + + public Gasto salve(Gasto gasto, Integer codigousuario) { + gasto.setCodigousuario(codigousuario); + return gastoRepository.save(gasto); + } + + + public List listar(Integer codigousuario){ + List gastosDTO = new ArrayList<>(); + List gastos = gastoRepository.findAllByCodigousuario(codigousuario); + gastos.forEach(g -> { + GastoDTO gastoDTO = new GastoDTO(); + BeanUtils.copyProperties(g, gastoDTO); + gastosDTO.add(gastoDTO); + }); + return gastosDTO; + } + + public List listarPorData(String data, Integer codigousuario){ + if(dataValida(data)) { + int dia = Integer.parseInt(data.split("/")[0]); + int mes = Integer.parseInt(data.split("/")[1]); + int ano = Integer.parseInt(data.split("/")[2]); + Calendar inicio = GregorianCalendar.getInstance(); + inicio.set(ano, mes-1, dia, 0, 0); + + Calendar fim = GregorianCalendar.getInstance(); + fim.set(ano, mes-1, dia, 23, 59); + + List gastosDTO = new ArrayList<>(); + List gastos = gastoRepository.findAllByDataBetweenAndCodigousuario(inicio.getTime(), fim.getTime(), codigousuario); + gastos.forEach(g -> { + GastoDTO gastoDTO = new GastoDTO(); + BeanUtils.copyProperties(g, gastoDTO); + gastosDTO.add(gastoDTO); + }); + return gastosDTO; + } + return null; + + } + + public GastoDTO getDTO(String uuid, Integer codigousuario) { + Optional gasto = gastoRepository.findByUuidAndCodigousuario(uuid, codigousuario); + GastoDTO gastoDTO = new GastoDTO(); + BeanUtils.copyProperties(gasto.get(), gastoDTO); + return gastoDTO; + } + + private Gasto get(String uuid, Integer codigousuario) { + Optional gasto = gastoRepository.findByUuidAndCodigousuario(uuid, codigousuario); + return gasto.get(); + } + + /** + * Método de uso interno(private) para recuperar os gastos por uma descriç~ao + * @author valdeci + * @param descricao + * @param codigousuario + * @return + */ + private List gastosPorDescricao(String descricao, Integer codigousuario){ + return gastoRepository.findAllByLikeDescricaoAndCodigousuario(descricao, codigousuario); + } + + /** + * Esse método altera a categoria de um gasto que foi + * @author valdeci + * @param categoria + * @param uuid + * @param codigousuario + * @return + */ + public GastoDTO alterarCategoria(String categoria, String uuid, Integer codigousuario) { + Gasto gasto = get(uuid, codigousuario); + gasto.setCategoria(categoria); + GastoDTO gastoDTO = new GastoDTO(); + salve(gasto, codigousuario); + BeanUtils.copyProperties(gasto, gastoDTO); + return gastoDTO; + } + + /** + * Método de uso interno para fazer algumas validações de data. Esse método não foi copiado da internet. O mesmo + * foi elaborado por mim + * @author valdeci + * @param data + * @return + */ + private Boolean dataValida(String data) { + if(data == null) { + ResponseUtil.mensagemErro("Valor da data está Null"); + return false; + }else { + char separador = data.charAt(2); + if(separador != '-' && separador != '/') { + ResponseUtil.mensagemErro("A "+ data +" não está no padrão brasileiro"); + return false; + }else { + if(separador == '/') { + int dia = Integer.parseInt(data.split("/")[0]); + int mes = Integer.parseInt(data.split("/")[1]); + int ano = Integer.parseInt(data.split("/")[2]); + if(dia > 30) { + ResponseUtil.mensagemErro("A "+ data +" está inválida"); + return false; + } + if(mes < 1 || mes > 12) { + ResponseUtil.mensagemErro("A "+ data +" está inválida"); + return false; + } + }else { + int dia = Integer.parseInt(data.split("-")[0]); + int mes = Integer.parseInt(data.split("-")[1]); + int ano = Integer.parseInt(data.split("-")[2]); + if(dia > 30) { + ResponseUtil.mensagemErro("A "+ data +" está inválida"); + return false; + } + if(mes < 1 || mes > 12) { + ResponseUtil.mensagemErro("A "+ data +" está inválida"); + return false; + } + } + } + } + return true; + + } + + public List pesquisarCategorias(String categoria, Integer codigousuario){ + return gastoRepository.findCategoraiasByCodigousuarioAndLikeCategoria(codigousuario, "%"+categoria+"%"); + } +} + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/main/java/br/com/santander/services/ResponseUtil.java b/src/main/java/br/com/santander/services/ResponseUtil.java new file mode 100644 index 00000000..09b1ef01 --- /dev/null +++ b/src/main/java/br/com/santander/services/ResponseUtil.java @@ -0,0 +1,21 @@ +package br.com.santander.services; + +import java.util.List; + +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.web.server.ResponseStatusException; + +public class ResponseUtil { + public static void mensagemErro(String mensagem) { + throw new ResponseStatusException(HttpStatus.I_AM_A_TEAPOT, mensagem, null); + } + + public static void mensagemErro(String mensagem, Exception e) { + throw new ResponseStatusException(HttpStatus.I_AM_A_TEAPOT, mensagem, e); + } + + public static ResponseEntity retornaMensagemErro(List mensagens) { + return ResponseEntity.status(HttpStatus.I_AM_A_TEAPOT).body(mensagens); + } +} diff --git a/src/main/java/br/com/santander/services/UserDetailsServiceImpl.java b/src/main/java/br/com/santander/services/UserDetailsServiceImpl.java new file mode 100644 index 00000000..18d53dbf --- /dev/null +++ b/src/main/java/br/com/santander/services/UserDetailsServiceImpl.java @@ -0,0 +1,33 @@ +package br.com.santander.services; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.security.core.context.SecurityContextHolder; +import org.springframework.security.core.userdetails.UserDetails; +import org.springframework.security.core.userdetails.UserDetailsService; +import org.springframework.security.core.userdetails.UsernameNotFoundException; +import org.springframework.stereotype.Service; + +import br.com.santander.entities.Usuario; +import br.com.santander.security.UserSecurity; + +@Service +public class UserDetailsServiceImpl implements UserDetailsService { + + @Autowired + private UsuarioService usuarioService; + + @Override + public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { + Usuario usuario = usuarioService.usuarioPorUsername(username); + + System.out.println("DADOS-------------------------------"); + System.out.println(usuario.getUsername()); + System.out.println(); + return new UserSecurity(usuario.getUuid(), usuario.getUsername(), usuario.getPassword(), usuario.getPerfis(), usuario.getCodigo()); + } + + public UserSecurity get(){ + return (UserSecurity) SecurityContextHolder.getContext().getAuthentication().getPrincipal(); + } + +} diff --git a/src/main/java/br/com/santander/services/UsuarioService.java b/src/main/java/br/com/santander/services/UsuarioService.java new file mode 100644 index 00000000..b1d78f05 --- /dev/null +++ b/src/main/java/br/com/santander/services/UsuarioService.java @@ -0,0 +1,24 @@ +package br.com.santander.services; + +import java.util.Optional; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +import br.com.santander.entities.Usuario; +import br.com.santander.repositories.UsuarioRepository; + +@Service +public class UsuarioService { + + @Autowired + private UsuarioRepository usuarioRepository; + + public Usuario usuarioPorUsername(String username) { + Optional usuario = usuarioRepository.findByUsername(username); + if(!usuario.isPresent()) { + ResponseUtil.mensagemErro("Não foi encontrado nenhum usuário com o username "+username); + } + return usuario.get(); + } +} diff --git a/src/main/resources/application.yml b/src/main/resources/application.yml new file mode 100644 index 00000000..7a808877 --- /dev/null +++ b/src/main/resources/application.yml @@ -0,0 +1,33 @@ +server: + port: 8081 + +jwt: + secret: quero-ir-para-sao-paulo + expire: 90000000 + +spring: + datasource: + url: jdbc:postgresql://localhost:5432/santander?compatible=7.2 + username: postgres + password: postgres + flyway: + url: jdbc:postgresql://localhost:5432/santander?compatible=7.2 + schemas: public + user: postgres + password: postgres + baselineOnMigrate: true + + jpa: + properties: + hibernate: + dialect: org.hibernate.dialect.PostgreSQL9Dialect + use_sql_comments: true + format_sql: true + type: trace + show_sql: true + use_jdbc_metadata_defaults: false + jdbc.lob.non_contextual_creation: true + hibernate: + ddl-auto: update + application: + name: santander \ No newline at end of file diff --git a/src/main/resources/db/migration/V1__Initial.sql b/src/main/resources/db/migration/V1__Initial.sql new file mode 100644 index 00000000..dbccebba --- /dev/null +++ b/src/main/resources/db/migration/V1__Initial.sql @@ -0,0 +1,3 @@ +INSERT INTO usuarios(id, password, username, codigo) VALUES +('abc123', '$2a$10$ZLsxgbeBkwhHsuDkNn.Vc.OJMQmabkfVJhrM3SzVHk/lQR/uPDduu', 'email@email.com', 1), +('def456', '$2a$10$ZLsxgbeBkwhHsuDkNn.Vc.OJMQmabkfVJhrM3SzVHk/lQR/uPDduu', 'dev@email.com', 2); \ No newline at end of file diff --git a/src/test/java/br/com/santander/AbstractTest.java b/src/test/java/br/com/santander/AbstractTest.java new file mode 100644 index 00000000..20cf1ef8 --- /dev/null +++ b/src/test/java/br/com/santander/AbstractTest.java @@ -0,0 +1,14 @@ +package br.com.santander; + +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.annotation.Rollback; +import org.springframework.test.context.TestPropertySource; +import org.springframework.test.context.junit4.SpringRunner; + +@RunWith(SpringRunner.class) +@SpringBootTest +@TestPropertySource(locations="classpath:application-test.yml") +@Rollback(true) +public abstract class AbstractTest {} + diff --git a/src/test/java/br/com/santander/GastosTest.java b/src/test/java/br/com/santander/GastosTest.java new file mode 100644 index 00000000..92003db2 --- /dev/null +++ b/src/test/java/br/com/santander/GastosTest.java @@ -0,0 +1,76 @@ +package br.com.santander; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.math.BigDecimal; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.annotation.Rollback; +import org.springframework.test.context.junit4.SpringRunner; + +import br.com.santander.dtos.GastoDTO; +import br.com.santander.services.GastoService; + +@Rollback(true) +@RunWith(SpringRunner.class) +@SpringBootTest +public class GastosTest extends AbstractTest{ + + @Autowired + private GastoService gastoService; + + @Test + public void listar() { + assertThat(gastoService.listar(1).size()).isGreaterThan(0); + } + + @Test + public void listarPorData() { + assertThat(gastoService.listarPorData("01/09/2019", 1).size()).isGreaterThan(0); + } + + @Test + public void cadastrar() { + GastoDTO gasto = new GastoDTO(); + + gasto.setDescricao("Teste unitário"); + gasto.setValor(BigDecimal.valueOf(0.50)); + + assertThat(gastoService.cadastrar(gasto, 1).getUuid()).isNotBlank(); + } + + @Test + public void get() { + assertThat(gastoService.getDTO("c403abf5-81e9-432c-8180-b6f460a91749", 1).getUuid()).isNotBlank(); + } + + @Test + public void alterarCategoria() { + assertThat(gastoService.alterarCategoria("alterando", "c403abf5-81e9-432c-8180-b6f460a91749", 1).getUuid()).isNotBlank(); + } + + @Test + public void pesquisarCategorias() { + assertThat(gastoService.pesquisarCategorias("e", 1).size()).isGreaterThan(1); + } +} + + + + + + + + + + + + + + + + + diff --git a/src/test/java/br/com/santander/SantanderApplicationTests.java b/src/test/java/br/com/santander/SantanderApplicationTests.java new file mode 100644 index 00000000..c2b669d3 --- /dev/null +++ b/src/test/java/br/com/santander/SantanderApplicationTests.java @@ -0,0 +1,24 @@ +package br.com.santander; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; +import org.springframework.test.context.junit4.SpringRunner; + +import br.com.santander.services.UsuarioService; + +@RunWith(SpringRunner.class) +@SpringBootTest +public class SantanderApplicationTests extends AbstractTest { + + @Autowired + private BCryptPasswordEncoder e; + + @Test + public void contextLoads() { + System.out.println(e.encode("123")); + } + +} diff --git a/src/test/resources/application-test.yml b/src/test/resources/application-test.yml new file mode 100644 index 00000000..3ec6946a --- /dev/null +++ b/src/test/resources/application-test.yml @@ -0,0 +1,7 @@ +server: + port: 8081 +spring: + datasource: + url: jdbc:postgresql://localhost:5432/santander?compatible=7.2 + username: postgres + password: postgres