diff --git a/.gitignore b/.gitignore new file mode 100644 index 00000000..153c9335 --- /dev/null +++ b/.gitignore @@ -0,0 +1,29 @@ +HELP.md +/target/ +!.mvn/wrapper/maven-wrapper.jar + +### 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/Dockerfile b/Dockerfile new file mode 100644 index 00000000..981ae252 --- /dev/null +++ b/Dockerfile @@ -0,0 +1,20 @@ +# Start with a base image containing Java runtime +FROM openjdk:8-jdk-alpine + +# Add Maintainer Info +LABEL maintainer="thadeu.afm@gmail.com" + +# Add a volume pointing to /tmp +VOLUME /tmp + +# Make port 8080 available to the world outside this container +EXPOSE 8080 + +# The application's jar file +ARG JAR_FILE=target/SantanderTechnologies-0.0.1-SNAPSHOT.jar + +# Add the application's jar to the container +ADD ${JAR_FILE} app.jar + +# Run the jar file +ENTRYPOINT ["java","-Djava.security.egd=file:/dev/./urandom","-jar","/app.jar"] \ No newline at end of file diff --git a/README.md b/README.md index 15d8f685..f359cdad 100644 --- a/README.md +++ b/README.md @@ -1,3 +1,118 @@ +# Como executar + +# Docker-Compose + +Execute as seguintes linhas de comando + + git clone https://github.com/ThadeuFerreira/TestBackJava + cd TestBackJava + mvn package + java -jar target/SantanderTechnologies-0.0.1-SNAPSHOT.jar + + docker-compose build + docker-compose up + +ATENÇÃO! +É possivel que na primeira vez que seja executado a aplicação java tente se conectar com o banco de dados antes dele estar funcionando. +Nesse caso, tente novamente. Se o erro persistir, execute a aplicação e o banco de dados separadamente, proxima sessão. + +# Executando o banco de dados se paradamente + +Crie um servidor de banco de dados mysql no localhost e portas padão 3306 com senha de root "password" e nome test +Ou execute o comando a seguir para criar o servidor e banco pelo Docker + + docker run --name mysql -e MYSQL_ROOT_PASSWORD=password -e MYSQL_DATABASE=test -p 3306:3306 -p 33060:33060 -d mysql:latest + +Execute a aplicação + + mvn spring-boot:run + +# Como utilizar a API + +A autenticação é feita utilizando Bearer Token. Criar usuário não requer autenticação, todas as outras requisicões precisam do Token obtido no login. + +- Criar usuário + + + POST localhost:8080/api/auth/signup + + Payload + { + "name": "Thadeu Costa", + "username": "ThadeuCosta", + "email":"thadeucosta@gmail.com", + "password":"Secret" + } + +- Login + + + + Post http://localhost:8080/api/auth/signin + Payload + { + "usernameOrEmail":"ThadeuCosta" , + "password":"Secret" + } + +- Criar novo cartão de crédito + + + POST http://localhost:8080/api/user/newCreditCard + Payload + { + "number":"666 666 666 666", + "validationCode":"666", + "clientName":"Thadeu Antonio F Melo", + "duoDate":"2020-04-21T18:25:43-05:00" + } + +- Adicionar gasto em um Cartão + + + POST http://localhost:8080/api/spending + Payload + { + "description":"Descrição", + "amount": 88.10, + "category": "Roupas", + "date": "2019-05-21T18:25:43-05:00", + "creditCardNumber":"666 666 666 666" + } + + +- Listar total de gastos do Cartão + + + GET http://localhost:8080/api/creditcard/details/ + +- Listar todos os gastos do usuário + + + GET http://localhost:8080/api/user/creditCards + +- Listar gastos filtrados por dia + + + GET http://localhost:8080/api/spending/filterbydate/21052019 + + - Listar gastos sem category de um Cartão + + + GET http://localhost:8080/api/spending/nocategory/ + +- Editar a categoria de um gasto + + + POST http://localhost:8080/api/spending/edit + Payload + { + "spendingId":9, + "category":"Games" + } + + + # Show me the code ### # DESAFIO: diff --git a/docker-compose.yml b/docker-compose.yml new file mode 100644 index 00000000..e29a87e4 --- /dev/null +++ b/docker-compose.yml @@ -0,0 +1,47 @@ +# Docker Compose file Reference (https://docs.docker.com/compose/compose-file/) + +version: '3.3' + +# Define services +services: + # App backend service + app-server: + # Configuration for building the docker image for the backend service + build: + context: . # Use an image built from the specified dockerfile in the `polling-app-server` directory. + dockerfile: Dockerfile + ports: + - "8080:8080" # Forward the exposed port 8080 on the container to port 8080 on the host machine + restart: always + depends_on: + - db # This service depends on mysql. Start that first. + environment: # Pass environment variables to the service + SPRING_DATASOURCE_URL: jdbc:mysql://db:3306/test?useSSL=false&serverTimezone=UTC&useLegacyDatetimeCode=false + SPRING_DATASOURCE_USERNAME: test + SPRING_DATASOURCE_PASSWORD: password + networks: # Networks to join (Services on the same network can communicate with each other using their name) + - backend + + # Database Service (Mysql) + db: + image: mysql:5.7 + ports: + - "3306:3306" + restart: always + environment: + MYSQL_DATABASE: test + MYSQL_USER: test + MYSQL_PASSWORD: password + MYSQL_ROOT_PASSWORD: root + volumes: + - db-data:/var/lib/mysql + networks: + - backend + +# Volumes +volumes: + db-data: + +# Networks to be created to facilitate communication between containers +networks: + backend: \ No newline at end of file diff --git a/mvnw b/mvnw new file mode 100644 index 00000000..8b61d43a --- /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 - description of a JDK home dir +# +# Optional ENV vars +# ----------------- +# M2_HOME - description 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 amount; do + case "$key" in (wrapperUrl) jarUrl="$amount"; 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..89466c06 --- /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 - description of a JDK home dir +@REM +@REM Optional ENV vars +@REM M2_HOME - description 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 description 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 description 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..ae14f15b --- /dev/null +++ b/pom.xml @@ -0,0 +1,103 @@ + + + 4.0.0 + + org.springframework.boot + spring-boot-starter-parent + 2.1.4.RELEASE + + + com.example + SantanderTechnologies + 0.0.1-SNAPSHOT + SantanderTechnologies + Demo project for Spring Boot + + + 1.8 + + + + + org.springframework.boot + spring-boot-starter-data-jpa + + + org.springframework.boot + spring-boot-starter-security + + + + + io.springfox + springfox-swagger2 + 2.6.1 + + + + io.springfox + springfox-swagger-ui + 2.6.1 + + + + io.jsonwebtoken + jjwt + 0.8.0 + + + + + org.springframework.security + spring-security-jwt + 1.0.10.RELEASE + + + + org.projectlombok + lombok + true + + + + org.springframework.boot + spring-boot-starter-web + + + org.springframework.session + spring-session-core + + + + org.springframework.boot + spring-boot-devtools + runtime + + + mysql + mysql-connector-java + runtime + + + org.springframework.boot + spring-boot-starter-test + test + + + org.springframework.security + spring-security-test + test + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + + diff --git a/src/main/java/com/example/SantanderTechnologies/SantanderTechnologiesApplication.java b/src/main/java/com/example/SantanderTechnologies/SantanderTechnologiesApplication.java new file mode 100644 index 00000000..6368f8f5 --- /dev/null +++ b/src/main/java/com/example/SantanderTechnologies/SantanderTechnologiesApplication.java @@ -0,0 +1,13 @@ +package com.example.SantanderTechnologies; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class SantanderTechnologiesApplication { + + public static void main(String[] args) { + SpringApplication.run(SantanderTechnologiesApplication.class, args); + } + +} diff --git a/src/main/java/com/example/SantanderTechnologies/config/AuditingConfig.java b/src/main/java/com/example/SantanderTechnologies/config/AuditingConfig.java new file mode 100644 index 00000000..09ac2f28 --- /dev/null +++ b/src/main/java/com/example/SantanderTechnologies/config/AuditingConfig.java @@ -0,0 +1,40 @@ +package com.example.SantanderTechnologies.config; + +import com.example.SantanderTechnologies.security.UserPrincipal; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.data.domain.AuditorAware; +import org.springframework.data.jpa.repository.config.EnableJpaAuditing; +import org.springframework.security.authentication.AnonymousAuthenticationToken; +import org.springframework.security.core.Authentication; +import org.springframework.security.core.context.SecurityContextHolder; + +import java.util.Optional; + +@Configuration +@EnableJpaAuditing +public class AuditingConfig { + + @Bean + public AuditorAware auditorProvider() { + return new SpringSecurityAuditAwareImpl(); + } +} + +class SpringSecurityAuditAwareImpl implements AuditorAware { + + @Override + public Optional getCurrentAuditor() { + Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); + + if (authentication == null || + !authentication.isAuthenticated() || + authentication instanceof AnonymousAuthenticationToken) { + return Optional.empty(); + } + + UserPrincipal userPrincipal = (UserPrincipal) authentication.getPrincipal(); + + return Optional.ofNullable(userPrincipal.getId()); + } +} diff --git a/src/main/java/com/example/SantanderTechnologies/config/SecurityConfig.java b/src/main/java/com/example/SantanderTechnologies/config/SecurityConfig.java new file mode 100644 index 00000000..984c11f2 --- /dev/null +++ b/src/main/java/com/example/SantanderTechnologies/config/SecurityConfig.java @@ -0,0 +1,105 @@ +package com.example.SantanderTechnologies.config; + + +import com.example.SantanderTechnologies.security.CustomUserDetailsService; +import com.example.SantanderTechnologies.security.JwtAuthenticationEntryPoint; +import com.example.SantanderTechnologies.security.JwtAuthenticationFilter; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.http.HttpMethod; +import org.springframework.security.authentication.AuthenticationManager; +import org.springframework.security.config.BeanIds; +import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; +import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity; +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.crypto.bcrypt.BCryptPasswordEncoder; +import org.springframework.security.crypto.password.PasswordEncoder; +import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter; + + +/** + * Created by rajeevkumarsingh on 01/08/17. + */ + +@Configuration +@EnableWebSecurity +@EnableGlobalMethodSecurity( + securedEnabled = true, + jsr250Enabled = true, + prePostEnabled = true +) +public class SecurityConfig extends WebSecurityConfigurerAdapter { + + @Autowired + CustomUserDetailsService customUserDetailsService; + + @Autowired + private JwtAuthenticationEntryPoint unauthorizedHandler; + + @Bean + public JwtAuthenticationFilter jwtAuthenticationFilter() { + return new JwtAuthenticationFilter(); + } + + @Override + public void configure(AuthenticationManagerBuilder authenticationManagerBuilder) throws Exception { + authenticationManagerBuilder + .userDetailsService(customUserDetailsService) + .passwordEncoder(passwordEncoder()); + } + + @Bean(BeanIds.AUTHENTICATION_MANAGER) + @Override + public AuthenticationManager authenticationManagerBean() throws Exception { + return super.authenticationManagerBean(); + } + + @Bean + public PasswordEncoder passwordEncoder() { + return new BCryptPasswordEncoder(); + } + + @Override + protected void configure(HttpSecurity http) throws Exception { + http + .cors() + .and() + .csrf() + .disable() + .exceptionHandling() + .authenticationEntryPoint(unauthorizedHandler) + .and() + .sessionManagement() + .sessionCreationPolicy(SessionCreationPolicy.STATELESS) + .and() + .authorizeRequests() + .antMatchers("/", + "/favicon.ico", + "/**/*.png", + "/**/*.gif", + "/**/*.svg", + "/**/*.jpg", + "/**/*.html", + "/**/*.css", + "/**/*.js") + .permitAll() + .antMatchers("/api/auth/**") + .permitAll() + .antMatchers("/api/user/checkUsernameAvailability", "/api/user/checkEmailAvailability") + .permitAll() + .antMatchers(HttpMethod.GET, "/api/users/**") + .permitAll() + .antMatchers("/META-INF/resources/**", "/v2/api-docs", "/configuration/**", "/swagger*/**", "/webjars/**") + .permitAll() + .anyRequest() + .authenticated(); + + // Add our custom JWT security filter + http.addFilterBefore(jwtAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class); + + } +} \ No newline at end of file diff --git a/src/main/java/com/example/SantanderTechnologies/config/SwaggerConfig.java b/src/main/java/com/example/SantanderTechnologies/config/SwaggerConfig.java new file mode 100644 index 00000000..a6a23d64 --- /dev/null +++ b/src/main/java/com/example/SantanderTechnologies/config/SwaggerConfig.java @@ -0,0 +1,32 @@ +package com.example.SantanderTechnologies.config; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; +import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport; +import springfox.documentation.builders.ApiInfoBuilder; +import springfox.documentation.builders.PathSelectors; +import springfox.documentation.builders.RequestHandlerSelectors; +import springfox.documentation.service.ApiInfo; +import springfox.documentation.service.Contact; +import springfox.documentation.spi.DocumentationType; +import springfox.documentation.spring.web.plugins.Docket; +import springfox.documentation.swagger2.annotations.EnableSwagger2; + +import java.util.Arrays; +import java.util.HashSet; +import java.util.Set; + + +@Configuration +@EnableSwagger2 +public class SwaggerConfig { + @Bean + public Docket api() { + return new Docket(DocumentationType.SWAGGER_2) + .select() + .apis(RequestHandlerSelectors.any()) + .paths(PathSelectors.any()) + .build(); + } +} diff --git a/src/main/java/com/example/SantanderTechnologies/config/WebMvcConfig.java b/src/main/java/com/example/SantanderTechnologies/config/WebMvcConfig.java new file mode 100644 index 00000000..c0b9bb68 --- /dev/null +++ b/src/main/java/com/example/SantanderTechnologies/config/WebMvcConfig.java @@ -0,0 +1,23 @@ +package com.example.SantanderTechnologies.config; + +import org.springframework.context.annotation.Configuration; +import org.springframework.web.servlet.config.annotation.CorsRegistry; +import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; + +/** + * Created by rajeevkumarsingh on 02/08/17. + */ + +@Configuration +public class WebMvcConfig implements WebMvcConfigurer { + + private final long MAX_AGE_SECS = 3600; + + @Override + public void addCorsMappings(CorsRegistry registry) { + registry.addMapping("/**") + .allowedOrigins("*") + .allowedMethods("HEAD", "OPTIONS", "GET", "POST", "PUT", "PATCH", "DELETE") + .maxAge(MAX_AGE_SECS); + } +} diff --git a/src/main/java/com/example/SantanderTechnologies/controller/AuthController.java b/src/main/java/com/example/SantanderTechnologies/controller/AuthController.java new file mode 100644 index 00000000..6011a088 --- /dev/null +++ b/src/main/java/com/example/SantanderTechnologies/controller/AuthController.java @@ -0,0 +1,104 @@ +package com.example.SantanderTechnologies.controller; + + +import com.example.SantanderTechnologies.exception.AppException; +import com.example.SantanderTechnologies.model.Role; +import com.example.SantanderTechnologies.model.RoleName; +import com.example.SantanderTechnologies.model.User; +import com.example.SantanderTechnologies.payload.ApiResponse; +import com.example.SantanderTechnologies.payload.JwtAuthenticationResponse; +import com.example.SantanderTechnologies.payload.LoginRequest; +import com.example.SantanderTechnologies.payload.SignUpRequest; +import com.example.SantanderTechnologies.repository.RoleRepository; +import com.example.SantanderTechnologies.repository.UserRepository; +import com.example.SantanderTechnologies.security.JwtTokenProvider; +import io.swagger.annotations.Api; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.security.authentication.AuthenticationManager; +import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; +import org.springframework.security.core.Authentication; +import org.springframework.security.core.context.SecurityContextHolder; +import org.springframework.security.crypto.password.PasswordEncoder; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; +import org.springframework.web.servlet.support.ServletUriComponentsBuilder; + +import javax.validation.Valid; +import java.net.URI; +import java.util.Collections; + +/** + * Created by rajeevkumarsingh on 02/08/17. + */ +@RestController +@RequestMapping("/api/auth") +@Api(value = "Greeting", description = "Greeting people") +public class AuthController { + + @Autowired + AuthenticationManager authenticationManager; + + @Autowired + UserRepository userRepository; + + @Autowired + RoleRepository roleRepository; + + @Autowired + PasswordEncoder passwordEncoder; + + @Autowired + JwtTokenProvider tokenProvider; + + @PostMapping("/signin") + public ResponseEntity authenticateUser(@Valid @RequestBody LoginRequest loginRequest) { + + Authentication authentication = authenticationManager.authenticate( + new UsernamePasswordAuthenticationToken( + loginRequest.getUsernameOrEmail(), + loginRequest.getPassword() + ) + ); + + SecurityContextHolder.getContext().setAuthentication(authentication); + + String jwt = tokenProvider.generateToken(authentication); + return ResponseEntity.ok(new JwtAuthenticationResponse(jwt)); + } + + @PostMapping("/signup") + public ResponseEntity registerUser(@Valid @RequestBody SignUpRequest signUpRequest) { + if(userRepository.existsByUsername(signUpRequest.getUsername())) { + return new ResponseEntity(new ApiResponse(false, "Username is already taken!"), + HttpStatus.BAD_REQUEST); + } + + if(userRepository.existsByEmail(signUpRequest.getEmail())) { + return new ResponseEntity(new ApiResponse(false, "Email Address already in use!"), + HttpStatus.BAD_REQUEST); + } + + // Creating user's account + User user = new User(signUpRequest.getName(), signUpRequest.getUsername(), + signUpRequest.getEmail(), signUpRequest.getPassword()); + + user.setPassword(passwordEncoder.encode(user.getPassword())); + + Role userRole = roleRepository.findByName(RoleName.ROLE_USER) + .orElseThrow(() -> new AppException("User Role not set.")); + + user.setRoles(Collections.singleton(userRole)); + + User result = userRepository.save(user); + + URI location = ServletUriComponentsBuilder + .fromCurrentContextPath().path("/users/{username}") + .buildAndExpand(result.getUsername()).toUri(); + + return ResponseEntity.created(location).body(new ApiResponse(true, "User registered successfully")); + } +} diff --git a/src/main/java/com/example/SantanderTechnologies/controller/CreditCardController.java b/src/main/java/com/example/SantanderTechnologies/controller/CreditCardController.java new file mode 100644 index 00000000..237317af --- /dev/null +++ b/src/main/java/com/example/SantanderTechnologies/controller/CreditCardController.java @@ -0,0 +1,55 @@ +package com.example.SantanderTechnologies.controller; + +import com.example.SantanderTechnologies.model.CreditCard; +import com.example.SantanderTechnologies.model.Spending; +import com.example.SantanderTechnologies.payload.ApiResponse; +import com.example.SantanderTechnologies.payload.CreditCardResponse; +import com.example.SantanderTechnologies.repository.CreditCardRepository; +import com.example.SantanderTechnologies.repository.SpendingRepository; +import com.example.SantanderTechnologies.security.CurrentUser; +import com.example.SantanderTechnologies.security.UserPrincipal; +import io.swagger.annotations.Api; +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.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +import java.math.BigDecimal; +import java.util.List; +import java.util.Optional; + +@RestController +@RequestMapping("/api/creditcard") +public class CreditCardController { + + @Autowired + CreditCardRepository creditCardRepository; + + @Autowired + SpendingRepository spendingRepository; + + @GetMapping("/details/{number}") + public ApiResponse getCreditCard(@CurrentUser UserPrincipal currentUser, @PathVariable String number){ + Optional optionalCreditCard = creditCardRepository.findByNumber(number); + if(!optionalCreditCard.isPresent()){ + return new ApiResponse(false, "Could not find credit card"); + } + + CreditCard creditCard = optionalCreditCard.get(); + + List spendings = spendingRepository.findAllByCreditCardId(creditCard.getId()); + BigDecimal totalSpending = new BigDecimal(0); + for(Spending s : spendings){ + totalSpending = totalSpending.add(s.getValue()==null?new BigDecimal(0):s.getValue()); + } + + CreditCardResponse creditCardResponse = new CreditCardResponse(true, "Success"); + creditCardResponse.setAmount(totalSpending); + creditCardResponse.setDate(creditCard.getDuoDate()); + creditCardResponse.setUserCode(currentUser.getId()); + creditCardResponse.setDescription(creditCard.getClientName() + " " + creditCard.getUser().getUsername()); + return creditCardResponse; + } + +} diff --git a/src/main/java/com/example/SantanderTechnologies/controller/SpendingController.java b/src/main/java/com/example/SantanderTechnologies/controller/SpendingController.java new file mode 100644 index 00000000..f9f658d8 --- /dev/null +++ b/src/main/java/com/example/SantanderTechnologies/controller/SpendingController.java @@ -0,0 +1,129 @@ +package com.example.SantanderTechnologies.controller; + +import com.example.SantanderTechnologies.model.CreditCard; +import com.example.SantanderTechnologies.model.Spending; +import com.example.SantanderTechnologies.model.SpendingCategory; +import com.example.SantanderTechnologies.payload.ApiResponse; +import com.example.SantanderTechnologies.payload.EditSpendingRequest; +import com.example.SantanderTechnologies.payload.SpendingRequest; +import com.example.SantanderTechnologies.repository.CategoryRepository; +import com.example.SantanderTechnologies.repository.CreditCardRepository; +import com.example.SantanderTechnologies.repository.SpendingRepository; +import com.example.SantanderTechnologies.security.CurrentUser; +import com.example.SantanderTechnologies.security.UserPrincipal; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.format.annotation.DateTimeFormat; +import org.springframework.web.bind.annotation.*; + +import java.util.*; +import java.util.stream.Collectors; + +@RestController +@RequestMapping("/api/spending") +public class SpendingController { + + @Autowired + CreditCardRepository creditCardRepository; + + @Autowired + SpendingRepository spendingRepository; + + @Autowired + CategoryRepository categoryRepository; + + @PostMapping + public ApiResponse addNewSpending(@CurrentUser UserPrincipal currentUser, @RequestBody SpendingRequest spendingRequest){ + Optional optionalCreditCard = creditCardRepository.findByNumber(spendingRequest.getCreditCardNumber()); + if(!optionalCreditCard.isPresent()){ + return new ApiResponse(false, "Could not find credit card"); + } + + CreditCard creditCard = optionalCreditCard.get(); + SpendingCategory spendingCategory; + String spendingCategoryName = spendingRequest.getCategory(); + if(spendingCategoryName == null || spendingRequest.getDescription() != null){ + Optional optionalSpending = spendingRepository.findFirstByDescription(spendingRequest.getDescription()); + if(optionalSpending.isPresent() && optionalSpending.get().getCategory() != null){ + spendingCategoryName = optionalSpending.get().getCategory().getCategoryName(); + } + } + + Optional optionalSpendingCategory = categoryRepository.findByCategoryName(spendingCategoryName); + if(!optionalSpendingCategory.isPresent()){ + SpendingCategory sc = new SpendingCategory(); + sc.setCategoryName(spendingRequest.getCategory()); + categoryRepository.save(sc); + spendingCategory = sc; + } + else { + spendingCategory = optionalSpendingCategory.get(); + } + Spending spending = new Spending(spendingRequest.getDescription(), + spendingRequest.getAmount(), + spendingCategory, + spendingRequest.getDate(), + creditCard); + spendingRepository.save(spending); + + return new ApiResponse(true, "Spending Created"); + + } + + @GetMapping("/nocategory/{cardnumber}") + public List getSpendingWithoutCategory(@CurrentUser UserPrincipal currentUser, @PathVariable String cardnumber){ + Optional optionalCreditCard = creditCardRepository.findByNumber(cardnumber); + if (!optionalCreditCard.isPresent()){ + return null; //TODO make a default Api Response + } + + List spendings = spendingRepository.findAllByCreditCardId(optionalCreditCard.get().getId()); + + return spendings + .stream() + .filter(spending -> + spending.getCategory() == null || spending.getCategory().getCategoryName() == null) + .collect(Collectors.toList()); + + + } + + @PostMapping("/edit") + public ApiResponse editSpending(@CurrentUser UserPrincipal currentUser, @RequestBody EditSpendingRequest editSpendingRequest){ + + Optional optionalSpending = spendingRepository.findById(editSpendingRequest.getSpendingId()); + + if(!optionalSpending.isPresent()){ + return new ApiResponse(false, "Could not find spending"); + } + + Spending spending = optionalSpending.get(); + SpendingCategory newSpendingCategory = new SpendingCategory(editSpendingRequest.getCategory()); + + spending.setCategory(newSpendingCategory); + categoryRepository.save(newSpendingCategory); + spendingRepository.save(spending); + + return new ApiResponse(true, "Spending category edited."); + } + + @GetMapping("/filterbydate/{date}") + public List filterSpendingByDate(@CurrentUser UserPrincipal currentUser, @PathVariable @DateTimeFormat(pattern = "ddMMyyyy") Date date){ + + List creditCards = creditCardRepository.findAllByUserId(currentUser.getId()); + List spendings = new ArrayList<>(); + for(CreditCard c : creditCards){ + List s = spendingRepository.findAllByCreditCardId(c.getId()); + + s = s.stream().filter( + p -> { + Calendar cal1 = Calendar.getInstance(); + Calendar cal2 = Calendar.getInstance(); + cal1.setTime(p.getDate()); + cal2.setTime(date); + return cal1.get(Calendar.DAY_OF_YEAR) == cal2.get(Calendar.DAY_OF_YEAR);} + ).collect(Collectors.toList()); + spendings.addAll(s); + } + return spendings; + } +} diff --git a/src/main/java/com/example/SantanderTechnologies/controller/UserCardController.java b/src/main/java/com/example/SantanderTechnologies/controller/UserCardController.java new file mode 100644 index 00000000..29f0df52 --- /dev/null +++ b/src/main/java/com/example/SantanderTechnologies/controller/UserCardController.java @@ -0,0 +1,51 @@ +package com.example.SantanderTechnologies.controller; + +import com.example.SantanderTechnologies.model.CreditCard; +import com.example.SantanderTechnologies.model.User; +import com.example.SantanderTechnologies.payload.ApiResponse; +import com.example.SantanderTechnologies.payload.CreditCardRequest; +import com.example.SantanderTechnologies.payload.UserSummary; +import com.example.SantanderTechnologies.repository.CreditCardRepository; +import com.example.SantanderTechnologies.repository.UserRepository; +import com.example.SantanderTechnologies.security.CurrentUser; +import com.example.SantanderTechnologies.security.UserPrincipal; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.security.access.prepost.PreAuthorize; +import org.springframework.web.bind.annotation.*; + +import java.util.List; +import java.util.Optional; + +@RestController +@RequestMapping("/api") +public class UserCardController { + + @Autowired + private UserRepository userRepository; + + @Autowired + private CreditCardRepository creditCardRepository; + + @PostMapping("/user/newCreditCard") + public ApiResponse createNewCreditCard(@CurrentUser UserPrincipal currentUser, @RequestBody CreditCardRequest creditCardRequest) { + + CreditCard creditCard = new CreditCard(creditCardRequest.getClientName(), + creditCardRequest.getNumber(), + creditCardRequest.getValidationCode(), + creditCardRequest.getDuoDate()); + Optional optionalUser = userRepository.findById(currentUser.getId()); + if(!optionalUser.isPresent()){ + return new ApiResponse(true, "Could not find current user"); + } + creditCard.setUser(optionalUser.get()); + creditCardRepository.save(creditCard); + return new ApiResponse(true, "Credit Card created"); + } + + @GetMapping("/user/creditCards") + public List getCreditCards(@CurrentUser UserPrincipal currentUser){ + List creditCards = creditCardRepository.findAllByUserId(currentUser.getId()); + + return creditCards; + } +} diff --git a/src/main/java/com/example/SantanderTechnologies/controller/UserController.java b/src/main/java/com/example/SantanderTechnologies/controller/UserController.java new file mode 100644 index 00000000..f0adce4f --- /dev/null +++ b/src/main/java/com/example/SantanderTechnologies/controller/UserController.java @@ -0,0 +1,61 @@ +package com.example.SantanderTechnologies.controller; + + +import com.example.SantanderTechnologies.exception.ResourceNotFoundException; +import com.example.SantanderTechnologies.model.User; +import com.example.SantanderTechnologies.payload.ApiResponse; +import com.example.SantanderTechnologies.payload.UserIdentityAvailability; +import com.example.SantanderTechnologies.payload.UserProfile; +import com.example.SantanderTechnologies.payload.UserSummary; +import com.example.SantanderTechnologies.repository.UserRepository; +import com.example.SantanderTechnologies.security.CurrentUser; +import com.example.SantanderTechnologies.security.UserPrincipal; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.security.access.prepost.PreAuthorize; +import org.springframework.web.bind.annotation.*; + +@RestController +@RequestMapping("/api") +public class UserController { + + @Autowired + private UserRepository userRepository; + + + private static final Logger logger = LoggerFactory.getLogger(UserController.class); + + @GetMapping("/user/me") + @PreAuthorize("hasRole('USER')") + public UserSummary getCurrentUser(@CurrentUser UserPrincipal currentUser) { + UserSummary userSummary = new UserSummary(currentUser.getId(), currentUser.getUsername(), currentUser.getName()); + return userSummary; + } + + @GetMapping("/user/checkUsernameAvailability") + public UserIdentityAvailability checkUsernameAvailability(@RequestParam(value = "username") String username) { + Boolean isAvailable = !userRepository.existsByUsername(username); + return new UserIdentityAvailability(isAvailable); + } + + @GetMapping("/user/checkEmailAvailability") + public UserIdentityAvailability checkEmailAvailability(@RequestParam(value = "email") String email) { + Boolean isAvailable = !userRepository.existsByEmail(email); + return new UserIdentityAvailability(isAvailable); + } + + @GetMapping("/users/{username}") + public UserProfile getUserProfile(@PathVariable(value = "username") String username) { + User user = userRepository.findByUsername(username) + .orElseThrow(() -> new ResourceNotFoundException("User", "username", username)); + + + UserProfile userProfile = new UserProfile(user.getId(), user.getUsername(), user.getName(), user.getCreatedAt()); + + return userProfile; + } + + + +} diff --git a/src/main/java/com/example/SantanderTechnologies/exception/AppException.java b/src/main/java/com/example/SantanderTechnologies/exception/AppException.java new file mode 100644 index 00000000..e4532652 --- /dev/null +++ b/src/main/java/com/example/SantanderTechnologies/exception/AppException.java @@ -0,0 +1,15 @@ +package com.example.SantanderTechnologies.exception; + +import org.springframework.http.HttpStatus; +import org.springframework.web.bind.annotation.ResponseStatus; + +@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR) +public class AppException extends RuntimeException { + public AppException(String message) { + super(message); + } + + public AppException(String message, Throwable cause) { + super(message, cause); + } +} diff --git a/src/main/java/com/example/SantanderTechnologies/exception/BadRequestException.java b/src/main/java/com/example/SantanderTechnologies/exception/BadRequestException.java new file mode 100644 index 00000000..1116ee4f --- /dev/null +++ b/src/main/java/com/example/SantanderTechnologies/exception/BadRequestException.java @@ -0,0 +1,16 @@ +package com.example.SantanderTechnologies.exception; + +import org.springframework.http.HttpStatus; +import org.springframework.web.bind.annotation.ResponseStatus; + +@ResponseStatus(HttpStatus.BAD_REQUEST) +public class BadRequestException extends RuntimeException { + + public BadRequestException(String message) { + super(message); + } + + public BadRequestException(String message, Throwable cause) { + super(message, cause); + } +} diff --git a/src/main/java/com/example/SantanderTechnologies/exception/ResourceNotFoundException.java b/src/main/java/com/example/SantanderTechnologies/exception/ResourceNotFoundException.java new file mode 100644 index 00000000..19c5acf5 --- /dev/null +++ b/src/main/java/com/example/SantanderTechnologies/exception/ResourceNotFoundException.java @@ -0,0 +1,30 @@ +package com.example.SantanderTechnologies.exception; + +import org.springframework.http.HttpStatus; +import org.springframework.web.bind.annotation.ResponseStatus; + +@ResponseStatus(HttpStatus.NOT_FOUND) +public class ResourceNotFoundException extends RuntimeException { + private String resourceName; + private String fieldName; + private Object fieldValue; + + public ResourceNotFoundException( String resourceName, String fieldName, Object fieldValue) { + super(String.format("%s not found with %s : '%s'", resourceName, fieldName, fieldValue)); + this.resourceName = resourceName; + this.fieldName = fieldName; + this.fieldValue = fieldValue; + } + + public String getResourceName() { + return resourceName; + } + + public String getFieldName() { + return fieldName; + } + + public Object getFieldValue() { + return fieldValue; + } +} diff --git a/src/main/java/com/example/SantanderTechnologies/model/CreditCard.java b/src/main/java/com/example/SantanderTechnologies/model/CreditCard.java new file mode 100644 index 00000000..23da8bfd --- /dev/null +++ b/src/main/java/com/example/SantanderTechnologies/model/CreditCard.java @@ -0,0 +1,105 @@ +package com.example.SantanderTechnologies.model; + +import com.fasterxml.jackson.annotation.JsonIgnore; + +import javax.persistence.*; +import java.math.BigDecimal; +import java.util.Date; +import java.util.List; + +@Entity +public class CreditCard { + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; + + private BigDecimal totalAmount; + + private String number; + + private Integer validationCode; + + private String clientName; + + private Date duoDate; + + @ManyToOne(fetch=FetchType.LAZY) + @JsonIgnore + private User user; + + @OneToMany + private List spendings; + + public CreditCard(){} + + public CreditCard(String clientName, String number, Integer validationCode, Date duoDate) { + this.clientName = clientName; + this.number = number; + this.validationCode = validationCode; + this.duoDate = duoDate; + } + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public BigDecimal getTotalAmount() { + return totalAmount; + } + + public void setTotalAmount(BigDecimal totalAmount) { + this.totalAmount = totalAmount; + } + + public String getNumber() { + return number; + } + + public void setNumber(String number) { + this.number = number; + } + + public Integer getValidationCode() { + return validationCode; + } + + public void setValidationCode(Integer validationCode) { + this.validationCode = validationCode; + } + + public String getClientName() { + return clientName; + } + + public void setClientName(String clientName) { + this.clientName = clientName; + } + + public Date getDuoDate() { + return duoDate; + } + + public void setDuoDate(Date duoDate) { + this.duoDate = duoDate; + } + + public User getUser() { + return user; + } + + public void setUser(User user) { + this.user = user; + } + + public List getSpendings() { + return spendings; + } + + public void setSpendings(List spendings) { + this.spendings = spendings; + } +} diff --git a/src/main/java/com/example/SantanderTechnologies/model/Role.java b/src/main/java/com/example/SantanderTechnologies/model/Role.java new file mode 100644 index 00000000..16447c21 --- /dev/null +++ b/src/main/java/com/example/SantanderTechnologies/model/Role.java @@ -0,0 +1,45 @@ +package com.example.SantanderTechnologies.model; + +import org.hibernate.annotations.NaturalId; +import javax.persistence.*; + +/** + * Created by rajeevkumarsingh on 01/08/17. + */ +@Entity +@Table(name = "roles") +public class Role { + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; + + @Enumerated(EnumType.STRING) + @NaturalId + @Column(length = 60) + private RoleName name; + + public Role() { + + } + + public Role(RoleName name) { + this.name = name; + } + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public RoleName getName() { + return name; + } + + public void setName(RoleName name) { + this.name = name; + } + +} diff --git a/src/main/java/com/example/SantanderTechnologies/model/RoleName.java b/src/main/java/com/example/SantanderTechnologies/model/RoleName.java new file mode 100644 index 00000000..53ff07a3 --- /dev/null +++ b/src/main/java/com/example/SantanderTechnologies/model/RoleName.java @@ -0,0 +1,9 @@ +package com.example.SantanderTechnologies.model; + +/** + * Created by rajeevkumarsingh on 07/12/17. + */ +public enum RoleName { + ROLE_USER, + ROLE_ADMIN +} diff --git a/src/main/java/com/example/SantanderTechnologies/model/Spending.java b/src/main/java/com/example/SantanderTechnologies/model/Spending.java new file mode 100644 index 00000000..078df87d --- /dev/null +++ b/src/main/java/com/example/SantanderTechnologies/model/Spending.java @@ -0,0 +1,85 @@ +package com.example.SantanderTechnologies.model; + +import com.fasterxml.jackson.annotation.JsonIgnore; + +import javax.persistence.*; +import java.math.BigDecimal; +import java.util.Date; + +@Entity +public class Spending { + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; + + private String description; + + private BigDecimal value; + + @ManyToOne(fetch= FetchType.EAGER) + private SpendingCategory category; + + private Date date; + + @ManyToOne(fetch= FetchType.LAZY) + @JsonIgnore + private CreditCard creditCard; + + public Spending(){} + + public Spending(String description, BigDecimal value, SpendingCategory category, Date date, CreditCard creditCard) { + this.description = description; + this.value = value; + this.category = category; + this.date = date; + this.creditCard = creditCard; + } + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } + + public BigDecimal getValue() { + return value; + } + + public void setValue(BigDecimal value) { + this.value = value; + } + + public Date getDate() { + return date; + } + + public void setDate(Date date) { + this.date = date; + } + + public CreditCard getCreditCard() { + return creditCard; + } + + public void setCreditCard(CreditCard creditCard) { + this.creditCard = creditCard; + } + + public SpendingCategory getCategory() { + return category; + } + + public void setCategory(SpendingCategory category) { + this.category = category; + } +} diff --git a/src/main/java/com/example/SantanderTechnologies/model/SpendingCategory.java b/src/main/java/com/example/SantanderTechnologies/model/SpendingCategory.java new file mode 100644 index 00000000..ee9bf29b --- /dev/null +++ b/src/main/java/com/example/SantanderTechnologies/model/SpendingCategory.java @@ -0,0 +1,30 @@ +package com.example.SantanderTechnologies.model; + +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; + +@Entity +public class SpendingCategory { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; + + private String categoryName; + + public SpendingCategory(){} + + public SpendingCategory(String categoryName){ + this.categoryName = categoryName; + } + + public String getCategoryName() { + return categoryName; + } + + public void setCategoryName(String categoryName) { + this.categoryName = categoryName; + } +} diff --git a/src/main/java/com/example/SantanderTechnologies/model/User.java b/src/main/java/com/example/SantanderTechnologies/model/User.java new file mode 100644 index 00000000..f82640c2 --- /dev/null +++ b/src/main/java/com/example/SantanderTechnologies/model/User.java @@ -0,0 +1,124 @@ +package com.example.SantanderTechnologies.model; + +import com.example.SantanderTechnologies.model.audit.DateAudit; +import org.hibernate.annotations.NaturalId; +import javax.persistence.*; +import javax.validation.constraints.Email; +import javax.validation.constraints.NotBlank; +import javax.validation.constraints.Size; +import java.util.HashSet; +import java.util.List; +import java.util.Set; + +/** + * Created by rajeevkumarsingh on 01/08/17. + */ + +@Entity +@Table(name = "users", uniqueConstraints = { + @UniqueConstraint(columnNames = { + "username" + }), + @UniqueConstraint(columnNames = { + "email" + }) +}) +public class User extends DateAudit { + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; + + @NotBlank + @Size(max = 40) + private String name; + + @NotBlank + @Size(max = 15) + private String username; + + @NaturalId + @NotBlank + @Size(max = 40) + @Email + private String email; + + @NotBlank + @Size(max = 100) + private String password; + + @ManyToMany(fetch = FetchType.LAZY) + @JoinTable(name = "user_roles", + joinColumns = @JoinColumn(name = "user_id"), + inverseJoinColumns = @JoinColumn(name = "role_id")) + private Set roles = new HashSet<>(); + + public List getCreditCards() { + return creditCards; + } + + public void setCreditCards(List creditCards) { + this.creditCards = creditCards; + } + + @OneToMany + private List creditCards; + + public User() { + + } + + public User(String name, String username, String email, String password) { + this.name = name; + this.username = username; + this.email = email; + this.password = password; + } + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public String getUsername() { + return username; + } + + public void setUsername(String username) { + this.username = username; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getEmail() { + return email; + } + + public void setEmail(String email) { + this.email = email; + } + + public String getPassword() { + return password; + } + + public void setPassword(String password) { + this.password = password; + } + + public Set getRoles() { + return roles; + } + + public void setRoles(Set roles) { + this.roles = roles; + } +} \ No newline at end of file diff --git a/src/main/java/com/example/SantanderTechnologies/model/audit/DateAudit.java b/src/main/java/com/example/SantanderTechnologies/model/audit/DateAudit.java new file mode 100644 index 00000000..9fd65c9c --- /dev/null +++ b/src/main/java/com/example/SantanderTechnologies/model/audit/DateAudit.java @@ -0,0 +1,43 @@ +package com.example.SantanderTechnologies.model.audit; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import org.springframework.data.annotation.CreatedDate; +import org.springframework.data.annotation.LastModifiedDate; +import org.springframework.data.jpa.domain.support.AuditingEntityListener; + +import javax.persistence.EntityListeners; +import javax.persistence.MappedSuperclass; +import java.io.Serializable; +import java.time.Instant; + +@MappedSuperclass +@EntityListeners(AuditingEntityListener.class) +@JsonIgnoreProperties( + value = {"createdAt", "updatedAt"}, + allowGetters = true +) +public abstract class DateAudit implements Serializable { + + @CreatedDate + private Instant createdAt; + + @LastModifiedDate + private Instant updatedAt; + + public Instant getCreatedAt() { + return createdAt; + } + + public void setCreatedAt(Instant createdAt) { + this.createdAt = createdAt; + } + + public Instant getUpdatedAt() { + return updatedAt; + } + + public void setUpdatedAt(Instant updatedAt) { + this.updatedAt = updatedAt; + } + +} diff --git a/src/main/java/com/example/SantanderTechnologies/model/audit/UserDateAudit.java b/src/main/java/com/example/SantanderTechnologies/model/audit/UserDateAudit.java new file mode 100644 index 00000000..e9590607 --- /dev/null +++ b/src/main/java/com/example/SantanderTechnologies/model/audit/UserDateAudit.java @@ -0,0 +1,41 @@ +package com.example.SantanderTechnologies.model.audit; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import org.springframework.data.annotation.CreatedBy; +import org.springframework.data.annotation.LastModifiedBy; + +import javax.persistence.MappedSuperclass; + +/** + * Created by rajeevkumarsingh on 19/08/17. + */ + +@MappedSuperclass +@JsonIgnoreProperties( + value = {"createdBy", "updatedBy"}, + allowGetters = true +) +public abstract class UserDateAudit extends DateAudit { + + @CreatedBy + private Long createdBy; + + @LastModifiedBy + private Long updatedBy; + + public Long getCreatedBy() { + return createdBy; + } + + public void setCreatedBy(Long createdBy) { + this.createdBy = createdBy; + } + + public Long getUpdatedBy() { + return updatedBy; + } + + public void setUpdatedBy(Long updatedBy) { + this.updatedBy = updatedBy; + } +} diff --git a/src/main/java/com/example/SantanderTechnologies/payload/ApiResponse.java b/src/main/java/com/example/SantanderTechnologies/payload/ApiResponse.java new file mode 100644 index 00000000..60920705 --- /dev/null +++ b/src/main/java/com/example/SantanderTechnologies/payload/ApiResponse.java @@ -0,0 +1,30 @@ +package com.example.SantanderTechnologies.payload; + +/** + * Created by rajeevkumarsingh on 19/08/17. + */ +public class ApiResponse { + private Boolean success; + private String message; + + public ApiResponse(Boolean success, String message) { + this.success = success; + this.message = message; + } + + public Boolean getSuccess() { + return success; + } + + public void setSuccess(Boolean success) { + this.success = success; + } + + public String getMessage() { + return message; + } + + public void setMessage(String message) { + this.message = message; + } +} diff --git a/src/main/java/com/example/SantanderTechnologies/payload/CreditCardRequest.java b/src/main/java/com/example/SantanderTechnologies/payload/CreditCardRequest.java new file mode 100644 index 00000000..cc1b7978 --- /dev/null +++ b/src/main/java/com/example/SantanderTechnologies/payload/CreditCardRequest.java @@ -0,0 +1,52 @@ +package com.example.SantanderTechnologies.payload; + +import java.util.Date; + +public class CreditCardRequest { + private String number; + + private Integer validationCode; + + private String clientName; + + private Date duoDate; + + public CreditCardRequest(String number, Integer validationCode, String clientName, Date duoDate) { + this.number = number; + this.validationCode = validationCode; + this.clientName = clientName; + this.duoDate = duoDate; + } + + public String getNumber() { + return number; + } + + public void setNumber(String number) { + this.number = number; + } + + public Integer getValidationCode() { + return validationCode; + } + + public void setValidationCode(Integer validationCode) { + this.validationCode = validationCode; + } + + public String getClientName() { + return clientName; + } + + public void setClientName(String clientName) { + this.clientName = clientName; + } + + public Date getDuoDate() { + return duoDate; + } + + public void setDuoDate(Date duoDate) { + this.duoDate = duoDate; + } +} diff --git a/src/main/java/com/example/SantanderTechnologies/payload/CreditCardResponse.java b/src/main/java/com/example/SantanderTechnologies/payload/CreditCardResponse.java new file mode 100644 index 00000000..ec5aba1e --- /dev/null +++ b/src/main/java/com/example/SantanderTechnologies/payload/CreditCardResponse.java @@ -0,0 +1,60 @@ +package com.example.SantanderTechnologies.payload; + +import com.fasterxml.jackson.annotation.JsonFormat; +import com.fasterxml.jackson.annotation.JsonProperty; + + +import java.math.BigDecimal; +import java.util.Date; + +public class CreditCardResponse extends ApiResponse{ + + @JsonProperty("descricao") + private String description; + + @JsonProperty("valor") + @JsonFormat(shape=JsonFormat.Shape.STRING) + private BigDecimal amount; + + @JsonProperty("codigousuario") + private Long userCode; + + @JsonProperty("data") + private Date date; + + public CreditCardResponse(Boolean success, String message) { + super(success, message); + } + + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } + + public BigDecimal getAmount() { + return amount; + } + + public void setAmount(BigDecimal amount) { + this.amount = amount; + } + + public Long getUserCode() { + return userCode; + } + + public void setUserCode(Long userCode) { + this.userCode = userCode; + } + + public Date getDate() { + return date; + } + + public void setDate(Date date) { + this.date = date; + } +} diff --git a/src/main/java/com/example/SantanderTechnologies/payload/EditSpendingRequest.java b/src/main/java/com/example/SantanderTechnologies/payload/EditSpendingRequest.java new file mode 100644 index 00000000..7cbdb77a --- /dev/null +++ b/src/main/java/com/example/SantanderTechnologies/payload/EditSpendingRequest.java @@ -0,0 +1,22 @@ +package com.example.SantanderTechnologies.payload; + +public class EditSpendingRequest { + private Long spendingId; + private String category; + + public Long getSpendingId() { + return spendingId; + } + + public void setSpendingId(Long spendingId) { + this.spendingId = spendingId; + } + + public String getCategory() { + return category; + } + + public void setCategory(String category) { + this.category = category; + } +} diff --git a/src/main/java/com/example/SantanderTechnologies/payload/JwtAuthenticationResponse.java b/src/main/java/com/example/SantanderTechnologies/payload/JwtAuthenticationResponse.java new file mode 100644 index 00000000..6e04fb86 --- /dev/null +++ b/src/main/java/com/example/SantanderTechnologies/payload/JwtAuthenticationResponse.java @@ -0,0 +1,29 @@ +package com.example.SantanderTechnologies.payload; + +/** + * Created by rajeevkumarsingh on 19/08/17. + */ +public class JwtAuthenticationResponse { + private String accessToken; + private String tokenType = "Bearer"; + + public JwtAuthenticationResponse(String accessToken) { + this.accessToken = accessToken; + } + + public String getAccessToken() { + return accessToken; + } + + public void setAccessToken(String accessToken) { + this.accessToken = accessToken; + } + + public String getTokenType() { + return tokenType; + } + + public void setTokenType(String tokenType) { + this.tokenType = tokenType; + } +} diff --git a/src/main/java/com/example/SantanderTechnologies/payload/LoginRequest.java b/src/main/java/com/example/SantanderTechnologies/payload/LoginRequest.java new file mode 100644 index 00000000..8c3ced67 --- /dev/null +++ b/src/main/java/com/example/SantanderTechnologies/payload/LoginRequest.java @@ -0,0 +1,30 @@ +package com.example.SantanderTechnologies.payload; + +import javax.validation.constraints.NotBlank; + +/** + * Created by rajeevkumarsingh on 02/08/17. + */ +public class LoginRequest { + @NotBlank + private String usernameOrEmail; + + @NotBlank + private String password; + + public String getUsernameOrEmail() { + return usernameOrEmail; + } + + public void setUsernameOrEmail(String usernameOrEmail) { + this.usernameOrEmail = usernameOrEmail; + } + + public String getPassword() { + return password; + } + + public void setPassword(String password) { + this.password = password; + } +} diff --git a/src/main/java/com/example/SantanderTechnologies/payload/PagedResponse.java b/src/main/java/com/example/SantanderTechnologies/payload/PagedResponse.java new file mode 100644 index 00000000..a4a2c864 --- /dev/null +++ b/src/main/java/com/example/SantanderTechnologies/payload/PagedResponse.java @@ -0,0 +1,74 @@ +package com.example.SantanderTechnologies.payload; + +import java.util.List; + +public class PagedResponse { + + private List content; + private int page; + private int size; + private long totalElements; + private int totalPages; + private boolean last; + + public PagedResponse() { + + } + + public PagedResponse(List content, int page, int size, long totalElements, int totalPages, boolean last) { + this.content = content; + this.page = page; + this.size = size; + this.totalElements = totalElements; + this.totalPages = totalPages; + this.last = last; + } + + public List getContent() { + return content; + } + + public void setContent(List content) { + this.content = content; + } + + public int getPage() { + return page; + } + + public void setPage(int page) { + this.page = page; + } + + public int getSize() { + return size; + } + + public void setSize(int size) { + this.size = size; + } + + public long getTotalElements() { + return totalElements; + } + + public void setTotalElements(long totalElements) { + this.totalElements = totalElements; + } + + public int getTotalPages() { + return totalPages; + } + + public void setTotalPages(int totalPages) { + this.totalPages = totalPages; + } + + public boolean isLast() { + return last; + } + + public void setLast(boolean last) { + this.last = last; + } +} diff --git a/src/main/java/com/example/SantanderTechnologies/payload/SignUpRequest.java b/src/main/java/com/example/SantanderTechnologies/payload/SignUpRequest.java new file mode 100644 index 00000000..5aea3dac --- /dev/null +++ b/src/main/java/com/example/SantanderTechnologies/payload/SignUpRequest.java @@ -0,0 +1,58 @@ +package com.example.SantanderTechnologies.payload; + +import javax.validation.constraints.*; + +/** + * Created by rajeevkumarsingh on 02/08/17. + */ + +public class SignUpRequest { + @NotBlank + @Size(min = 4, max = 40) + private String name; + + @NotBlank + @Size(min = 3, max = 15) + private String username; + + @NotBlank + @Size(max = 40) + @Email + private String email; + + @NotBlank + @Size(min = 6, max = 20) + private String password; + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getUsername() { + return username; + } + + public void setUsername(String username) { + this.username = username; + } + + public String getEmail() { + return email; + } + + public void setEmail(String email) { + this.email = email; + } + + public String getPassword() { + return password; + } + + public void setPassword(String password) { + this.password = password; + } +} diff --git a/src/main/java/com/example/SantanderTechnologies/payload/SpendingListResponse.java b/src/main/java/com/example/SantanderTechnologies/payload/SpendingListResponse.java new file mode 100644 index 00000000..43aa7404 --- /dev/null +++ b/src/main/java/com/example/SantanderTechnologies/payload/SpendingListResponse.java @@ -0,0 +1,12 @@ +package com.example.SantanderTechnologies.payload; + +import com.example.SantanderTechnologies.model.Spending; +import com.fasterxml.jackson.annotation.JsonProperty; + +import java.util.List; + +public class SpendingListResponse { + + @JsonProperty("listagemDeGastos") + private List spendingList; +} diff --git a/src/main/java/com/example/SantanderTechnologies/payload/SpendingRequest.java b/src/main/java/com/example/SantanderTechnologies/payload/SpendingRequest.java new file mode 100644 index 00000000..9618c0ae --- /dev/null +++ b/src/main/java/com/example/SantanderTechnologies/payload/SpendingRequest.java @@ -0,0 +1,71 @@ +package com.example.SantanderTechnologies.payload; + +import java.math.BigDecimal; +import java.util.Date; + +public class SpendingRequest { + + private String description; + private BigDecimal amount; + private String category; + private Date date; + + private String creditCardNumber; + + public SpendingRequest(){} + + public SpendingRequest(BigDecimal amount, String creditCardNumber) { + this.amount = amount; + this.creditCardNumber = creditCardNumber; + this.date = new Date(); + this.description = "Default Description"; + } + + public SpendingRequest(String description, BigDecimal amount, String category, Date date, String creditCardNumber) { + this.description = description; + this.amount = amount; + this.category = category; + this.date = date; + this.creditCardNumber = creditCardNumber; + } + + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } + + public BigDecimal getAmount() { + return amount; + } + + public void setAmount(BigDecimal amount) { + this.amount = amount; + } + + public String getCategory() { + return category; + } + + public void setCategory(String category) { + this.category = category; + } + + public Date getDate() { + return date; + } + + public void setDate(Date date) { + this.date = date; + } + + public String getCreditCardNumber() { + return creditCardNumber; + } + + public void setCreditCardNumber(String creditCardNumber) { + this.creditCardNumber = creditCardNumber; + } +} diff --git a/src/main/java/com/example/SantanderTechnologies/payload/UserIdentityAvailability.java b/src/main/java/com/example/SantanderTechnologies/payload/UserIdentityAvailability.java new file mode 100644 index 00000000..6d632aae --- /dev/null +++ b/src/main/java/com/example/SantanderTechnologies/payload/UserIdentityAvailability.java @@ -0,0 +1,17 @@ +package com.example.SantanderTechnologies.payload; + +public class UserIdentityAvailability { + private Boolean available; + + public UserIdentityAvailability(Boolean available) { + this.available = available; + } + + public Boolean getAvailable() { + return available; + } + + public void setAvailable(Boolean available) { + this.available = available; + } +} diff --git a/src/main/java/com/example/SantanderTechnologies/payload/UserProfile.java b/src/main/java/com/example/SantanderTechnologies/payload/UserProfile.java new file mode 100644 index 00000000..9d2bd5a2 --- /dev/null +++ b/src/main/java/com/example/SantanderTechnologies/payload/UserProfile.java @@ -0,0 +1,50 @@ +package com.example.SantanderTechnologies.payload; + +import java.time.Instant; + +public class UserProfile { + private Long id; + private String username; + private String name; + private Instant joinedAt; + + public UserProfile(Long id, String username, String name, Instant joinedAt) { + this.id = id; + this.username = username; + this.name = name; + this.joinedAt = joinedAt; + } + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public String getUsername() { + return username; + } + + public void setUsername(String username) { + this.username = username; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public Instant getJoinedAt() { + return joinedAt; + } + + public void setJoinedAt(Instant joinedAt) { + this.joinedAt = joinedAt; + } + +} diff --git a/src/main/java/com/example/SantanderTechnologies/payload/UserSummary.java b/src/main/java/com/example/SantanderTechnologies/payload/UserSummary.java new file mode 100644 index 00000000..53cc3fcf --- /dev/null +++ b/src/main/java/com/example/SantanderTechnologies/payload/UserSummary.java @@ -0,0 +1,37 @@ +package com.example.SantanderTechnologies.payload; + +public class UserSummary { + private Long id; + private String username; + private String name; + + public UserSummary(Long id, String username, String name) { + this.id = id; + this.username = username; + this.name = name; + } + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public String getUsername() { + return username; + } + + public void setUsername(String username) { + this.username = username; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } +} diff --git a/src/main/java/com/example/SantanderTechnologies/repository/CategoryRepository.java b/src/main/java/com/example/SantanderTechnologies/repository/CategoryRepository.java new file mode 100644 index 00000000..030394fa --- /dev/null +++ b/src/main/java/com/example/SantanderTechnologies/repository/CategoryRepository.java @@ -0,0 +1,11 @@ +package com.example.SantanderTechnologies.repository; + +import com.example.SantanderTechnologies.model.SpendingCategory; +import org.springframework.data.jpa.repository.JpaRepository; + +import java.util.Optional; + +public interface CategoryRepository extends JpaRepository { + + Optional findByCategoryName(String categoryName); +} diff --git a/src/main/java/com/example/SantanderTechnologies/repository/CreditCardRepository.java b/src/main/java/com/example/SantanderTechnologies/repository/CreditCardRepository.java new file mode 100644 index 00000000..d453ac40 --- /dev/null +++ b/src/main/java/com/example/SantanderTechnologies/repository/CreditCardRepository.java @@ -0,0 +1,18 @@ +package com.example.SantanderTechnologies.repository; + +import com.example.SantanderTechnologies.model.CreditCard; + +import org.springframework.data.jpa.repository.EntityGraph; +import org.springframework.data.jpa.repository.JpaRepository; + +import java.util.List; +import java.util.Optional; + +public interface CreditCardRepository extends JpaRepository { + + Optional findById(Long creditCardId); + + Optional findByNumber(String number); + + List findAllByUserId(Long userId); +} diff --git a/src/main/java/com/example/SantanderTechnologies/repository/RoleRepository.java b/src/main/java/com/example/SantanderTechnologies/repository/RoleRepository.java new file mode 100644 index 00000000..20a2f47e --- /dev/null +++ b/src/main/java/com/example/SantanderTechnologies/repository/RoleRepository.java @@ -0,0 +1,16 @@ +package com.example.SantanderTechnologies.repository; + +import com.example.SantanderTechnologies.model.Role; +import com.example.SantanderTechnologies.model.RoleName; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.stereotype.Repository; + +import java.util.Optional; + +/** + * Created by rajeevkumarsingh on 02/08/17. + */ +@Repository +public interface RoleRepository extends JpaRepository { + Optional findByName(RoleName roleName); +} diff --git a/src/main/java/com/example/SantanderTechnologies/repository/SpendingRepository.java b/src/main/java/com/example/SantanderTechnologies/repository/SpendingRepository.java new file mode 100644 index 00000000..5bc7fd24 --- /dev/null +++ b/src/main/java/com/example/SantanderTechnologies/repository/SpendingRepository.java @@ -0,0 +1,17 @@ +package com.example.SantanderTechnologies.repository; + +import com.example.SantanderTechnologies.model.Spending; +import org.springframework.data.jpa.repository.JpaRepository; + +import java.util.List; +import java.util.Optional; + +public interface SpendingRepository extends JpaRepository { + + Optional findById(Long spendingId); + + List findAllByCreditCardId(Long creditCardId); + + Optional findFirstByDescription(String description); + +} diff --git a/src/main/java/com/example/SantanderTechnologies/repository/UserRepository.java b/src/main/java/com/example/SantanderTechnologies/repository/UserRepository.java new file mode 100644 index 00000000..d2462c79 --- /dev/null +++ b/src/main/java/com/example/SantanderTechnologies/repository/UserRepository.java @@ -0,0 +1,27 @@ +package com.example.SantanderTechnologies.repository; + + +import com.example.SantanderTechnologies.model.User; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.stereotype.Repository; + +import java.util.List; +import java.util.Optional; + +/** + * Created by rajeevkumarsingh on 02/08/17. + */ +@Repository +public interface UserRepository extends JpaRepository { + Optional findByEmail(String email); + + Optional findByUsernameOrEmail(String username, String email); + + List findByIdIn(List userIds); + + Optional findByUsername(String username); + + Boolean existsByUsername(String username); + + Boolean existsByEmail(String email); +} diff --git a/src/main/java/com/example/SantanderTechnologies/security/CurrentUser.java b/src/main/java/com/example/SantanderTechnologies/security/CurrentUser.java new file mode 100644 index 00000000..13c89262 --- /dev/null +++ b/src/main/java/com/example/SantanderTechnologies/security/CurrentUser.java @@ -0,0 +1,13 @@ +package com.example.SantanderTechnologies.security; + +import org.springframework.security.core.annotation.AuthenticationPrincipal; + +import java.lang.annotation.*; + +@Target({ElementType.PARAMETER, ElementType.TYPE}) +@Retention(RetentionPolicy.RUNTIME) +@Documented +@AuthenticationPrincipal +public @interface CurrentUser { + +} diff --git a/src/main/java/com/example/SantanderTechnologies/security/CustomUserDetailsService.java b/src/main/java/com/example/SantanderTechnologies/security/CustomUserDetailsService.java new file mode 100644 index 00000000..9dff35be --- /dev/null +++ b/src/main/java/com/example/SantanderTechnologies/security/CustomUserDetailsService.java @@ -0,0 +1,44 @@ +package com.example.SantanderTechnologies.security; + +import com.example.SantanderTechnologies.exception.ResourceNotFoundException; +import com.example.SantanderTechnologies.model.User; +import com.example.SantanderTechnologies.repository.UserRepository; +import org.springframework.beans.factory.annotation.Autowired; +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 org.springframework.transaction.annotation.Transactional; + +/** + * Created by rajeevkumarsingh on 02/08/17. + */ + +@Service +public class CustomUserDetailsService implements UserDetailsService { + + @Autowired + UserRepository userRepository; + + @Override + @Transactional + public UserDetails loadUserByUsername(String usernameOrEmail) + throws UsernameNotFoundException { + // Let people login with either username or email + User user = userRepository.findByUsernameOrEmail(usernameOrEmail, usernameOrEmail) + .orElseThrow(() -> + new UsernameNotFoundException("User not found with username or email : " + usernameOrEmail) + ); + + return UserPrincipal.create(user); + } + + @Transactional + public UserDetails loadUserById(Long id) { + User user = userRepository.findById(id).orElseThrow( + () -> new ResourceNotFoundException("User", "id", id) + ); + + return UserPrincipal.create(user); + } +} \ No newline at end of file diff --git a/src/main/java/com/example/SantanderTechnologies/security/JwtAuthenticationEntryPoint.java b/src/main/java/com/example/SantanderTechnologies/security/JwtAuthenticationEntryPoint.java new file mode 100644 index 00000000..e66e72c4 --- /dev/null +++ b/src/main/java/com/example/SantanderTechnologies/security/JwtAuthenticationEntryPoint.java @@ -0,0 +1,28 @@ +package com.example.SantanderTechnologies.security; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.security.core.AuthenticationException; +import org.springframework.security.web.AuthenticationEntryPoint; +import org.springframework.stereotype.Component; + +import javax.servlet.ServletException; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import java.io.IOException; + +/** + * Created by rajeevkumarsingh on 07/12/17. + */ +@Component +public class JwtAuthenticationEntryPoint implements AuthenticationEntryPoint { + + private static final Logger logger = LoggerFactory.getLogger(JwtAuthenticationEntryPoint.class); + @Override + public void commence(HttpServletRequest httpServletRequest, + HttpServletResponse httpServletResponse, + AuthenticationException e) throws IOException, ServletException { + logger.error("Responding with unauthorized error. Message - {}", e.getMessage()); + httpServletResponse.sendError(HttpServletResponse.SC_UNAUTHORIZED, e.getMessage()); + } +} diff --git a/src/main/java/com/example/SantanderTechnologies/security/JwtAuthenticationFilter.java b/src/main/java/com/example/SantanderTechnologies/security/JwtAuthenticationFilter.java new file mode 100644 index 00000000..cd1fd7f9 --- /dev/null +++ b/src/main/java/com/example/SantanderTechnologies/security/JwtAuthenticationFilter.java @@ -0,0 +1,65 @@ +package com.example.SantanderTechnologies.security; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; +import org.springframework.security.core.context.SecurityContextHolder; +import org.springframework.security.core.userdetails.UserDetails; +import org.springframework.security.web.authentication.WebAuthenticationDetailsSource; +import org.springframework.util.StringUtils; +import org.springframework.web.filter.OncePerRequestFilter; + +import javax.servlet.FilterChain; +import javax.servlet.ServletException; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import java.io.IOException; + +/** + * Created by rajeevkumarsingh on 19/08/17. + */ +public class JwtAuthenticationFilter extends OncePerRequestFilter { + + @Autowired + private JwtTokenProvider tokenProvider; + + @Autowired + private CustomUserDetailsService customUserDetailsService; + + private static final Logger logger = LoggerFactory.getLogger(JwtAuthenticationFilter.class); + + @Override + protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException { + try { + String jwt = getJwtFromRequest(request); + + if (StringUtils.hasText(jwt) && tokenProvider.validateToken(jwt)) { + Long userId = tokenProvider.getUserIdFromJWT(jwt); + + /* + Note that you could also encode the user's username and roles inside JWT claims + and create the UserDetails object by parsing those claims from the JWT. + That would avoid the following database hit. It's completely up to you. + */ + UserDetails userDetails = customUserDetailsService.loadUserById(userId); + UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities()); + authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request)); + + SecurityContextHolder.getContext().setAuthentication(authentication); + } + } catch (Exception ex) { + logger.error("Could not set user authentication in security context", ex); + } + + filterChain.doFilter(request, response); + } + + private String getJwtFromRequest(HttpServletRequest request) { + String bearerToken = request.getHeader("Authorization"); + if (StringUtils.hasText(bearerToken) && bearerToken.startsWith("Bearer ")) { + return bearerToken.substring(7, bearerToken.length()); + } + return null; + } +} diff --git a/src/main/java/com/example/SantanderTechnologies/security/JwtTokenProvider.java b/src/main/java/com/example/SantanderTechnologies/security/JwtTokenProvider.java new file mode 100644 index 00000000..0ba8231b --- /dev/null +++ b/src/main/java/com/example/SantanderTechnologies/security/JwtTokenProvider.java @@ -0,0 +1,67 @@ +package com.example.SantanderTechnologies.security; + +import io.jsonwebtoken.*; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.security.core.Authentication; +import org.springframework.stereotype.Component; + +import java.util.Date; + +/** + * Created by rajeevkumarsingh on 19/08/17. + */ +@Component +public class JwtTokenProvider { + + private static final Logger logger = LoggerFactory.getLogger(JwtTokenProvider.class); + + @Value("${app.jwtSecret}") + private String jwtSecret; + + @Value("${app.jwtExpirationInMs}") + private int jwtExpirationInMs; + + public String generateToken(Authentication authentication) { + + UserPrincipal userPrincipal = (UserPrincipal) authentication.getPrincipal(); + + Date now = new Date(); + Date expiryDate = new Date(now.getTime() + jwtExpirationInMs); + + return Jwts.builder() + .setSubject(Long.toString(userPrincipal.getId())) + .setIssuedAt(new Date()) + .setExpiration(expiryDate) + .signWith(SignatureAlgorithm.HS512, jwtSecret) + .compact(); + } + + public Long getUserIdFromJWT(String token) { + Claims claims = Jwts.parser() + .setSigningKey(jwtSecret) + .parseClaimsJws(token) + .getBody(); + + return Long.parseLong(claims.getSubject()); + } + + public boolean validateToken(String authToken) { + try { + Jwts.parser().setSigningKey(jwtSecret).parseClaimsJws(authToken); + return true; + } catch (SignatureException ex) { + logger.error("Invalid JWT signature"); + } catch (MalformedJwtException ex) { + logger.error("Invalid JWT token"); + } catch (ExpiredJwtException ex) { + logger.error("Expired JWT token"); + } catch (UnsupportedJwtException ex) { + logger.error("Unsupported JWT token"); + } catch (IllegalArgumentException ex) { + logger.error("JWT claims string is empty."); + } + return false; + } +} diff --git a/src/main/java/com/example/SantanderTechnologies/security/UserPrincipal.java b/src/main/java/com/example/SantanderTechnologies/security/UserPrincipal.java new file mode 100644 index 00000000..931474bd --- /dev/null +++ b/src/main/java/com/example/SantanderTechnologies/security/UserPrincipal.java @@ -0,0 +1,113 @@ +package com.example.SantanderTechnologies.security; + +import com.example.SantanderTechnologies.model.User; +import com.fasterxml.jackson.annotation.JsonIgnore; +import org.springframework.security.core.GrantedAuthority; +import org.springframework.security.core.authority.SimpleGrantedAuthority; +import org.springframework.security.core.userdetails.UserDetails; + +import java.util.Collection; +import java.util.List; +import java.util.Objects; +import java.util.stream.Collectors; + +public class UserPrincipal implements UserDetails { + private Long id; + + private String name; + + private String username; + + @JsonIgnore + private String email; + + @JsonIgnore + private String password; + + private Collection authorities; + + public UserPrincipal(Long id, String name, String username, String email, String password, Collection authorities) { + this.id = id; + this.name = name; + this.username = username; + this.email = email; + this.password = password; + this.authorities = authorities; + } + + public static UserPrincipal create(User user) { + List authorities = user.getRoles().stream().map(role -> + new SimpleGrantedAuthority(role.getName().name()) + ).collect(Collectors.toList()); + + return new UserPrincipal( + user.getId(), + user.getName(), + user.getUsername(), + user.getEmail(), + user.getPassword(), + authorities + ); + } + + public Long getId() { + return id; + } + + public String getName() { + return name; + } + + public String getEmail() { + return email; + } + + @Override + public String getUsername() { + return username; + } + + @Override + public String getPassword() { + return password; + } + + @Override + public Collection getAuthorities() { + return authorities; + } + + @Override + public boolean isAccountNonExpired() { + return true; + } + + @Override + public boolean isAccountNonLocked() { + return true; + } + + @Override + public boolean isCredentialsNonExpired() { + return true; + } + + @Override + public boolean isEnabled() { + return true; + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + UserPrincipal that = (UserPrincipal) o; + return Objects.equals(id, that.id); + } + + @Override + public int hashCode() { + + return Objects.hash(id); + } +} diff --git a/src/main/java/com/example/SantanderTechnologies/util/AppConstants.java b/src/main/java/com/example/SantanderTechnologies/util/AppConstants.java new file mode 100644 index 00000000..a2042ecc --- /dev/null +++ b/src/main/java/com/example/SantanderTechnologies/util/AppConstants.java @@ -0,0 +1,8 @@ +package com.example.SantanderTechnologies.util; + +public interface AppConstants { + String DEFAULT_PAGE_NUMBER = "0"; + String DEFAULT_PAGE_SIZE = "30"; + + int MAX_PAGE_SIZE = 50; +} diff --git a/src/main/resources/application.properties b/src/main/resources/application.properties new file mode 100644 index 00000000..189f92af --- /dev/null +++ b/src/main/resources/application.properties @@ -0,0 +1,29 @@ +## Server Properties +server.port= 8080 +server.compression.enabled=true + +spring.datasource.url=jdbc:mysql://localhost:3306/test?useSSL=false +spring.datasource.username=root +spring.datasource.password=password + +## Hibernate Properties +# The SQL dialect makes Hibernate generate better SQL for the chosen database +spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5InnoDBDialect +spring.jpa.hibernate.ddl-auto = update + +## Hibernate Logging +logging.level.org.hibernate.SQL= DEBUG + +# Initialize the datasource with available DDL and DML scripts +spring.datasource.initialization-mode=always + +## Jackson Properties +spring.jackson.serialization.WRITE_DATES_AS_TIMESTAMPS= false +spring.jackson.time-zone= UTC + +## App Properties +app.jwtSecret= JWTSuperSecretKey +app.jwtExpirationInMs = 604800000 + +## Spring Profiles +# spring.profiles.active=prod \ No newline at end of file diff --git a/src/main/resources/data.sql b/src/main/resources/data.sql new file mode 100644 index 00000000..9d393b4c --- /dev/null +++ b/src/main/resources/data.sql @@ -0,0 +1,2 @@ +INSERT IGNORE INTO roles(name) VALUES('ROLE_USER'); +INSERT IGNORE INTO roles(name) VALUES('ROLE_ADMIN'); \ No newline at end of file diff --git a/src/test/java/com/example/SantanderTechnologies/SantanderTechnologiesApplicationTests.java b/src/test/java/com/example/SantanderTechnologies/SantanderTechnologiesApplicationTests.java new file mode 100644 index 00000000..e2956e98 --- /dev/null +++ b/src/test/java/com/example/SantanderTechnologies/SantanderTechnologiesApplicationTests.java @@ -0,0 +1,16 @@ +package com.example.SantanderTechnologies; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +@RunWith(SpringRunner.class) +@SpringBootTest +public class SantanderTechnologiesApplicationTests { + + @Test + public void contextLoads() { + } + +}