Selaa lähdekoodia

Initial commit

Fabio Dalle Ave 3 kuukautta sitten
vanhempi
commit
5df65b4dca
71 muutettua tiedostoa jossa 3664 lisäystä ja 10 poistoa
  1. 2 0
      .gitattributes
  2. 29 10
      .gitignore
  3. 3 0
      .mvn/wrapper/maven-wrapper.properties
  4. 295 0
      mvnw
  5. 189 0
      mvnw.cmd
  6. 196 0
      pom.xml
  7. 46 0
      src/main/java/it/bgates/remotebe/RemoteBeApplication.java
  8. 85 0
      src/main/java/it/bgates/remotebe/config/BGatesUserDetailService.java
  9. 75 0
      src/main/java/it/bgates/remotebe/config/BGatesUserDetails.java
  10. 90 0
      src/main/java/it/bgates/remotebe/config/JwtAuthenticationFilter.java
  11. 104 0
      src/main/java/it/bgates/remotebe/config/JwtService.java
  12. 40 0
      src/main/java/it/bgates/remotebe/config/LogoutService.java
  13. 95 0
      src/main/java/it/bgates/remotebe/config/SecurityConfig.java
  14. 64 0
      src/main/java/it/bgates/remotebe/controller/CustomerController.java
  15. 65 0
      src/main/java/it/bgates/remotebe/controller/DeviceController.java
  16. 61 0
      src/main/java/it/bgates/remotebe/controller/DistributorController.java
  17. 46 0
      src/main/java/it/bgates/remotebe/controller/InstallerController.java
  18. 76 0
      src/main/java/it/bgates/remotebe/controller/PhoneController.java
  19. 90 0
      src/main/java/it/bgates/remotebe/controller/UserController.java
  20. 78 0
      src/main/java/it/bgates/remotebe/controller/auth/AuthController.java
  21. 16 0
      src/main/java/it/bgates/remotebe/controller/auth/beans/AuthenticationRequest.java
  22. 24 0
      src/main/java/it/bgates/remotebe/controller/auth/beans/AuthenticationResponse.java
  23. 25 0
      src/main/java/it/bgates/remotebe/controller/auth/beans/NewUserBean.java
  24. 15 0
      src/main/java/it/bgates/remotebe/controller/auth/beans/RefreshTokenRequest.java
  25. 21 0
      src/main/java/it/bgates/remotebe/controller/auth/beans/RegisterRequest.java
  26. 8 0
      src/main/java/it/bgates/remotebe/controller/beans/FilterBean.java
  27. 42 0
      src/main/java/it/bgates/remotebe/entities/Customer.java
  28. 78 0
      src/main/java/it/bgates/remotebe/entities/Device.java
  29. 48 0
      src/main/java/it/bgates/remotebe/entities/Distributor.java
  30. 69 0
      src/main/java/it/bgates/remotebe/entities/Installer.java
  31. 19 0
      src/main/java/it/bgates/remotebe/entities/Owner.java
  32. 44 0
      src/main/java/it/bgates/remotebe/entities/Phone.java
  33. 48 0
      src/main/java/it/bgates/remotebe/entities/Privilege.java
  34. 76 0
      src/main/java/it/bgates/remotebe/entities/Role.java
  35. 56 0
      src/main/java/it/bgates/remotebe/entities/User.java
  36. 24 0
      src/main/java/it/bgates/remotebe/entities/base/Person.java
  37. 8 0
      src/main/java/it/bgates/remotebe/entities/enums/BGatesUserType.java
  38. 6 0
      src/main/java/it/bgates/remotebe/entities/enums/CustomerType.java
  39. 12 0
      src/main/java/it/bgates/remotebe/entities/enums/DeviceType.java
  40. 25 0
      src/main/java/it/bgates/remotebe/entities/token/RefreshToken.java
  41. 13 0
      src/main/java/it/bgates/remotebe/entities/token/RefreshTokenRepository.java
  42. 30 0
      src/main/java/it/bgates/remotebe/entities/token/Token.java
  43. 16 0
      src/main/java/it/bgates/remotebe/entities/token/TokenRepository.java
  44. 8 0
      src/main/java/it/bgates/remotebe/exception/AutorizationMissingException.java
  45. 8 0
      src/main/java/it/bgates/remotebe/exception/BadCredentialsException.java
  46. 8 0
      src/main/java/it/bgates/remotebe/exception/DisabledUserException.java
  47. 7 0
      src/main/java/it/bgates/remotebe/exception/NotFoundException.java
  48. 7 0
      src/main/java/it/bgates/remotebe/exception/PermissionDeniedException.java
  49. 8 0
      src/main/java/it/bgates/remotebe/exception/UserNotFoundException.java
  50. 36 0
      src/main/java/it/bgates/remotebe/repository/CustomerRepository.java
  51. 21 0
      src/main/java/it/bgates/remotebe/repository/DeviceRepository.java
  52. 11 0
      src/main/java/it/bgates/remotebe/repository/DistributorRepository.java
  53. 16 0
      src/main/java/it/bgates/remotebe/repository/InstallerRepository.java
  54. 12 0
      src/main/java/it/bgates/remotebe/repository/PhoneRepository.java
  55. 15 0
      src/main/java/it/bgates/remotebe/repository/UserRepository.java
  56. 91 0
      src/main/java/it/bgates/remotebe/service/BaseService.java
  57. 73 0
      src/main/java/it/bgates/remotebe/service/CustomerService.java
  58. 134 0
      src/main/java/it/bgates/remotebe/service/DeviceService.java
  59. 107 0
      src/main/java/it/bgates/remotebe/service/DistributorService.java
  60. 33 0
      src/main/java/it/bgates/remotebe/service/InstallerService.java
  61. 127 0
      src/main/java/it/bgates/remotebe/service/PhoneService.java
  62. 9 0
      src/main/java/it/bgates/remotebe/service/QueryParameter.java
  63. 140 0
      src/main/java/it/bgates/remotebe/service/UserService.java
  64. 177 0
      src/main/java/it/bgates/remotebe/service/auth/AuthService.java
  65. 47 0
      src/main/java/it/bgates/remotebe/service/auth/RefreshTokenService.java
  66. 28 0
      src/main/resources/app.key
  67. 9 0
      src/main/resources/app.pub
  68. 25 0
      src/main/resources/application-dev.properties
  69. 26 0
      src/main/resources/application-prod.properties
  70. 16 0
      src/main/resources/application.properties
  71. 13 0
      src/test/java/it/bgates/remotebe/RemoteBeApplicationTests.java

+ 2 - 0
.gitattributes

@@ -0,0 +1,2 @@
+/mvnw text eol=lf
+*.cmd text eol=crlf

+ 29 - 10
.gitignore

@@ -1,14 +1,33 @@
-# ---> Java
-*.class
+HELP.md
+target/
+.mvn/wrapper/maven-wrapper.jar
+!**/src/main/**/target/
+!**/src/test/**/target/
 
-# Mobile Tools for Java (J2ME)
-.mtj.tmp/
+### STS ###
+.apt_generated
+.classpath
+.factorypath
+.project
+.settings
+.springBeans
+.sts4-cache
 
-# Package Files #
-*.jar
-*.war
-*.ear
+### IntelliJ IDEA ###
+.idea
+*.iws
+*.iml
+*.ipr
 
-# virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml
-hs_err_pid*
+### NetBeans ###
+/nbproject/private/
+/nbbuild/
+/dist/
+/nbdist/
+/.nb-gradle/
+build/
+!**/src/main/**/build/
+!**/src/test/**/build/
 
+### VS Code ###
+.vscode/

+ 3 - 0
.mvn/wrapper/maven-wrapper.properties

@@ -0,0 +1,3 @@
+wrapperVersion=3.3.4
+distributionType=only-script
+distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.9.11/apache-maven-3.9.11-bin.zip

+ 295 - 0
mvnw

@@ -0,0 +1,295 @@
+#!/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
+#
+#    http://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.
+# ----------------------------------------------------------------------------
+
+# ----------------------------------------------------------------------------
+# Apache Maven Wrapper startup batch script, version 3.3.4
+#
+# Optional ENV vars
+# -----------------
+#   JAVA_HOME - location of a JDK home dir, required when download maven via java source
+#   MVNW_REPOURL - repo url base for downloading maven distribution
+#   MVNW_USERNAME/MVNW_PASSWORD - user and password for downloading maven
+#   MVNW_VERBOSE - true: enable verbose log; debug: trace the mvnw script; others: silence the output
+# ----------------------------------------------------------------------------
+
+set -euf
+[ "${MVNW_VERBOSE-}" != debug ] || set -x
+
+# OS specific support.
+native_path() { printf %s\\n "$1"; }
+case "$(uname)" in
+CYGWIN* | MINGW*)
+  [ -z "${JAVA_HOME-}" ] || JAVA_HOME="$(cygpath --unix "$JAVA_HOME")"
+  native_path() { cygpath --path --windows "$1"; }
+  ;;
+esac
+
+# set JAVACMD and JAVACCMD
+set_java_home() {
+  # For Cygwin and MinGW, ensure paths are in Unix format before anything is touched
+  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"
+      JAVACCMD="$JAVA_HOME/jre/sh/javac"
+    else
+      JAVACMD="$JAVA_HOME/bin/java"
+      JAVACCMD="$JAVA_HOME/bin/javac"
+
+      if [ ! -x "$JAVACMD" ] || [ ! -x "$JAVACCMD" ]; then
+        echo "The JAVA_HOME environment variable is not defined correctly, so mvnw cannot run." >&2
+        echo "JAVA_HOME is set to \"$JAVA_HOME\", but \"\$JAVA_HOME/bin/java\" or \"\$JAVA_HOME/bin/javac\" does not exist." >&2
+        return 1
+      fi
+    fi
+  else
+    JAVACMD="$(
+      'set' +e
+      'unset' -f command 2>/dev/null
+      'command' -v java
+    )" || :
+    JAVACCMD="$(
+      'set' +e
+      'unset' -f command 2>/dev/null
+      'command' -v javac
+    )" || :
+
+    if [ ! -x "${JAVACMD-}" ] || [ ! -x "${JAVACCMD-}" ]; then
+      echo "The java/javac command does not exist in PATH nor is JAVA_HOME set, so mvnw cannot run." >&2
+      return 1
+    fi
+  fi
+}
+
+# hash string like Java String::hashCode
+hash_string() {
+  str="${1:-}" h=0
+  while [ -n "$str" ]; do
+    char="${str%"${str#?}"}"
+    h=$(((h * 31 + $(LC_CTYPE=C printf %d "'$char")) % 4294967296))
+    str="${str#?}"
+  done
+  printf %x\\n $h
+}
+
+verbose() { :; }
+[ "${MVNW_VERBOSE-}" != true ] || verbose() { printf %s\\n "${1-}"; }
+
+die() {
+  printf %s\\n "$1" >&2
+  exit 1
+}
+
+trim() {
+  # MWRAPPER-139:
+  #   Trims trailing and leading whitespace, carriage returns, tabs, and linefeeds.
+  #   Needed for removing poorly interpreted newline sequences when running in more
+  #   exotic environments such as mingw bash on Windows.
+  printf "%s" "${1}" | tr -d '[:space:]'
+}
+
+scriptDir="$(dirname "$0")"
+scriptName="$(basename "$0")"
+
+# parse distributionUrl and optional distributionSha256Sum, requires .mvn/wrapper/maven-wrapper.properties
+while IFS="=" read -r key value; do
+  case "${key-}" in
+  distributionUrl) distributionUrl=$(trim "${value-}") ;;
+  distributionSha256Sum) distributionSha256Sum=$(trim "${value-}") ;;
+  esac
+done <"$scriptDir/.mvn/wrapper/maven-wrapper.properties"
+[ -n "${distributionUrl-}" ] || die "cannot read distributionUrl property in $scriptDir/.mvn/wrapper/maven-wrapper.properties"
+
+case "${distributionUrl##*/}" in
+maven-mvnd-*bin.*)
+  MVN_CMD=mvnd.sh _MVNW_REPO_PATTERN=/maven/mvnd/
+  case "${PROCESSOR_ARCHITECTURE-}${PROCESSOR_ARCHITEW6432-}:$(uname -a)" in
+  *AMD64:CYGWIN* | *AMD64:MINGW*) distributionPlatform=windows-amd64 ;;
+  :Darwin*x86_64) distributionPlatform=darwin-amd64 ;;
+  :Darwin*arm64) distributionPlatform=darwin-aarch64 ;;
+  :Linux*x86_64*) distributionPlatform=linux-amd64 ;;
+  *)
+    echo "Cannot detect native platform for mvnd on $(uname)-$(uname -m), use pure java version" >&2
+    distributionPlatform=linux-amd64
+    ;;
+  esac
+  distributionUrl="${distributionUrl%-bin.*}-$distributionPlatform.zip"
+  ;;
+maven-mvnd-*) MVN_CMD=mvnd.sh _MVNW_REPO_PATTERN=/maven/mvnd/ ;;
+*) MVN_CMD="mvn${scriptName#mvnw}" _MVNW_REPO_PATTERN=/org/apache/maven/ ;;
+esac
+
+# apply MVNW_REPOURL and calculate MAVEN_HOME
+# maven home pattern: ~/.m2/wrapper/dists/{apache-maven-<version>,maven-mvnd-<version>-<platform>}/<hash>
+[ -z "${MVNW_REPOURL-}" ] || distributionUrl="$MVNW_REPOURL$_MVNW_REPO_PATTERN${distributionUrl#*"$_MVNW_REPO_PATTERN"}"
+distributionUrlName="${distributionUrl##*/}"
+distributionUrlNameMain="${distributionUrlName%.*}"
+distributionUrlNameMain="${distributionUrlNameMain%-bin}"
+MAVEN_USER_HOME="${MAVEN_USER_HOME:-${HOME}/.m2}"
+MAVEN_HOME="${MAVEN_USER_HOME}/wrapper/dists/${distributionUrlNameMain-}/$(hash_string "$distributionUrl")"
+
+exec_maven() {
+  unset MVNW_VERBOSE MVNW_USERNAME MVNW_PASSWORD MVNW_REPOURL || :
+  exec "$MAVEN_HOME/bin/$MVN_CMD" "$@" || die "cannot exec $MAVEN_HOME/bin/$MVN_CMD"
+}
+
+if [ -d "$MAVEN_HOME" ]; then
+  verbose "found existing MAVEN_HOME at $MAVEN_HOME"
+  exec_maven "$@"
+fi
+
+case "${distributionUrl-}" in
+*?-bin.zip | *?maven-mvnd-?*-?*.zip) ;;
+*) die "distributionUrl is not valid, must match *-bin.zip or maven-mvnd-*.zip, but found '${distributionUrl-}'" ;;
+esac
+
+# prepare tmp dir
+if TMP_DOWNLOAD_DIR="$(mktemp -d)" && [ -d "$TMP_DOWNLOAD_DIR" ]; then
+  clean() { rm -rf -- "$TMP_DOWNLOAD_DIR"; }
+  trap clean HUP INT TERM EXIT
+else
+  die "cannot create temp dir"
+fi
+
+mkdir -p -- "${MAVEN_HOME%/*}"
+
+# Download and Install Apache Maven
+verbose "Couldn't find MAVEN_HOME, downloading and installing it ..."
+verbose "Downloading from: $distributionUrl"
+verbose "Downloading to: $TMP_DOWNLOAD_DIR/$distributionUrlName"
+
+# select .zip or .tar.gz
+if ! command -v unzip >/dev/null; then
+  distributionUrl="${distributionUrl%.zip}.tar.gz"
+  distributionUrlName="${distributionUrl##*/}"
+fi
+
+# verbose opt
+__MVNW_QUIET_WGET=--quiet __MVNW_QUIET_CURL=--silent __MVNW_QUIET_UNZIP=-q __MVNW_QUIET_TAR=''
+[ "${MVNW_VERBOSE-}" != true ] || __MVNW_QUIET_WGET='' __MVNW_QUIET_CURL='' __MVNW_QUIET_UNZIP='' __MVNW_QUIET_TAR=v
+
+# normalize http auth
+case "${MVNW_PASSWORD:+has-password}" in
+'') MVNW_USERNAME='' MVNW_PASSWORD='' ;;
+has-password) [ -n "${MVNW_USERNAME-}" ] || MVNW_USERNAME='' MVNW_PASSWORD='' ;;
+esac
+
+if [ -z "${MVNW_USERNAME-}" ] && command -v wget >/dev/null; then
+  verbose "Found wget ... using wget"
+  wget ${__MVNW_QUIET_WGET:+"$__MVNW_QUIET_WGET"} "$distributionUrl" -O "$TMP_DOWNLOAD_DIR/$distributionUrlName" || die "wget: Failed to fetch $distributionUrl"
+elif [ -z "${MVNW_USERNAME-}" ] && command -v curl >/dev/null; then
+  verbose "Found curl ... using curl"
+  curl ${__MVNW_QUIET_CURL:+"$__MVNW_QUIET_CURL"} -f -L -o "$TMP_DOWNLOAD_DIR/$distributionUrlName" "$distributionUrl" || die "curl: Failed to fetch $distributionUrl"
+elif set_java_home; then
+  verbose "Falling back to use Java to download"
+  javaSource="$TMP_DOWNLOAD_DIR/Downloader.java"
+  targetZip="$TMP_DOWNLOAD_DIR/$distributionUrlName"
+  cat >"$javaSource" <<-END
+	public class Downloader extends java.net.Authenticator
+	{
+	  protected java.net.PasswordAuthentication getPasswordAuthentication()
+	  {
+	    return new java.net.PasswordAuthentication( System.getenv( "MVNW_USERNAME" ), System.getenv( "MVNW_PASSWORD" ).toCharArray() );
+	  }
+	  public static void main( String[] args ) throws Exception
+	  {
+	    setDefault( new Downloader() );
+	    java.nio.file.Files.copy( java.net.URI.create( args[0] ).toURL().openStream(), java.nio.file.Paths.get( args[1] ).toAbsolutePath().normalize() );
+	  }
+	}
+	END
+  # For Cygwin/MinGW, switch paths to Windows format before running javac and java
+  verbose " - Compiling Downloader.java ..."
+  "$(native_path "$JAVACCMD")" "$(native_path "$javaSource")" || die "Failed to compile Downloader.java"
+  verbose " - Running Downloader.java ..."
+  "$(native_path "$JAVACMD")" -cp "$(native_path "$TMP_DOWNLOAD_DIR")" Downloader "$distributionUrl" "$(native_path "$targetZip")"
+fi
+
+# If specified, validate the SHA-256 sum of the Maven distribution zip file
+if [ -n "${distributionSha256Sum-}" ]; then
+  distributionSha256Result=false
+  if [ "$MVN_CMD" = mvnd.sh ]; then
+    echo "Checksum validation is not supported for maven-mvnd." >&2
+    echo "Please disable validation by removing 'distributionSha256Sum' from your maven-wrapper.properties." >&2
+    exit 1
+  elif command -v sha256sum >/dev/null; then
+    if echo "$distributionSha256Sum  $TMP_DOWNLOAD_DIR/$distributionUrlName" | sha256sum -c - >/dev/null 2>&1; then
+      distributionSha256Result=true
+    fi
+  elif command -v shasum >/dev/null; then
+    if echo "$distributionSha256Sum  $TMP_DOWNLOAD_DIR/$distributionUrlName" | shasum -a 256 -c >/dev/null 2>&1; then
+      distributionSha256Result=true
+    fi
+  else
+    echo "Checksum validation was requested but neither 'sha256sum' or 'shasum' are available." >&2
+    echo "Please install either command, or disable validation by removing 'distributionSha256Sum' from your maven-wrapper.properties." >&2
+    exit 1
+  fi
+  if [ $distributionSha256Result = false ]; then
+    echo "Error: Failed to validate Maven distribution SHA-256, your Maven distribution might be compromised." >&2
+    echo "If you updated your Maven version, you need to update the specified distributionSha256Sum property." >&2
+    exit 1
+  fi
+fi
+
+# unzip and move
+if command -v unzip >/dev/null; then
+  unzip ${__MVNW_QUIET_UNZIP:+"$__MVNW_QUIET_UNZIP"} "$TMP_DOWNLOAD_DIR/$distributionUrlName" -d "$TMP_DOWNLOAD_DIR" || die "failed to unzip"
+else
+  tar xzf${__MVNW_QUIET_TAR:+"$__MVNW_QUIET_TAR"} "$TMP_DOWNLOAD_DIR/$distributionUrlName" -C "$TMP_DOWNLOAD_DIR" || die "failed to untar"
+fi
+
+# Find the actual extracted directory name (handles snapshots where filename != directory name)
+actualDistributionDir=""
+
+# First try the expected directory name (for regular distributions)
+if [ -d "$TMP_DOWNLOAD_DIR/$distributionUrlNameMain" ]; then
+  if [ -f "$TMP_DOWNLOAD_DIR/$distributionUrlNameMain/bin/$MVN_CMD" ]; then
+    actualDistributionDir="$distributionUrlNameMain"
+  fi
+fi
+
+# If not found, search for any directory with the Maven executable (for snapshots)
+if [ -z "$actualDistributionDir" ]; then
+  # enable globbing to iterate over items
+  set +f
+  for dir in "$TMP_DOWNLOAD_DIR"/*; do
+    if [ -d "$dir" ]; then
+      if [ -f "$dir/bin/$MVN_CMD" ]; then
+        actualDistributionDir="$(basename "$dir")"
+        break
+      fi
+    fi
+  done
+  set -f
+fi
+
+if [ -z "$actualDistributionDir" ]; then
+  verbose "Contents of $TMP_DOWNLOAD_DIR:"
+  verbose "$(ls -la "$TMP_DOWNLOAD_DIR")"
+  die "Could not find Maven distribution directory in extracted archive"
+fi
+
+verbose "Found extracted Maven distribution directory: $actualDistributionDir"
+printf %s\\n "$distributionUrl" >"$TMP_DOWNLOAD_DIR/$actualDistributionDir/mvnw.url"
+mv -- "$TMP_DOWNLOAD_DIR/$actualDistributionDir" "$MAVEN_HOME" || [ -d "$MAVEN_HOME" ] || die "fail to move MAVEN_HOME"
+
+clean || :
+exec_maven "$@"

+ 189 - 0
mvnw.cmd

@@ -0,0 +1,189 @@
+<# : batch portion
+@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    http://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 Apache Maven Wrapper startup batch script, version 3.3.4
+@REM
+@REM Optional ENV vars
+@REM   MVNW_REPOURL - repo url base for downloading maven distribution
+@REM   MVNW_USERNAME/MVNW_PASSWORD - user and password for downloading maven
+@REM   MVNW_VERBOSE - true: enable verbose log; others: silence the output
+@REM ----------------------------------------------------------------------------
+
+@IF "%__MVNW_ARG0_NAME__%"=="" (SET __MVNW_ARG0_NAME__=%~nx0)
+@SET __MVNW_CMD__=
+@SET __MVNW_ERROR__=
+@SET __MVNW_PSMODULEP_SAVE=%PSModulePath%
+@SET PSModulePath=
+@FOR /F "usebackq tokens=1* delims==" %%A IN (`powershell -noprofile "& {$scriptDir='%~dp0'; $script='%__MVNW_ARG0_NAME__%'; icm -ScriptBlock ([Scriptblock]::Create((Get-Content -Raw '%~f0'))) -NoNewScope}"`) DO @(
+  IF "%%A"=="MVN_CMD" (set __MVNW_CMD__=%%B) ELSE IF "%%B"=="" (echo %%A) ELSE (echo %%A=%%B)
+)
+@SET PSModulePath=%__MVNW_PSMODULEP_SAVE%
+@SET __MVNW_PSMODULEP_SAVE=
+@SET __MVNW_ARG0_NAME__=
+@SET MVNW_USERNAME=
+@SET MVNW_PASSWORD=
+@IF NOT "%__MVNW_CMD__%"=="" ("%__MVNW_CMD__%" %*)
+@echo Cannot start maven from wrapper >&2 && exit /b 1
+@GOTO :EOF
+: end batch / begin powershell #>
+
+$ErrorActionPreference = "Stop"
+if ($env:MVNW_VERBOSE -eq "true") {
+  $VerbosePreference = "Continue"
+}
+
+# calculate distributionUrl, requires .mvn/wrapper/maven-wrapper.properties
+$distributionUrl = (Get-Content -Raw "$scriptDir/.mvn/wrapper/maven-wrapper.properties" | ConvertFrom-StringData).distributionUrl
+if (!$distributionUrl) {
+  Write-Error "cannot read distributionUrl property in $scriptDir/.mvn/wrapper/maven-wrapper.properties"
+}
+
+switch -wildcard -casesensitive ( $($distributionUrl -replace '^.*/','') ) {
+  "maven-mvnd-*" {
+    $USE_MVND = $true
+    $distributionUrl = $distributionUrl -replace '-bin\.[^.]*$',"-windows-amd64.zip"
+    $MVN_CMD = "mvnd.cmd"
+    break
+  }
+  default {
+    $USE_MVND = $false
+    $MVN_CMD = $script -replace '^mvnw','mvn'
+    break
+  }
+}
+
+# apply MVNW_REPOURL and calculate MAVEN_HOME
+# maven home pattern: ~/.m2/wrapper/dists/{apache-maven-<version>,maven-mvnd-<version>-<platform>}/<hash>
+if ($env:MVNW_REPOURL) {
+  $MVNW_REPO_PATTERN = if ($USE_MVND -eq $False) { "/org/apache/maven/" } else { "/maven/mvnd/" }
+  $distributionUrl = "$env:MVNW_REPOURL$MVNW_REPO_PATTERN$($distributionUrl -replace "^.*$MVNW_REPO_PATTERN",'')"
+}
+$distributionUrlName = $distributionUrl -replace '^.*/',''
+$distributionUrlNameMain = $distributionUrlName -replace '\.[^.]*$','' -replace '-bin$',''
+
+$MAVEN_M2_PATH = "$HOME/.m2"
+if ($env:MAVEN_USER_HOME) {
+  $MAVEN_M2_PATH = "$env:MAVEN_USER_HOME"
+}
+
+if (-not (Test-Path -Path $MAVEN_M2_PATH)) {
+    New-Item -Path $MAVEN_M2_PATH -ItemType Directory | Out-Null
+}
+
+$MAVEN_WRAPPER_DISTS = $null
+if ((Get-Item $MAVEN_M2_PATH).Target[0] -eq $null) {
+  $MAVEN_WRAPPER_DISTS = "$MAVEN_M2_PATH/wrapper/dists"
+} else {
+  $MAVEN_WRAPPER_DISTS = (Get-Item $MAVEN_M2_PATH).Target[0] + "/wrapper/dists"
+}
+
+$MAVEN_HOME_PARENT = "$MAVEN_WRAPPER_DISTS/$distributionUrlNameMain"
+$MAVEN_HOME_NAME = ([System.Security.Cryptography.SHA256]::Create().ComputeHash([byte[]][char[]]$distributionUrl) | ForEach-Object {$_.ToString("x2")}) -join ''
+$MAVEN_HOME = "$MAVEN_HOME_PARENT/$MAVEN_HOME_NAME"
+
+if (Test-Path -Path "$MAVEN_HOME" -PathType Container) {
+  Write-Verbose "found existing MAVEN_HOME at $MAVEN_HOME"
+  Write-Output "MVN_CMD=$MAVEN_HOME/bin/$MVN_CMD"
+  exit $?
+}
+
+if (! $distributionUrlNameMain -or ($distributionUrlName -eq $distributionUrlNameMain)) {
+  Write-Error "distributionUrl is not valid, must end with *-bin.zip, but found $distributionUrl"
+}
+
+# prepare tmp dir
+$TMP_DOWNLOAD_DIR_HOLDER = New-TemporaryFile
+$TMP_DOWNLOAD_DIR = New-Item -Itemtype Directory -Path "$TMP_DOWNLOAD_DIR_HOLDER.dir"
+$TMP_DOWNLOAD_DIR_HOLDER.Delete() | Out-Null
+trap {
+  if ($TMP_DOWNLOAD_DIR.Exists) {
+    try { Remove-Item $TMP_DOWNLOAD_DIR -Recurse -Force | Out-Null }
+    catch { Write-Warning "Cannot remove $TMP_DOWNLOAD_DIR" }
+  }
+}
+
+New-Item -Itemtype Directory -Path "$MAVEN_HOME_PARENT" -Force | Out-Null
+
+# Download and Install Apache Maven
+Write-Verbose "Couldn't find MAVEN_HOME, downloading and installing it ..."
+Write-Verbose "Downloading from: $distributionUrl"
+Write-Verbose "Downloading to: $TMP_DOWNLOAD_DIR/$distributionUrlName"
+
+$webclient = New-Object System.Net.WebClient
+if ($env:MVNW_USERNAME -and $env:MVNW_PASSWORD) {
+  $webclient.Credentials = New-Object System.Net.NetworkCredential($env:MVNW_USERNAME, $env:MVNW_PASSWORD)
+}
+[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
+$webclient.DownloadFile($distributionUrl, "$TMP_DOWNLOAD_DIR/$distributionUrlName") | Out-Null
+
+# If specified, validate the SHA-256 sum of the Maven distribution zip file
+$distributionSha256Sum = (Get-Content -Raw "$scriptDir/.mvn/wrapper/maven-wrapper.properties" | ConvertFrom-StringData).distributionSha256Sum
+if ($distributionSha256Sum) {
+  if ($USE_MVND) {
+    Write-Error "Checksum validation is not supported for maven-mvnd. `nPlease disable validation by removing 'distributionSha256Sum' from your maven-wrapper.properties."
+  }
+  Import-Module $PSHOME\Modules\Microsoft.PowerShell.Utility -Function Get-FileHash
+  if ((Get-FileHash "$TMP_DOWNLOAD_DIR/$distributionUrlName" -Algorithm SHA256).Hash.ToLower() -ne $distributionSha256Sum) {
+    Write-Error "Error: Failed to validate Maven distribution SHA-256, your Maven distribution might be compromised. If you updated your Maven version, you need to update the specified distributionSha256Sum property."
+  }
+}
+
+# unzip and move
+Expand-Archive "$TMP_DOWNLOAD_DIR/$distributionUrlName" -DestinationPath "$TMP_DOWNLOAD_DIR" | Out-Null
+
+# Find the actual extracted directory name (handles snapshots where filename != directory name)
+$actualDistributionDir = ""
+
+# First try the expected directory name (for regular distributions)
+$expectedPath = Join-Path "$TMP_DOWNLOAD_DIR" "$distributionUrlNameMain"
+$expectedMvnPath = Join-Path "$expectedPath" "bin/$MVN_CMD"
+if ((Test-Path -Path $expectedPath -PathType Container) -and (Test-Path -Path $expectedMvnPath -PathType Leaf)) {
+  $actualDistributionDir = $distributionUrlNameMain
+}
+
+# If not found, search for any directory with the Maven executable (for snapshots)
+if (!$actualDistributionDir) {
+  Get-ChildItem -Path "$TMP_DOWNLOAD_DIR" -Directory | ForEach-Object {
+    $testPath = Join-Path $_.FullName "bin/$MVN_CMD"
+    if (Test-Path -Path $testPath -PathType Leaf) {
+      $actualDistributionDir = $_.Name
+    }
+  }
+}
+
+if (!$actualDistributionDir) {
+  Write-Error "Could not find Maven distribution directory in extracted archive"
+}
+
+Write-Verbose "Found extracted Maven distribution directory: $actualDistributionDir"
+Rename-Item -Path "$TMP_DOWNLOAD_DIR/$actualDistributionDir" -NewName $MAVEN_HOME_NAME | Out-Null
+try {
+  Move-Item -Path "$TMP_DOWNLOAD_DIR/$MAVEN_HOME_NAME" -Destination $MAVEN_HOME_PARENT | Out-Null
+} catch {
+  if (! (Test-Path -Path "$MAVEN_HOME" -PathType Container)) {
+    Write-Error "fail to move MAVEN_HOME"
+  }
+} finally {
+  try { Remove-Item $TMP_DOWNLOAD_DIR -Recurse -Force | Out-Null }
+  catch { Write-Warning "Cannot remove $TMP_DOWNLOAD_DIR" }
+}
+
+Write-Output "MVN_CMD=$MAVEN_HOME/bin/$MVN_CMD"

+ 196 - 0
pom.xml

@@ -0,0 +1,196 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
+    <modelVersion>4.0.0</modelVersion>
+    <parent>
+        <groupId>org.springframework.boot</groupId>
+        <artifactId>spring-boot-starter-parent</artifactId>
+        <version>3.5.6</version>
+        <relativePath/> <!-- lookup parent from repository -->
+    </parent>
+    <groupId>it.bgates</groupId>
+    <artifactId>remote-be</artifactId>
+    <version>0.0.1-SNAPSHOT</version>
+    <name>remote-be</name>
+    <description>remote-be</description>
+    <url/>
+    <licenses>
+        <license/>
+    </licenses>
+    <developers>
+        <developer/>
+    </developers>
+    <scm>
+        <connection/>
+        <developerConnection/>
+        <tag/>
+        <url/>
+    </scm>
+    <properties>
+        <java.version>21</java.version>
+    </properties>
+    <dependencies>
+        <dependency>
+            <groupId>org.springframework.boot</groupId>
+            <artifactId>spring-boot-starter-data-jdbc</artifactId>
+        </dependency>
+        <dependency>
+            <groupId>org.springframework.boot</groupId>
+            <artifactId>spring-boot-starter-data-jpa</artifactId>
+        </dependency>
+        <dependency>
+            <groupId>org.springframework.boot</groupId>
+            <artifactId>spring-boot-starter-mail</artifactId>
+        </dependency>
+        <dependency>
+            <groupId>org.springframework.boot</groupId>
+            <artifactId>spring-boot-starter-security</artifactId>
+        </dependency>
+        <dependency>
+            <groupId>org.springframework.boot</groupId>
+            <artifactId>spring-boot-starter-validation</artifactId>
+        </dependency>
+        <dependency>
+            <groupId>org.springframework.boot</groupId>
+            <artifactId>spring-boot-starter-web</artifactId>
+        </dependency>
+
+        <dependency>
+            <groupId>org.springframework.boot</groupId>
+            <artifactId>spring-boot-starter-oauth2-resource-server</artifactId>
+        </dependency>
+
+
+        <dependency>
+            <groupId>org.springframework.boot</groupId>
+            <artifactId>spring-boot-devtools</artifactId>
+            <scope>runtime</scope>
+            <optional>true</optional>
+        </dependency>
+        <dependency>
+            <groupId>org.mariadb.jdbc</groupId>
+            <artifactId>mariadb-java-client</artifactId>
+            <scope>runtime</scope>
+        </dependency>
+        <dependency>
+            <groupId>org.springframework.boot</groupId>
+            <artifactId>spring-boot-configuration-processor</artifactId>
+            <optional>true</optional>
+        </dependency>
+        <dependency>
+            <groupId>org.projectlombok</groupId>
+            <artifactId>lombok</artifactId>
+            <optional>true</optional>
+        </dependency>
+        <dependency>
+            <groupId>org.springframework.boot</groupId>
+            <artifactId>spring-boot-starter-test</artifactId>
+            <scope>test</scope>
+        </dependency>
+        <dependency>
+            <groupId>org.springframework.security</groupId>
+            <artifactId>spring-security-test</artifactId>
+            <scope>test</scope>
+        </dependency>
+
+        <dependency>
+            <groupId>io.jsonwebtoken</groupId>
+            <artifactId>jjwt-api</artifactId>
+            <version>0.11.5</version>
+        </dependency>
+        <dependency>
+            <groupId>io.jsonwebtoken</groupId>
+            <artifactId>jjwt-impl</artifactId>
+            <version>0.11.5</version>
+            <scope>runtime</scope>
+        </dependency>
+        <dependency>
+            <groupId>io.jsonwebtoken</groupId>
+            <artifactId>jjwt-jackson</artifactId>
+            <version>0.11.5</version>
+            <scope>runtime</scope>
+        </dependency>
+        <dependency>
+            <groupId>org.jetbrains</groupId>
+            <artifactId>annotations</artifactId>
+            <version>13.0</version>
+            <scope>compile</scope>
+        </dependency>
+
+        <dependency>
+            <groupId>org.springdoc</groupId>
+            <artifactId>springdoc-openapi-starter-webmvc-ui</artifactId>
+            <version>2.8.14</version>
+        </dependency>
+
+
+    </dependencies>
+
+    <build>
+        <finalName>${final.name}</finalName>
+        <resources>
+            <resource>
+                <directory>src/main/resources</directory>
+                <filtering>true</filtering>
+            </resource>
+        </resources>
+        <plugins>
+            <plugin>
+                <groupId>org.apache.maven.plugins</groupId>
+                <artifactId>maven-compiler-plugin</artifactId>
+                <configuration>
+                    <annotationProcessorPaths>
+                        <path>
+                            <groupId>org.springframework.boot</groupId>
+                            <artifactId>spring-boot-configuration-processor</artifactId>
+                        </path>
+                        <path>
+                            <groupId>org.projectlombok</groupId>
+                            <artifactId>lombok</artifactId>
+                        </path>
+                    </annotationProcessorPaths>
+                </configuration>
+            </plugin>
+            <plugin>
+                <groupId>org.springframework.boot</groupId>
+                <artifactId>spring-boot-maven-plugin</artifactId>
+                <configuration>
+                    <excludes>
+                        <exclude>
+                            <groupId>org.projectlombok</groupId>
+                            <artifactId>lombok</artifactId>
+                        </exclude>
+                    </excludes>
+                </configuration>
+            </plugin>
+        </plugins>
+    </build>
+
+    <profiles>
+        <profile>
+            <id>dev</id>
+            <activation>
+                <activeByDefault>true</activeByDefault>
+            </activation>
+            <properties>
+                <spring.profiles.active>dev</spring.profiles.active>
+                <final.name>remote-be</final.name>
+            </properties>
+        </profile>
+        <profile>
+            <id>prod</id>
+            <properties>
+                <spring.profiles.active>prod</spring.profiles.active>
+                <final.name>remote-be</final.name>
+            </properties>
+        </profile>
+        <profile>
+            <id>test</id>
+            <properties>
+                <spring.profiles.active>test</spring.profiles.active>
+                <final.name>remote-be-test</final.name>
+            </properties>
+        </profile>
+    </profiles>
+
+</project>

+ 46 - 0
src/main/java/it/bgates/remotebe/RemoteBeApplication.java

@@ -0,0 +1,46 @@
+package it.bgates.remotebe;
+
+import org.springframework.boot.SpringApplication;
+import org.springframework.boot.autoconfigure.SpringBootApplication;
+import org.springframework.context.annotation.Bean;
+import org.springframework.web.servlet.config.annotation.CorsRegistry;
+import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
+
+@SpringBootApplication
+public class RemoteBeApplication {
+
+    public static void main(String[] args) {
+        SpringApplication.run(RemoteBeApplication.class, args);
+    }
+
+
+    public static String[] allowedOrigins = {
+            "http://localhost:4211",
+            "http://localhost:4210",
+            "*"
+
+    };
+
+    public static String[] allowedMethods = {
+            "POST",
+            "GET",
+            "DELETE",
+            "PATCH",
+            "OPTIONS"
+    };
+
+    @Bean
+    public WebMvcConfigurer corsConfigurer() {
+        return new WebMvcConfigurer() {
+            @Override
+            public void addCorsMappings(CorsRegistry registry){
+                registry.addMapping("/**")
+                        .allowedOrigins(allowedOrigins)
+                        .allowedMethods(allowedMethods)
+                        // .allowCredentials(true)
+                ;
+            }
+        };
+    }
+
+}

+ 85 - 0
src/main/java/it/bgates/remotebe/config/BGatesUserDetailService.java

@@ -0,0 +1,85 @@
+package it.bgates.remotebe.config;
+
+import it.bgates.remotebe.entities.Privilege;
+import it.bgates.remotebe.entities.Role;
+import it.bgates.remotebe.entities.User;
+import it.bgates.remotebe.service.UserService;
+import jakarta.transaction.Transactional;
+import lombok.RequiredArgsConstructor;
+import org.springframework.security.authentication.AuthenticationProvider;
+import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
+import org.springframework.security.core.Authentication;
+import org.springframework.security.core.AuthenticationException;
+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 java.util.*;
+import java.util.stream.Collectors;
+
+
+@Service
+@RequiredArgsConstructor
+public class BGatesUserDetailService implements UserDetailsService, AuthenticationProvider {
+
+    private final UserService userService;
+
+    @Override
+    @Transactional
+    public BGatesUserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
+        Optional<User> user = userService.findByUsername(username);
+
+        if (user.isEmpty()) {
+            throw new UsernameNotFoundException("User not found with username: " + username);
+        }
+
+        List<String> roles = user.get().getRoles().stream()
+                .map(Role::getName)
+                .collect(Collectors.toList());
+
+
+
+        return new BGatesUserDetails(
+                user.get().getId(),
+                user.get().getUsername(),
+                user.get().getPassword(),
+                user.get().getUserType(),
+                user.get().getEnabled(),
+                user.get().getPerson(),
+                user.get().getCustomer(),
+                user.get().getDistributor(),
+                getPrivileges(user.get().getRoles()),
+                roles
+        );
+
+    }
+
+    @Override
+    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
+        final String username = authentication.getName();
+        final String password = authentication.getCredentials() != null?  authentication.getCredentials().toString() : null;
+
+        final UserDetails userDetails = loadUserByUsername(username);
+        return new UsernamePasswordAuthenticationToken(userDetails, password, userDetails.getAuthorities());
+    }
+
+    @Override
+    public boolean supports(Class<?> authentication) {
+        return authentication.equals(UsernamePasswordAuthenticationToken.class);
+    }
+
+    protected List<String> getPrivileges(Collection<Role> roles) {
+
+        List<String> privileges = new ArrayList<>();
+        for(Role role: roles) {
+            for (Privilege privilege : role.getPrivileges()) {
+                privileges.add(privilege.getName());
+            }
+
+        }
+        return privileges;
+    }
+
+}
+

+ 75 - 0
src/main/java/it/bgates/remotebe/config/BGatesUserDetails.java

@@ -0,0 +1,75 @@
+package it.bgates.remotebe.config;
+
+import com.fasterxml.jackson.annotation.JsonIgnore;
+import it.bgates.remotebe.entities.Customer;
+import it.bgates.remotebe.entities.Distributor;
+import it.bgates.remotebe.entities.base.Person;
+import it.bgates.remotebe.entities.enums.BGatesUserType;
+import lombok.Getter;
+import org.springframework.security.core.GrantedAuthority;
+import org.springframework.security.core.authority.SimpleGrantedAuthority;
+import org.springframework.security.core.userdetails.UserDetails;
+
+import java.util.*;
+
+@Getter
+public class BGatesUserDetails implements UserDetails {
+
+    private final Integer id;
+    private final String username;
+    private BGatesUserType userType;
+    @JsonIgnore
+    private final String password;
+    private boolean enabled;
+    private Person person;
+    private final Customer customer;
+    private final Distributor distributor;
+    private final List<String> privileges;
+    private final List<String> roles;
+
+    public BGatesUserDetails(
+            Integer id,
+            String username,
+            String password,
+            BGatesUserType userType,
+            boolean enabled,
+            Person person,
+            Customer customer,
+            Distributor distributor,
+            final List<String> privileges,
+            final List<String> roles) {
+        this.id = id;
+        this.username = username;
+        this.password = password;
+        this.userType = userType;
+        this.person = person;
+        this.customer = customer;
+        this.distributor = distributor;
+        this.enabled = enabled;
+        this.privileges = Collections.unmodifiableList(privileges);
+        this.roles = Collections.unmodifiableList(roles);
+
+    }
+
+    @Override
+    public Collection<? extends GrantedAuthority> getAuthorities() {
+        final Set<GrantedAuthority> authorities = new HashSet<>();
+        for (String role : roles) authorities.add(new SimpleGrantedAuthority(role));
+        return authorities;
+    }
+
+    @Override
+    public String getPassword() {
+        return password;
+    }
+
+    @Override
+    public String getUsername() {
+        return username;
+    }
+
+    @Override
+    public boolean isEnabled() {
+        return this.enabled;
+    }
+}

+ 90 - 0
src/main/java/it/bgates/remotebe/config/JwtAuthenticationFilter.java

@@ -0,0 +1,90 @@
+package it.bgates.remotebe.config;
+
+import io.jsonwebtoken.MalformedJwtException;
+import it.bgates.remotebe.entities.token.Token;
+import it.bgates.remotebe.entities.token.TokenRepository;
+import jakarta.servlet.FilterChain;
+import jakarta.servlet.ServletException;
+import jakarta.servlet.http.HttpServletRequest;
+import jakarta.servlet.http.HttpServletResponse;
+import lombok.RequiredArgsConstructor;
+import org.springframework.lang.NonNull;
+import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
+import org.springframework.security.core.context.SecurityContextHolder;
+import org.springframework.security.core.userdetails.UserDetails;
+import org.springframework.security.core.userdetails.UserDetailsService;
+import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
+import org.springframework.stereotype.Component;
+import org.springframework.web.filter.OncePerRequestFilter;
+
+import java.io.IOException;
+import java.util.Optional;
+
+@Component
+@RequiredArgsConstructor
+public class JwtAuthenticationFilter extends OncePerRequestFilter {
+
+
+    private final JwtService jwtService;
+    private final TokenRepository tokenRepository;
+    private final BGatesUserDetailService userDetailsService;
+
+    @Override
+    protected void doFilterInternal(
+            @NonNull HttpServletRequest request,
+            @NonNull HttpServletResponse response,
+            @NonNull FilterChain filterChain
+    ) throws ServletException, IOException {
+        if (request.getServletPath().contains("/auth")) {
+            filterChain.doFilter(request, response);
+            return;
+        }
+
+        // estrai l'utente dal token
+        final String authHeader = request.getHeader("Authorization");
+        final String jwt;
+        final String username;
+        if (authHeader == null ||!authHeader.startsWith("Bearer ")) {
+            filterChain.doFilter(request, response);
+            return;
+        }
+        jwt = authHeader.substring(7);
+
+        try {
+            username = jwtService.extractUsername(jwt);
+        } catch (MalformedJwtException ex) {
+            return;
+        } catch (io.jsonwebtoken.ExpiredJwtException ex) {
+            System.out.println(ex.getMessage());
+            response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Sessione scaduta");
+            return;
+        }
+
+        if (username != null && SecurityContextHolder.getContext().getAuthentication() == null) {
+            // UserDetails userDetails = (UserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal();// this.userDetailsService.loadUserByUsername(userEmail);
+            Optional<Token> token = tokenRepository.findByToken(jwt);
+            var isTokenValid = false;
+            if (token.isPresent() && token.get().expired) {
+                isTokenValid = false;
+            }
+            isTokenValid = tokenRepository.findByToken(jwt)
+                    .map(t -> !t.isExpired() && !t.isRevoked())
+                    .orElse(false);
+
+            UserDetails userDetails = userDetailsService.loadUserByUsername(username);
+
+            if (jwtService.isTokenValid(jwt, userDetails) && isTokenValid) {
+                UsernamePasswordAuthenticationToken authToken = new UsernamePasswordAuthenticationToken(
+                        userDetails,
+                        null,
+                        userDetails.getAuthorities()
+                );
+                authToken.setDetails(
+                        new WebAuthenticationDetailsSource().buildDetails(request)
+                );
+                SecurityContextHolder.getContext().setAuthentication(authToken);
+            }
+        }
+        filterChain.doFilter(request, response);
+    }
+}

+ 104 - 0
src/main/java/it/bgates/remotebe/config/JwtService.java

@@ -0,0 +1,104 @@
+package it.bgates.remotebe.config;
+
+import io.jsonwebtoken.Claims;
+import io.jsonwebtoken.Jwts;
+import io.jsonwebtoken.SignatureAlgorithm;
+import io.jsonwebtoken.io.Decoders;
+import io.jsonwebtoken.security.Keys;
+import lombok.Getter;
+import lombok.RequiredArgsConstructor;
+import org.springframework.beans.factory.annotation.Value;
+import org.springframework.security.core.userdetails.UserDetails;
+import org.springframework.security.oauth2.jwt.JwtClaimsSet;
+import org.springframework.security.oauth2.jwt.JwtEncoder;
+import org.springframework.security.oauth2.jwt.JwtEncoderParameters;
+import org.springframework.stereotype.Service;
+
+import java.security.Key;
+import java.time.Instant;
+import java.util.Date;
+import java.util.HashMap;
+import java.util.Map;
+import java.util.function.Function;
+
+@Service
+@RequiredArgsConstructor
+public class JwtService {
+
+    @Value("${application.security.jwt.secret-key}")
+    private String secretKey;
+    @Value("${application.security.jwt.expiration}")
+    private long jwtExpiration;
+    @Getter
+    @Value("${application.security.jwt.refresh-token.expiration}")
+    private long refreshExpiration;
+
+    public String extractUsername(String token) {
+        return extractClaim(token, Claims::getSubject);
+    }
+
+    public <T> T extractClaim(String token, Function<Claims, T> claimsResolver) {
+        final Claims claims = extractAllClaims(token);
+        return claimsResolver.apply(claims);
+    }
+
+    public String generateToken(UserDetails userDetails) {
+        return generateToken(new HashMap<>(), userDetails);
+    }
+
+    public String generateToken(
+            Map<String, Object> extraClaims,
+            UserDetails userDetails
+    ) {
+        return buildToken(extraClaims, userDetails, jwtExpiration);
+    }
+
+    public String generateRefreshToken(
+            UserDetails userDetails
+    ) {
+        return buildToken(new HashMap<>(), userDetails, refreshExpiration);
+    }
+
+
+    private String buildToken(
+            Map<String, Object> extraClaims,
+            UserDetails userDetails,
+            long expiration
+    ) {
+        return Jwts
+                .builder()
+                .setClaims(extraClaims)
+                .setSubject(userDetails.getUsername())
+                .setIssuedAt(new Date(System.currentTimeMillis()))
+                .setExpiration(new Date(System.currentTimeMillis() + expiration))
+                .signWith(getSignInKey(), SignatureAlgorithm.HS256)
+                .compact();
+    }
+
+    public boolean isTokenValid(String token, UserDetails userDetails) {
+        final String username = extractUsername(token);
+        return (username.equals(userDetails.getUsername())) && !isTokenExpired(token);
+    }
+
+    private boolean isTokenExpired(String token) {
+        return extractExpiration(token).before(new Date());
+    }
+
+    private Date extractExpiration(String token) {
+        return extractClaim(token, Claims::getExpiration);
+    }
+
+    private Claims extractAllClaims(String token) {
+        return Jwts
+                .parserBuilder()
+                .setSigningKey(getSignInKey())
+                .build()
+                .parseClaimsJws(token)
+                .getBody();
+    }
+
+    private Key getSignInKey() {
+        byte[] keyBytes = Decoders.BASE64.decode(secretKey);
+        return Keys.hmacShaKeyFor(keyBytes);
+    }
+}

+ 40 - 0
src/main/java/it/bgates/remotebe/config/LogoutService.java

@@ -0,0 +1,40 @@
+package it.bgates.remotebe.config;
+
+
+import it.bgates.remotebe.entities.token.TokenRepository;
+import jakarta.servlet.http.HttpServletRequest;
+import jakarta.servlet.http.HttpServletResponse;
+import lombok.RequiredArgsConstructor;
+import org.springframework.security.core.Authentication;
+import org.springframework.security.core.context.SecurityContextHolder;
+import org.springframework.security.web.authentication.logout.LogoutHandler;
+import org.springframework.stereotype.Service;
+
+@Service
+@RequiredArgsConstructor
+public class LogoutService implements LogoutHandler {
+
+  private final TokenRepository tokenRepository;
+
+  @Override
+  public void logout(
+      HttpServletRequest request,
+      HttpServletResponse response,
+      Authentication authentication
+  ) {
+    final String authHeader = request.getHeader("Authorization");
+    final String jwt;
+    if (authHeader == null ||!authHeader.startsWith("Bearer ")) {
+      return;
+    }
+    jwt = authHeader.substring(7);
+    var storedToken = tokenRepository.findByToken(jwt)
+        .orElse(null);
+    if (storedToken != null) {
+      storedToken.setExpired(true);
+      storedToken.setRevoked(true);
+      tokenRepository.save(storedToken);
+      SecurityContextHolder.clearContext();
+    }
+  }
+}

+ 95 - 0
src/main/java/it/bgates/remotebe/config/SecurityConfig.java

@@ -0,0 +1,95 @@
+package it.bgates.remotebe.config;
+
+import com.nimbusds.jose.jwk.JWK;
+import com.nimbusds.jose.jwk.JWKSet;
+import com.nimbusds.jose.jwk.RSAKey;
+import com.nimbusds.jose.jwk.source.ImmutableJWKSet;
+import com.nimbusds.jose.jwk.source.JWKSource;
+import com.nimbusds.jose.proc.SecurityContext;
+import lombok.RequiredArgsConstructor;
+import org.springframework.beans.factory.annotation.Value;
+import org.springframework.context.annotation.Bean;
+import org.springframework.context.annotation.Configuration;
+import org.springframework.data.jpa.repository.config.EnableJpaAuditing;
+import org.springframework.security.authentication.AuthenticationManager;
+import org.springframework.security.config.annotation.authentication.configuration.AuthenticationConfiguration;
+import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity;
+import org.springframework.security.config.annotation.web.builders.HttpSecurity;
+import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
+import org.springframework.security.core.context.SecurityContextHolder;
+import org.springframework.security.crypto.password.NoOpPasswordEncoder;
+import org.springframework.security.crypto.password.PasswordEncoder;
+import org.springframework.security.oauth2.jwt.JwtDecoder;
+import org.springframework.security.oauth2.jwt.JwtEncoder;
+import org.springframework.security.oauth2.jwt.NimbusJwtDecoder;
+import org.springframework.security.oauth2.jwt.NimbusJwtEncoder;
+import org.springframework.security.web.SecurityFilterChain;
+import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
+import org.springframework.security.web.authentication.logout.LogoutHandler;
+
+import java.security.interfaces.RSAPrivateKey;
+import java.security.interfaces.RSAPublicKey;
+import java.util.Arrays;
+
+import static org.springframework.security.config.http.SessionCreationPolicy.STATELESS;
+
+@Configuration
+@RequiredArgsConstructor
+@EnableMethodSecurity
+@EnableJpaAuditing
+@EnableWebSecurity
+public class SecurityConfig {
+
+    private static final String[] WHITE_LIST_URL = {
+            "/v3/**",
+            "/auth/**",
+            "/error"
+    };
+
+    private final JwtAuthenticationFilter jwtAuthFilter;
+    private final LogoutHandler logoutHandler;
+
+    @Bean
+    public PasswordEncoder passwordEncoder()
+    {
+        return NoOpPasswordEncoder.getInstance();
+    }
+
+
+
+    @Bean
+    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
+
+        http
+                .csrf(csrf -> csrf.disable())
+                .authorizeHttpRequests(req ->
+                        req
+                                .requestMatchers(WHITE_LIST_URL)
+                                .permitAll()
+                                .anyRequest()
+                                .fullyAuthenticated()
+                )
+                .sessionManagement(session -> session.sessionCreationPolicy(STATELESS))
+                .addFilterBefore(jwtAuthFilter, UsernamePasswordAuthenticationFilter.class)
+                .logout(logout ->
+                        logout.logoutUrl("/auth/logout")
+                                .addLogoutHandler(logoutHandler)
+                                .logoutSuccessHandler((request, response, authentication) -> SecurityContextHolder.clearContext())
+
+                );
+
+
+        return http.build();
+
+    }
+
+
+    @Bean
+    public AuthenticationManager authenticationManager(AuthenticationConfiguration authenticationConfiguration) throws Exception {
+        return authenticationConfiguration.getAuthenticationManager();
+    }
+
+
+
+
+}

+ 64 - 0
src/main/java/it/bgates/remotebe/controller/CustomerController.java

@@ -0,0 +1,64 @@
+package it.bgates.remotebe.controller;
+
+import it.bgates.remotebe.entities.Customer;
+import it.bgates.remotebe.exception.NotFoundException;
+import it.bgates.remotebe.exception.PermissionDeniedException;
+import it.bgates.remotebe.exception.UserNotFoundException;
+import it.bgates.remotebe.service.CustomerService;
+import lombok.RequiredArgsConstructor;
+import org.apache.coyote.Response;
+import org.springframework.http.HttpStatusCode;
+import org.springframework.http.ResponseEntity;
+import org.springframework.web.bind.annotation.*;
+
+import java.security.Principal;
+import java.util.List;
+
+import static org.springframework.http.HttpStatus.*;
+
+@RestController
+@RequestMapping("/customers")
+@RequiredArgsConstructor
+
+public class CustomerController {
+    private final CustomerService customerService;
+
+    @GetMapping("")
+    public ResponseEntity<List<Customer>> listCustomers(Principal principal) {
+        try {
+            return ResponseEntity.ok(customerService.getAllCustomers(principal));
+        } catch(UserNotFoundException e) {
+            return ResponseEntity.status(PRECONDITION_FAILED).build();
+        }
+
+    }
+
+    @PostMapping("")
+    public ResponseEntity<Customer> saveCustomer(@RequestBody Customer customer, Principal principal) {
+        Customer savedCustomer;
+        try {
+            savedCustomer = customerService.saveCustomer(customer, principal);
+        } catch(UserNotFoundException  e) {
+            return ResponseEntity.status(PRECONDITION_FAILED).build();
+        } catch (PermissionDeniedException e) {
+            return ResponseEntity.status(UNAUTHORIZED).build();
+        }
+
+        return ResponseEntity.ok(savedCustomer);
+    }
+
+    @DeleteMapping("/{id}")
+    public ResponseEntity<Boolean> deleteCustomer(@PathVariable Integer id, Principal principal) {
+        try {
+            customerService.deleteCustomer(id, principal);
+            return ResponseEntity.ok(true);
+        } catch (NotFoundException e) {
+            return ResponseEntity.status(NOT_FOUND).build();
+        } catch(UserNotFoundException e) {
+            return ResponseEntity.status(PRECONDITION_FAILED).build();
+        } catch (PermissionDeniedException e) {
+            return ResponseEntity.status(UNAUTHORIZED).build();
+        }
+
+    }
+}

+ 65 - 0
src/main/java/it/bgates/remotebe/controller/DeviceController.java

@@ -0,0 +1,65 @@
+package it.bgates.remotebe.controller;
+
+import it.bgates.remotebe.controller.beans.FilterBean;
+import it.bgates.remotebe.entities.Device;
+import it.bgates.remotebe.exception.UserNotFoundException;
+import it.bgates.remotebe.service.DeviceService;
+import jakarta.servlet.Filter;
+import lombok.RequiredArgsConstructor;
+import org.springframework.http.ResponseEntity;
+import org.springframework.web.bind.annotation.*;
+
+import java.security.Principal;
+import java.util.List;
+
+import static org.springframework.http.HttpStatus.PRECONDITION_FAILED;
+
+@RestController
+@RequestMapping("/devices")
+@RequiredArgsConstructor
+public class DeviceController {
+    private final DeviceService deviceService;
+
+    @GetMapping("")
+    private ResponseEntity<List<Device>> getDevices(Principal principal) {
+        try {
+            return ResponseEntity.ok().body(deviceService.getDevices(principal));
+        } catch (UserNotFoundException e) {
+            return ResponseEntity.status(PRECONDITION_FAILED).build();
+        }
+    }
+
+    @GetMapping("/{id}")
+    private ResponseEntity<Device> getDeviceById(@PathVariable Integer id, Principal principal)  {
+        try {
+            Device device = deviceService.getDevice(id, principal);
+            return device != null
+                ? ResponseEntity.ok().body(device)
+                : ResponseEntity.notFound().build();
+        } catch (UserNotFoundException e) {
+            return ResponseEntity.status(PRECONDITION_FAILED).build();
+        }
+    }
+
+    @PostMapping("")
+    private ResponseEntity<Device> saveDevice(@RequestBody Device device, Principal principal) {
+        try {
+            Device savedDevice = deviceService.save(device, principal);
+            return ResponseEntity.ok().body(savedDevice);
+        } catch (Exception e) {
+            return ResponseEntity.badRequest().build();
+        }
+    }
+
+    @PostMapping("/filter")
+    public ResponseEntity<List<Device>> filterDevices(@RequestBody FilterBean filterBean, Principal principal) {
+        try {
+            List<Device> devices = deviceService.filter(filterBean.getFilter(), principal);
+            return ResponseEntity.ok(devices);
+        } catch (UserNotFoundException e) {
+            return ResponseEntity.status(PRECONDITION_FAILED).build();
+        }
+
+    }
+
+}

+ 61 - 0
src/main/java/it/bgates/remotebe/controller/DistributorController.java

@@ -0,0 +1,61 @@
+package it.bgates.remotebe.controller;
+
+import it.bgates.remotebe.controller.beans.FilterBean;
+import it.bgates.remotebe.entities.Distributor;
+import it.bgates.remotebe.exception.PermissionDeniedException;
+import it.bgates.remotebe.exception.UserNotFoundException;
+import it.bgates.remotebe.service.DistributorService;
+import it.bgates.remotebe.service.UserService;
+import jakarta.servlet.Filter;
+import lombok.RequiredArgsConstructor;
+import org.springframework.http.ResponseEntity;
+import org.springframework.web.bind.annotation.*;
+
+import java.security.Principal;
+import java.util.List;
+
+import static org.springframework.http.HttpStatus.PRECONDITION_FAILED;
+import static org.springframework.http.HttpStatus.UNAUTHORIZED;
+
+@RestController
+@RequestMapping("/distributors")
+@RequiredArgsConstructor
+public class DistributorController {
+
+    private final DistributorService distributorService;
+    private final UserService userService;
+
+    @GetMapping("")
+    private ResponseEntity<List<Distributor>> getDistributors(Principal principal) {
+        try {
+            List<Distributor> distributors = distributorService.getDistributors(principal);
+            return ResponseEntity.ok(distributors);
+        } catch (UserNotFoundException e) {
+            return ResponseEntity.status(PRECONDITION_FAILED).build();
+        }
+    }
+
+    @PostMapping("")
+    private ResponseEntity<Distributor> save(@RequestBody Distributor distributor, Principal principal) {
+       try {
+           Distributor saved = distributorService.save(distributor, principal);
+           return ResponseEntity.ok(saved);
+       } catch (UserNotFoundException e) {
+            return ResponseEntity.status(PRECONDITION_FAILED).build();
+        } catch (PermissionDeniedException e) {
+           return ResponseEntity.status(UNAUTHORIZED).build();
+       }
+    }
+
+    @PostMapping("/filter")
+    public ResponseEntity<List<Distributor>> filterDevices(@RequestBody FilterBean filterBean, Principal principal) {
+        try {
+            List<Distributor> distributors = distributorService.filter(filterBean.getFilter(), principal);
+            return ResponseEntity.ok(distributors);
+        } catch (UserNotFoundException e) {
+            return ResponseEntity.status(PRECONDITION_FAILED).build();
+        }
+    }
+
+
+}

+ 46 - 0
src/main/java/it/bgates/remotebe/controller/InstallerController.java

@@ -0,0 +1,46 @@
+package it.bgates.remotebe.controller;
+
+import it.bgates.remotebe.entities.Installer;
+import it.bgates.remotebe.exception.PermissionDeniedException;
+import it.bgates.remotebe.exception.UserNotFoundException;
+import it.bgates.remotebe.service.InstallerService;
+import lombok.RequiredArgsConstructor;
+import org.springframework.http.ResponseEntity;
+import org.springframework.web.bind.annotation.*;
+
+import java.security.Principal;
+import java.util.List;
+
+import static org.springframework.http.HttpStatus.PRECONDITION_FAILED;
+import static org.springframework.http.HttpStatus.UNAUTHORIZED;
+
+@RestController
+@RequestMapping("/installers")
+@RequiredArgsConstructor
+public class InstallerController {
+
+    private final InstallerService installerService;
+
+    @GetMapping("")
+    public ResponseEntity<List<Installer>> getAllInstallers(Principal principal)  {
+        try {
+            return ResponseEntity.ok(installerService.getAllInstallers(principal));
+        } catch (UserNotFoundException e) {
+            return ResponseEntity.status(PRECONDITION_FAILED).build();
+        }
+    }
+
+    @PostMapping("")
+    public ResponseEntity<Installer> saveInstaller(@RequestBody Installer installer, Principal principal) {
+
+        try {
+            Installer saved = installerService.save(installer, principal);
+            return ResponseEntity.ok(saved);
+        } catch (PermissionDeniedException e) {
+            return ResponseEntity.status(UNAUTHORIZED).build();
+        } catch (UserNotFoundException e) {
+            return ResponseEntity.status(PRECONDITION_FAILED).build();
+        }
+
+    }
+}

+ 76 - 0
src/main/java/it/bgates/remotebe/controller/PhoneController.java

@@ -0,0 +1,76 @@
+package it.bgates.remotebe.controller;
+
+import it.bgates.remotebe.controller.beans.FilterBean;
+import it.bgates.remotebe.entities.Phone;
+import it.bgates.remotebe.exception.NotFoundException;
+import it.bgates.remotebe.exception.UserNotFoundException;
+import it.bgates.remotebe.service.PhoneService;
+import jakarta.validation.Valid;
+import lombok.RequiredArgsConstructor;
+import org.springframework.http.ResponseEntity;
+import org.springframework.web.bind.annotation.*;
+
+import java.security.Principal;
+import java.util.List;
+
+import static org.springframework.http.HttpStatus.NOT_FOUND;
+import static org.springframework.http.HttpStatus.PRECONDITION_FAILED;
+
+@RestController
+@RequestMapping("/phones")
+@RequiredArgsConstructor
+public class PhoneController {
+
+    private final PhoneService phoneService;
+
+    @GetMapping("/{id}")
+    public ResponseEntity<List<Phone>> getDevicePhones(@PathVariable Integer id, Principal principal) {
+        try {
+            List<Phone> phones = phoneService.getPhonesByDeviceId(id, principal);
+            return ResponseEntity.ok(phones);
+        } catch (UserNotFoundException e) {
+            return ResponseEntity.status(PRECONDITION_FAILED).build();
+        } catch(NotFoundException e) {
+            return ResponseEntity.status(NOT_FOUND).build();
+        }
+    }
+
+    @PostMapping("")
+    public ResponseEntity<Phone> addPhone(@Valid @RequestBody Phone phone, Principal principal) {
+        return ResponseEntity.ok(phoneService.addPhone(phone, principal));
+    }
+
+    @PostMapping("/filter")
+    public ResponseEntity<List<Phone>> filter(@RequestBody FilterBean filterBean, Principal principal) {
+        try {
+            List<Phone> phones = phoneService.filter(filterBean.getFilter(), principal);
+            return ResponseEntity.ok(phones);
+        } catch (UserNotFoundException e) {
+            return ResponseEntity.status(PRECONDITION_FAILED).build();
+        }
+    }
+
+    @GetMapping("/deactivate/{id}")
+    public ResponseEntity<Boolean> deactivatePhone(@PathVariable Integer id, Principal principal) {
+        try {
+            Boolean res = phoneService.deactivatePhone(id, principal);
+            return ResponseEntity.ok(res);
+        } catch (UserNotFoundException e) {
+            return ResponseEntity.status(PRECONDITION_FAILED).build();
+        } catch (NotFoundException e) {
+            return ResponseEntity.status(NOT_FOUND).build();
+        }
+    }
+
+    @GetMapping("/activate/{id}")
+    public ResponseEntity<Boolean> activatePhone(@PathVariable Integer id, Principal principal) {
+        try {
+            Boolean res = phoneService.activatePhone(id, principal);
+            return ResponseEntity.ok(res);
+        } catch (UserNotFoundException e) {
+            return ResponseEntity.status(PRECONDITION_FAILED).build();
+        } catch (NotFoundException e) {
+            return ResponseEntity.status(NOT_FOUND).build();
+        }
+    }
+}

+ 90 - 0
src/main/java/it/bgates/remotebe/controller/UserController.java

@@ -0,0 +1,90 @@
+package it.bgates.remotebe.controller;
+
+import it.bgates.remotebe.config.BGatesUserDetails;
+import it.bgates.remotebe.controller.auth.beans.NewUserBean;
+import it.bgates.remotebe.entities.User;
+import it.bgates.remotebe.exception.PermissionDeniedException;
+import it.bgates.remotebe.exception.UserNotFoundException;
+import it.bgates.remotebe.service.UserService;
+import it.bgates.remotebe.service.auth.AuthService;
+import jakarta.validation.Valid;
+import lombok.RequiredArgsConstructor;
+import org.springframework.http.ResponseEntity;
+import org.springframework.web.bind.annotation.*;
+
+import java.security.Principal;
+import java.util.List;
+
+import static org.springframework.http.HttpStatus.*;
+
+@RestController
+@RequiredArgsConstructor
+@RequestMapping("/users")
+public class UserController {
+
+    private final AuthService authService;
+    private final UserService userService;
+
+    /***
+     *
+     * @param principal
+     * @return return the user information for the currently logged user
+     */
+    @GetMapping("/current-user")
+    public ResponseEntity<BGatesUserDetails> getCurrentUser(Principal principal) {
+        BGatesUserDetails user = authService.getCurrentUser();
+
+        return ResponseEntity
+                .status(OK)
+                .body(user);
+    }
+
+    @GetMapping("")
+    public ResponseEntity<List<User>> getUsers(Principal principal) {
+        try {
+            List<User> users = userService.getUsers(principal);
+            return ResponseEntity
+                    .status(OK)
+                    .body(users);
+        } catch (UserNotFoundException e) {
+            return ResponseEntity.status(PRECONDITION_FAILED).build();
+        }
+
+
+    }
+
+    @PostMapping("")
+    public ResponseEntity<User> saveUser(@Valid @RequestBody NewUserBean newUser, Principal principal) {
+        if (newUser.getId() == null && !userService.canCreateUsers(principal)) {
+            return ResponseEntity.status(FORBIDDEN).build();
+
+        }
+        try {
+            User savedUser = userService.save(newUser, principal);
+            return ResponseEntity
+                    .status(OK)
+                    .body(savedUser);
+        } catch (PermissionDeniedException e) {
+            return ResponseEntity.status(FORBIDDEN).build();
+        } catch (UserNotFoundException e) {
+            return ResponseEntity.status(PRECONDITION_FAILED).build();
+        }
+    }
+
+    @PostMapping("disable/{id}")
+    public ResponseEntity<Boolean> disableUser(@PathVariable() Integer id, Principal principal) {
+        Boolean result = null;
+        try {
+            result = userService.disableUser(id, principal);
+            return ResponseEntity
+                    .status(OK)
+                    .body(result);
+
+        } catch (UserNotFoundException e) {
+            return ResponseEntity.status(PRECONDITION_FAILED).build();
+        } catch (PermissionDeniedException e) {
+            return ResponseEntity.status(FORBIDDEN).build();
+        }
+    }
+
+}

+ 78 - 0
src/main/java/it/bgates/remotebe/controller/auth/AuthController.java

@@ -0,0 +1,78 @@
+package it.bgates.remotebe.controller.auth;
+
+import it.bgates.remotebe.controller.auth.beans.AuthenticationRequest;
+import it.bgates.remotebe.controller.auth.beans.AuthenticationResponse;
+import it.bgates.remotebe.controller.auth.beans.RefreshTokenRequest;
+import it.bgates.remotebe.exception.AutorizationMissingException;
+import it.bgates.remotebe.exception.BadCredentialsException;
+import it.bgates.remotebe.exception.DisabledUserException;
+import it.bgates.remotebe.exception.UserNotFoundException;
+import it.bgates.remotebe.service.auth.AuthService;
+import jakarta.servlet.http.HttpServletRequest;
+import jakarta.servlet.http.HttpServletResponse;
+import jakarta.validation.Valid;
+import lombok.RequiredArgsConstructor;
+import org.springframework.http.ResponseEntity;
+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 javax.naming.AuthenticationException;
+import java.io.IOException;
+import java.security.Principal;
+
+import static org.springframework.http.HttpStatus.OK;
+import static org.springframework.http.HttpStatus.PRECONDITION_FAILED;
+
+@RestController
+@RequestMapping("/auth")
+@RequiredArgsConstructor
+public class AuthController {
+
+    private final AuthService authService;
+
+    @PostMapping("/login")
+    public ResponseEntity<AuthenticationResponse> authenticate(
+            @RequestBody AuthenticationRequest request
+    ) {
+        try {
+            return ResponseEntity.ok(authService.authenticate(request));
+        } catch (DisabledUserException e) {
+            return ResponseEntity.status(403).build();
+        } catch (UserNotFoundException e) {
+            return ResponseEntity.status(PRECONDITION_FAILED).build();
+        }
+
+        /*catch (AuthenticationException e) {
+            return ResponseEntity.status(401).build();
+
+        } catch (DisabledUserException e) {
+            return ResponseEntity.status(403).build();
+
+        } catch (UserNotFoundException e) {
+            return ResponseEntity.status(404).build();
+        }
+
+         */
+    }
+
+    @PostMapping("/logout")
+    public ResponseEntity<String> logout(Principal principal) {
+
+
+        authService.logout(principal.getName());
+        return ResponseEntity.status(OK).build();
+    }
+
+    @PostMapping("/refresh/token")
+    public void refreshToken(
+            HttpServletRequest request,
+            HttpServletResponse response
+    ) throws IOException {
+        authService.refreshToken(request, response);
+    }
+
+
+}
+

+ 16 - 0
src/main/java/it/bgates/remotebe/controller/auth/beans/AuthenticationRequest.java

@@ -0,0 +1,16 @@
+package it.bgates.remotebe.controller.auth.beans;
+
+import lombok.AllArgsConstructor;
+import lombok.Builder;
+import lombok.Data;
+import lombok.NoArgsConstructor;
+
+@Data
+@Builder
+@AllArgsConstructor
+@NoArgsConstructor
+public class AuthenticationRequest {
+    private String username;
+    String password;
+}
+

+ 24 - 0
src/main/java/it/bgates/remotebe/controller/auth/beans/AuthenticationResponse.java

@@ -0,0 +1,24 @@
+package it.bgates.remotebe.controller.auth.beans;
+
+import lombok.AllArgsConstructor;
+import lombok.Builder;
+import lombok.Data;
+import lombok.NoArgsConstructor;
+
+import java.time.Instant;
+import java.util.List;
+import java.util.Set;
+
+@Data
+@Builder
+@AllArgsConstructor
+@NoArgsConstructor
+public class AuthenticationResponse {
+
+    private String accessToken;
+    private String refreshToken;
+    private Instant expiresAt;
+    private String username;
+    private List<String> roles;
+    private List<String> authorities;
+}

+ 25 - 0
src/main/java/it/bgates/remotebe/controller/auth/beans/NewUserBean.java

@@ -0,0 +1,25 @@
+package it.bgates.remotebe.controller.auth.beans;
+
+import lombok.Data;
+
+import java.util.List;
+
+@Data
+public class NewUserBean {
+    private Integer id;
+    private String username;
+    private String password;
+    private String email;
+    private String firstname;
+    private String lastname;
+    private String address;
+    private String city;
+    private String zip;
+    private String phone;
+    private String mobilePhone;
+    private Integer userType;
+    private List<String> roles;
+    private List<String> privileges;
+    private Integer customerId;
+    private Integer distributorId;
+}

+ 15 - 0
src/main/java/it/bgates/remotebe/controller/auth/beans/RefreshTokenRequest.java

@@ -0,0 +1,15 @@
+package it.bgates.remotebe.controller.auth.beans;
+
+import jakarta.validation.constraints.NotBlank;
+import lombok.AllArgsConstructor;
+import lombok.Data;
+import lombok.NoArgsConstructor;
+
+@Data
+@AllArgsConstructor
+@NoArgsConstructor
+public class RefreshTokenRequest {
+    @NotBlank
+    private String refreshToken;
+    private String username;
+}

+ 21 - 0
src/main/java/it/bgates/remotebe/controller/auth/beans/RegisterRequest.java

@@ -0,0 +1,21 @@
+package it.bgates.remotebe.controller.auth.beans;
+
+import it.bgates.remotebe.entities.Role;
+import lombok.AllArgsConstructor;
+import lombok.Builder;
+import lombok.Data;
+import lombok.NoArgsConstructor;
+
+@Data
+@Builder
+@AllArgsConstructor
+@NoArgsConstructor
+public class RegisterRequest {
+
+    private String nome;
+    private String cognome;
+    private String email;
+    private String password;
+    private String azienda;
+    private Role role;
+}

+ 8 - 0
src/main/java/it/bgates/remotebe/controller/beans/FilterBean.java

@@ -0,0 +1,8 @@
+package it.bgates.remotebe.controller.beans;
+
+import lombok.Data;
+
+@Data
+public class FilterBean {
+    private String filter;
+}

+ 42 - 0
src/main/java/it/bgates/remotebe/entities/Customer.java

@@ -0,0 +1,42 @@
+package it.bgates.remotebe.entities;
+
+import com.fasterxml.jackson.annotation.JsonIgnore;
+import it.bgates.remotebe.entities.enums.CustomerType;
+import jakarta.persistence.*;
+import lombok.Getter;
+import lombok.Setter;
+
+import java.util.List;
+
+@Getter
+@Setter
+@Entity
+@Table(name = "customers")
+public class Customer {
+    @Id
+    @GeneratedValue(strategy = GenerationType.IDENTITY)
+    private Integer id;
+
+    @Column(length = 100)
+    private String name;
+    @Column(length = 200)
+    private String description;
+    @Column(length = 100)
+    private String address;
+    @Column(length = 50)
+    private String city;
+    @Column(length = 5)
+    private String zip;
+    @Column(length = 11)
+    private String vat_number;
+    @Column(length = 16)
+    private String fiscal_code;
+    @Column(length = 20)
+    private String phone;
+    @Column(length = 60)
+    private String email;
+
+    @OneToMany(mappedBy = "owner")
+    List<Device> devices;
+
+}

+ 78 - 0
src/main/java/it/bgates/remotebe/entities/Device.java

@@ -0,0 +1,78 @@
+package it.bgates.remotebe.entities;
+
+import com.fasterxml.jackson.annotation.JsonIgnore;
+import it.bgates.remotebe.entities.base.Person;
+import it.bgates.remotebe.entities.enums.DeviceType;
+import jakarta.persistence.*;
+import lombok.Getter;
+import lombok.Setter;
+
+import java.time.LocalDate;
+
+@Getter
+@Setter
+@Entity
+@Table(name = "devices")
+public class Device {
+    @Id
+    @GeneratedValue(strategy = GenerationType.IDENTITY)
+    private Integer id;
+
+    private String serialNumber;
+    private String description;
+
+    @JsonIgnore
+    @ManyToOne
+    @JoinColumn(name = "distributor_id", foreignKey = @ForeignKey(name = "FK_DEVICE_DISTRIBUTOR"))
+    private Distributor distributor;
+
+
+    @JsonIgnore
+    @ManyToOne
+    @JoinColumn(name = "owner_id", foreignKey = @ForeignKey(name = "FK_DEVICE_OWNER"))
+    private Customer owner;
+
+    @ManyToOne
+    @JoinColumn(name = "installer_id", foreignKey = @ForeignKey(name = "FK_DEVICE_INSTALLER"))
+    private Installer installer;
+
+    @Column(length = 100)
+    private String address;
+    @Column(length = 50)
+    private String city;
+    @Column(length = 5)
+    private String zip;
+    @Column(length = 11)
+
+
+    private String apn;
+    private String username;
+    private String password;
+
+    private String timezone;
+
+    private Boolean logging;
+    private Integer logSize;
+
+    private Integer impulseDuration;
+
+    private Integer replyDelay;
+    private String server1;
+    private String server2;
+
+    private LocalDate simExpiryDate;
+
+    private String vericationSms;
+    private String welcomeSms;
+    private String type2OnSms;
+    private String type2OffSms;
+
+    private String logEmail;
+
+    private DeviceType type;
+    private Boolean SyndDatetimeServer;
+    private Boolean hideSim;
+
+
+
+}

+ 48 - 0
src/main/java/it/bgates/remotebe/entities/Distributor.java

@@ -0,0 +1,48 @@
+package it.bgates.remotebe.entities;
+
+import jakarta.persistence.*;
+import jakarta.validation.constraints.NotNull;
+import jakarta.validation.constraints.Size;
+import lombok.Getter;
+import lombok.Setter;
+
+@Getter
+@Setter
+@Entity
+@Table(name = "distributors")
+public class Distributor {
+    @Id
+    @GeneratedValue(strategy = GenerationType.IDENTITY)
+    @Column(name = "id", nullable = false)
+    private Integer id;
+
+    @Size(max = 200)
+    @NotNull
+    @Column(name = "name", nullable = false, length = 200)
+    private String name;
+
+    @Size(max = 100)
+    @Column(name = "address", length = 100)
+    private String address;
+
+    @Size(max = 100)
+    @Column(name = "city", length = 100)
+    private String city;
+
+    @Size(max = 6)
+    @Column(name = "zip", length = 6)
+    private String zip;
+
+    @Size(max = 16)
+    @Column(name = "fiscal_code", length = 16)
+    private String fiscalCode;
+
+    @Size(max = 11)
+    @Column(name = "vat_number", length = 11)
+    private String vatNumber;
+
+    @Size(max = 2048)
+    @Column(name = "notes", length = 2048)
+    private String notes;
+
+}

+ 69 - 0
src/main/java/it/bgates/remotebe/entities/Installer.java

@@ -0,0 +1,69 @@
+package it.bgates.remotebe.entities;
+
+import com.fasterxml.jackson.annotation.JsonIgnore;
+import jakarta.persistence.*;
+import jakarta.validation.constraints.Size;
+import lombok.Getter;
+import lombok.Setter;
+
+import java.util.LinkedHashSet;
+import java.util.Set;
+
+@Getter
+@Setter
+@Entity
+@Table(name = "installers")
+public class Installer {
+    @Id
+    @GeneratedValue(strategy = GenerationType.IDENTITY)
+    @Column(name = "id", nullable = false)
+    private Integer id;
+
+    @Size(max = 200)
+    @Column(name = "name", length = 200)
+    private String name;
+
+    @Size(max = 60)
+    @Column(name = "email", length = 60)
+    private String email;
+
+    @Size(max = 16)
+    @Column(name = "fiscal_code", length = 16)
+    private String fiscalCode;
+
+    @Size(max = 20)
+    @Column(name = "phone", length = 20)
+    private String phone;
+
+    @Size(max = 20)
+    @Column(name = "mobile_phone", length = 20)
+    private String mobilePhone;
+
+    @Size(max = 11)
+    @Column(name = "vat_number", length = 11)
+    private String vatNumber;
+
+    @Size(max = 100)
+    @Column(name = "address", length = 100)
+    private String address;
+
+    @Size(max = 50)
+    @Column(name = "city", length = 50)
+    private String city;
+
+    @Size(max = 5)
+    @Column(name = "zip", length = 5)
+    private String zip;
+
+    @Size(max = 2048)
+    @Column(name = "notes", length = 2048)
+    private String notes;
+
+    private Boolean active;
+
+    @JsonIgnore
+    @OneToMany
+    @JoinColumn(name = "installer_id")
+    private Set<Device> devices = new LinkedHashSet<>();
+
+}

+ 19 - 0
src/main/java/it/bgates/remotebe/entities/Owner.java

@@ -0,0 +1,19 @@
+package it.bgates.remotebe.entities;
+
+import it.bgates.remotebe.entities.base.Person;
+import jakarta.persistence.*;
+import lombok.Getter;
+import lombok.Setter;
+
+@Getter
+@Setter
+@Entity
+@Table(name = "owners")
+public class Owner {
+    @Id
+    @GeneratedValue(strategy = GenerationType.IDENTITY)
+    private Integer id;
+
+    private Person person;
+
+}

+ 44 - 0
src/main/java/it/bgates/remotebe/entities/Phone.java

@@ -0,0 +1,44 @@
+package it.bgates.remotebe.entities;
+
+import com.fasterxml.jackson.annotation.JsonIgnore;
+import jakarta.persistence.*;
+import lombok.Getter;
+import lombok.Setter;
+
+import java.time.LocalDate;
+import java.time.LocalDateTime;
+import java.time.LocalTime;
+
+@Getter
+@Setter
+@Entity
+@Table(name = "phones")
+public class Phone {
+    @Id
+    @GeneratedValue(strategy = GenerationType.IDENTITY)
+    private Integer id;
+
+    @JsonIgnore
+    @ManyToOne
+    @JoinColumn(name = "device_id", foreignKey = @ForeignKey(name = "FK_PHONE_DEVICE"))
+    private Device device;
+
+    private String phoneNumber;
+    private String description;
+    private Boolean active;
+    private LocalDateTime createDate;
+    private Boolean monday;
+    private Boolean tuesday;
+    private Boolean wednesday;
+    private Boolean thursday;
+    private Boolean friday;
+    private Boolean saturday;
+    private Boolean sunday;
+
+    private LocalDate fromDate;
+    private LocalDate toDate;
+
+    private LocalTime fromTime;
+    private LocalTime toTime;
+
+}

+ 48 - 0
src/main/java/it/bgates/remotebe/entities/Privilege.java

@@ -0,0 +1,48 @@
+package it.bgates.remotebe.entities;
+
+import jakarta.persistence.Entity;
+import jakarta.persistence.GeneratedValue;
+import jakarta.persistence.GenerationType;
+import jakarta.persistence.Id;
+import lombok.Getter;
+import lombok.RequiredArgsConstructor;
+
+@Entity
+public class Privilege {
+
+    @Id
+    @GeneratedValue(strategy = GenerationType.AUTO)
+    private Long id;
+
+    private String name;
+
+    /*
+    @ManyToMany(mappedBy = "privileges")
+    private Collection<Role> roles;
+ */
+    public Privilege(String name) {
+        this.name = name;
+    }
+
+    public Privilege() {
+
+    }
+
+    public Long getId() {
+        return id;
+    }
+
+    public void setId(Long id) {
+        this.id = id;
+    }
+
+    public String getName() {
+        return name;
+    }
+
+    public void setName(String name) {
+        this.name = name;
+    }
+
+}
+

+ 76 - 0
src/main/java/it/bgates/remotebe/entities/Role.java

@@ -0,0 +1,76 @@
+package it.bgates.remotebe.entities;
+
+import jakarta.persistence.*;
+import java.util.Collection;
+
+
+@Entity
+public class Role {
+
+    public final static String SUPER_USER = "SUPER_USER";
+    public final static String DISTRIBUTOR = "DISTRIBUTOR";
+    public final static String USER = "USER";
+
+
+    @Id
+    @GeneratedValue(strategy = GenerationType.AUTO)
+    private Long id;
+
+    private String name;
+
+    /*
+    @ManyToMany(mappedBy = "roles")
+    private Collection<User> users;
+*/
+    @ManyToMany
+    @JoinTable(
+            name = "roles_privileges",
+            joinColumns = @JoinColumn(
+                    name = "role_id", referencedColumnName = "id"),
+            inverseJoinColumns = @JoinColumn(
+                    name = "privilege_id", referencedColumnName = "id"))
+    private Collection<Privilege> privileges;
+
+    public Role() {
+
+    }
+
+    public Role(String name) {
+        this.name = name;
+    }
+
+    public Long getId() {
+        return id;
+    }
+
+    public void setId(Long id) {
+        this.id = id;
+    }
+
+    public String getName() {
+        return name;
+    }
+
+    public void setName(String name) {
+        this.name = name;
+    }
+
+    /*
+    public Collection<User> getUsers() {
+        return users;
+    }
+
+    public void setUsers(Collection<User> users) {
+        this.users = users;
+    }
+
+     */
+
+    public Collection<Privilege> getPrivileges() {
+        return privileges;
+    }
+
+    public void setPrivileges(Collection<Privilege> privileges) {
+        this.privileges = privileges;
+    }
+}

+ 56 - 0
src/main/java/it/bgates/remotebe/entities/User.java

@@ -0,0 +1,56 @@
+package it.bgates.remotebe.entities;
+
+import com.fasterxml.jackson.annotation.JsonIgnore;
+import com.fasterxml.jackson.annotation.JsonProperty;
+import it.bgates.remotebe.entities.base.Person;
+import it.bgates.remotebe.entities.enums.BGatesUserType;
+import jakarta.persistence.*;
+import jakarta.validation.constraints.NotNull;
+import lombok.Getter;
+import lombok.Setter;
+
+import java.util.Collection;
+
+@Getter
+@Setter
+@Entity
+@Table(name = "users")
+public class User {
+    @Id
+    @GeneratedValue(strategy = GenerationType.IDENTITY)
+    private Integer id;
+
+    @NotNull
+    @Column(nullable = false)
+    private String username;
+
+    // ignora password when generating json
+    @JsonProperty(access = JsonProperty.Access.WRITE_ONLY)
+    private String password;
+    private Boolean enabled;
+
+    @NotNull
+    @Column(nullable = false)
+    private BGatesUserType userType;
+    private Person person;
+
+    @ManyToOne(fetch = FetchType.EAGER)
+    @JoinColumn(name = "customer_id", foreignKey = @ForeignKey(name = "FK_USER_CUSTOMER"))
+    private Customer customer;
+
+    @ManyToOne(fetch = FetchType.EAGER)
+    @JoinColumn(name = "distributor_id", foreignKey = @ForeignKey(name = "FK_USER_DISTRIBUTOR"))
+    private Distributor distributor;
+
+    @JsonIgnore
+    @ManyToMany
+    @JoinTable(
+            name = "users_roles",
+            joinColumns = @JoinColumn(
+                    name = "user_id", referencedColumnName = "id"),
+            inverseJoinColumns = @JoinColumn(
+                    name = "role_id", referencedColumnName = "id"))
+    private Collection<Role> roles;
+
+
+}

+ 24 - 0
src/main/java/it/bgates/remotebe/entities/base/Person.java

@@ -0,0 +1,24 @@
+package it.bgates.remotebe.entities.base;
+
+import jakarta.persistence.Column;
+import jakarta.persistence.Embeddable;
+import lombok.Data;
+
+@Embeddable
+@Data
+public class Person {
+    private String email;
+    private String lastname;
+    private String firstname;
+    private String companyName;
+    private String address;
+    private String city;
+    private String zip;
+    private String mobilePhone;
+    private String phone;
+    private String fax;
+    @Column(length = 16)
+    private String fiscalCode;
+    @Column(length = 11)
+    private String vatNumber;
+}

+ 8 - 0
src/main/java/it/bgates/remotebe/entities/enums/BGatesUserType.java

@@ -0,0 +1,8 @@
+package it.bgates.remotebe.entities.enums;
+
+public enum BGatesUserType {
+
+    ADMIN,
+    DISTRIBUTOR,
+    USER;
+}

+ 6 - 0
src/main/java/it/bgates/remotebe/entities/enums/CustomerType.java

@@ -0,0 +1,6 @@
+package it.bgates.remotebe.entities.enums;
+
+public enum CustomerType {
+    INSTALLER,
+    CUSTOMER
+}

+ 12 - 0
src/main/java/it/bgates/remotebe/entities/enums/DeviceType.java

@@ -0,0 +1,12 @@
+package it.bgates.remotebe.entities.enums;
+
+public enum DeviceType {
+    // cancello, porta, ecc impulso
+    Impulse,
+
+    // tipo caldaia con SMS risposta Bistabile (on/off)
+    Type1,
+
+    // tipo caldaia con richiamata telefonica gratuita - Bistabile (on/off)
+    Type2
+}

+ 25 - 0
src/main/java/it/bgates/remotebe/entities/token/RefreshToken.java

@@ -0,0 +1,25 @@
+package it.bgates.remotebe.entities.token;
+
+import jakarta.persistence.Entity;
+import jakarta.persistence.GeneratedValue;
+import jakarta.persistence.GenerationType;
+import jakarta.persistence.Id;
+import lombok.*;
+
+import java.time.Instant;
+
+@Getter
+@Setter
+@ToString
+@Data
+@RequiredArgsConstructor
+@Entity
+@AllArgsConstructor
+public class RefreshToken {
+    @Id
+    @GeneratedValue(strategy = GenerationType.IDENTITY)
+    private Long id;
+    private String token;
+    private Instant createdDate;
+
+}

+ 13 - 0
src/main/java/it/bgates/remotebe/entities/token/RefreshTokenRepository.java

@@ -0,0 +1,13 @@
+package it.bgates.remotebe.entities.token;
+
+import org.springframework.data.jpa.repository.JpaRepository;
+import org.springframework.stereotype.Repository;
+
+import java.util.Optional;
+
+@Repository
+public interface RefreshTokenRepository extends JpaRepository<RefreshToken, Long> {
+    Optional<RefreshToken> findByToken(String token);
+
+    void deleteByToken(String token);
+}

+ 30 - 0
src/main/java/it/bgates/remotebe/entities/token/Token.java

@@ -0,0 +1,30 @@
+package it.bgates.remotebe.entities.token;
+
+import jakarta.persistence.*;
+import lombok.AllArgsConstructor;
+import lombok.Builder;
+import lombok.Data;
+import lombok.NoArgsConstructor;
+
+@Data
+@Builder
+@NoArgsConstructor
+@AllArgsConstructor
+@Entity
+public class Token {
+
+    @Id
+    @GeneratedValue
+    public Long id;
+
+    @Column(unique = true)
+    public String token;
+
+    public boolean revoked;
+
+    public boolean expired;
+
+    public String username;
+
+
+}

+ 16 - 0
src/main/java/it/bgates/remotebe/entities/token/TokenRepository.java

@@ -0,0 +1,16 @@
+package it.bgates.remotebe.entities.token;
+
+import org.springframework.data.jpa.repository.JpaRepository;
+import org.springframework.data.jpa.repository.Query;
+
+import java.util.List;
+import java.util.Optional;
+
+public interface TokenRepository extends JpaRepository<Token, Long> {
+
+    @Query(value = "select t from Token t where t.username = :username and (t.expired = false or t.revoked = false)")
+    List<Token> findAllValidTokenByUser(String username);
+
+    Optional<Token> findByToken(String token);
+
+}

+ 8 - 0
src/main/java/it/bgates/remotebe/exception/AutorizationMissingException.java

@@ -0,0 +1,8 @@
+package it.bgates.remotebe.exception;
+
+public class AutorizationMissingException extends Exception{
+
+    public AutorizationMissingException(String message) {
+        super(message);
+    }
+}

+ 8 - 0
src/main/java/it/bgates/remotebe/exception/BadCredentialsException.java

@@ -0,0 +1,8 @@
+package it.bgates.remotebe.exception;
+
+public class BadCredentialsException extends Exception{
+
+    public BadCredentialsException(String message) {
+        super(message);
+    }
+}

+ 8 - 0
src/main/java/it/bgates/remotebe/exception/DisabledUserException.java

@@ -0,0 +1,8 @@
+package it.bgates.remotebe.exception;
+
+public class DisabledUserException extends Exception{
+
+    public DisabledUserException(String message) {
+        super(message);
+    }
+}

+ 7 - 0
src/main/java/it/bgates/remotebe/exception/NotFoundException.java

@@ -0,0 +1,7 @@
+package it.bgates.remotebe.exception;
+
+public class NotFoundException extends Exception{
+    public NotFoundException(String message) {
+        super(message);
+    }
+}

+ 7 - 0
src/main/java/it/bgates/remotebe/exception/PermissionDeniedException.java

@@ -0,0 +1,7 @@
+package it.bgates.remotebe.exception;
+
+public class PermissionDeniedException extends Exception {
+    public PermissionDeniedException(String message) {
+        super(message);
+    }
+}

+ 8 - 0
src/main/java/it/bgates/remotebe/exception/UserNotFoundException.java

@@ -0,0 +1,8 @@
+package it.bgates.remotebe.exception;
+
+public class UserNotFoundException extends Exception{
+
+    public UserNotFoundException(String message) {
+        super(message);
+    }
+}

+ 36 - 0
src/main/java/it/bgates/remotebe/repository/CustomerRepository.java

@@ -0,0 +1,36 @@
+package it.bgates.remotebe.repository;
+
+import it.bgates.remotebe.entities.Customer;
+import it.bgates.remotebe.entities.enums.CustomerType;
+import org.springframework.data.jpa.repository.JpaRepository;
+import org.springframework.data.jpa.repository.Query;
+
+import java.util.List;
+
+public interface CustomerRepository extends JpaRepository<Customer, Integer> {
+
+    @Query("SELECT c from Customer c join fetch Device dev on dev.owner = c order by c.name")
+    List<Customer> findAllByOrderByDescription();
+
+    //@Query("SELECT C from Customer C WHERE C.devices in (select D from Device D where D.installer = :installer)  order by C.name")
+    @Query(
+            value = "SELECT C.* from customers C WHERE C.ID in (select D.owner_id from devices D where D.installer_id = :installerId)  order by C.name",
+            nativeQuery = true
+    )
+    List<Customer> findByInstaller(Integer installerId);
+
+/*    @Query(
+            value = "select c.* from customers c \n" +
+            "join devices d on d.owner_id = c.id\n" +
+            "join distributors dis on dis.id = d.distributor_id\n" +
+            "where dis.id = :distributorId",
+            nativeQuery = true
+    )
+
+ */
+    @Query(
+            value = "select c from Customer c join fetch Device dev on dev.owner = c join fetch Distributor d on dev.distributor = d where d.id=:distributorId"
+    )
+    List<Customer> findByDistributor(Integer distributorId);
+
+}

+ 21 - 0
src/main/java/it/bgates/remotebe/repository/DeviceRepository.java

@@ -0,0 +1,21 @@
+package it.bgates.remotebe.repository;
+
+import it.bgates.remotebe.entities.Customer;
+import it.bgates.remotebe.entities.Device;
+import it.bgates.remotebe.entities.Distributor;
+import it.bgates.remotebe.entities.User;
+import org.springframework.data.jpa.repository.JpaRepository;
+
+import java.util.List;
+
+public interface DeviceRepository extends JpaRepository<Device, Integer> {
+    List<Device>  findAll();
+
+    List<Device> findAllByInstallerOrderByDescription(Customer installer);
+    List<Device> findAllByDistributorOrderByDescription(Distributor distributor);
+    List<Device> findAllByOwnerOrderByDescription(Customer owner);
+
+    List<Device> findAllByOrderByDescription();
+
+    // List<Device> findAllByInstallerOrderByDescription();
+}

+ 11 - 0
src/main/java/it/bgates/remotebe/repository/DistributorRepository.java

@@ -0,0 +1,11 @@
+package it.bgates.remotebe.repository;
+
+import it.bgates.remotebe.entities.Distributor;
+import org.springframework.data.jpa.repository.JpaRepository;
+
+import java.util.List;
+
+public interface DistributorRepository extends JpaRepository<Distributor, Integer>{
+
+    List<Distributor> findAllByOrderByName();
+}

+ 16 - 0
src/main/java/it/bgates/remotebe/repository/InstallerRepository.java

@@ -0,0 +1,16 @@
+package it.bgates.remotebe.repository;
+
+import it.bgates.remotebe.entities.Customer;
+import it.bgates.remotebe.entities.Installer;
+import it.bgates.remotebe.entities.enums.CustomerType;
+import org.springframework.data.jpa.repository.JpaRepository;
+import org.springframework.data.jpa.repository.Query;
+import org.springframework.data.repository.query.Param;
+
+import java.util.List;
+
+public interface InstallerRepository extends JpaRepository<Installer, Integer> {
+
+    @Query(value="SELECT I from Installer I order by I.name")
+    List<Installer> findAllOrderByName();
+}

+ 12 - 0
src/main/java/it/bgates/remotebe/repository/PhoneRepository.java

@@ -0,0 +1,12 @@
+package it.bgates.remotebe.repository;
+
+import it.bgates.remotebe.entities.Device;
+import it.bgates.remotebe.entities.Phone;
+import org.springframework.data.jpa.repository.JpaRepository;
+
+import java.util.List;
+
+public interface PhoneRepository extends JpaRepository<Phone, Integer> {
+
+    List<Phone> findByDevice(Device device);
+}

+ 15 - 0
src/main/java/it/bgates/remotebe/repository/UserRepository.java

@@ -0,0 +1,15 @@
+package it.bgates.remotebe.repository;
+
+import it.bgates.remotebe.entities.Distributor;
+import it.bgates.remotebe.entities.User;
+import org.springframework.data.jpa.repository.JpaRepository;
+
+import java.util.List;
+import java.util.Optional;
+
+public interface UserRepository extends JpaRepository<User, Integer> {
+    Optional<User> findByUsername(String username);
+
+    List<User> findAllByOrderByUsername();
+    List<User> findAllByDistributorOrderByUsername(Distributor distributor);
+}

+ 91 - 0
src/main/java/it/bgates/remotebe/service/BaseService.java

@@ -0,0 +1,91 @@
+package it.bgates.remotebe.service;
+
+import it.bgates.remotebe.config.BGatesUserDetails;
+import it.bgates.remotebe.entities.Role;
+import it.bgates.remotebe.entities.enums.BGatesUserType;
+import it.bgates.remotebe.exception.UserNotFoundException;
+import org.springframework.data.domain.Pageable;
+import org.springframework.data.domain.Sort;
+import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
+
+import java.security.Principal;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Optional;
+
+public class BaseService {
+
+    protected BGatesUserDetails userDetails;
+
+    protected BGatesUserDetails getUserDetails(Principal principal) throws UserNotFoundException {
+        userDetails = (BGatesUserDetails)  ((UsernamePasswordAuthenticationToken) principal).getPrincipal();;
+        if (userDetails == null) {
+            throw new UserNotFoundException("User not found");
+        }
+        return userDetails;
+    }
+
+    protected boolean isSuperUser() {
+        return userDetails.getUserType().equals(BGatesUserType.ADMIN);
+        /*
+            return userDetails.getAuthorities().stream()
+                .anyMatch(a -> a.getAuthority().equals(Role.SUPER_USER));
+         */
+    }
+
+
+    protected boolean isDistributor() {
+        return userDetails.getUserType().equals(BGatesUserType.DISTRIBUTOR);
+        /*
+        return userDetails.getAuthorities().stream()
+                .anyMatch(a -> a.getAuthority().equals(Role.DISTRIBUTOR));
+         */
+    }
+
+    protected boolean isUser() {
+        return userDetails.getUserType().equals(BGatesUserType.USER);
+        /*
+        return userDetails.getAuthorities().stream()
+                .anyMatch(a -> a.getAuthority().equals(Role.USER));
+         */
+    }
+
+
+    public List<String> buildFilter(StringBuilder builder, String filter, String[] fields){
+        List<String> paramValues = new ArrayList<>();
+
+        // per filtri vuoti non aggiungere condizioni
+        if (!"".equals(filter)) {
+            String[] terms = filter.split(" ");
+
+            int termIndex = 0;
+            for (String term : terms) {
+                builder.append(System.lineSeparator());
+                builder.append("AND (");
+
+                for (int i = 0; i < fields.length; i++) {
+                    paramValues.add("%" + term + "%");
+                    builder.append(fields[i]).append(String.format(" like :param_%d", termIndex++));
+                    if (i < fields.length - 1) {
+                        builder.append(" OR ");
+                        builder.append(System.lineSeparator());
+                    }
+                }
+
+                builder.append(")");
+                builder.append(System.lineSeparator());
+            }
+        }
+        return paramValues;
+    }
+
+
+    public String getSortBy(Pageable pageable, String defaultSortField) {
+
+        Optional<Sort.Order> order =  pageable.getSort().stream().findFirst();
+        if (order.isPresent()) {
+            return order.get().getProperty() + " " + order.get().getDirection().name();
+        }
+        return defaultSortField;
+    }
+}

+ 73 - 0
src/main/java/it/bgates/remotebe/service/CustomerService.java

@@ -0,0 +1,73 @@
+package it.bgates.remotebe.service;
+
+import it.bgates.remotebe.config.BGatesUserDetails;
+import it.bgates.remotebe.entities.Customer;
+import it.bgates.remotebe.entities.User;
+import it.bgates.remotebe.entities.enums.CustomerType;
+import it.bgates.remotebe.exception.NotFoundException;
+import it.bgates.remotebe.exception.PermissionDeniedException;
+import it.bgates.remotebe.exception.UserNotFoundException;
+import it.bgates.remotebe.repository.CustomerRepository;
+import lombok.RequiredArgsConstructor;
+import org.springframework.stereotype.Service;
+
+import java.security.Principal;
+import java.util.List;
+import java.util.Optional;
+
+@Service
+@RequiredArgsConstructor
+public class CustomerService extends BaseService {
+    private final CustomerRepository customerRepository;
+    private final UserService userService;
+
+    public List<Customer> getAllCustomers(Principal principal) throws UserNotFoundException {
+        getUserDetails(principal);
+
+        if (isSuperUser()) {
+            return customerRepository.findAllByOrderByDescription();
+        } else if (isDistributor()) {
+            return customerRepository.findByDistributor(userDetails.getDistributor().getId());
+        }
+
+        Optional<User> user = userService.findByUsername(userDetails.getUsername());
+        if (isUser() && user.isPresent()) {
+            Integer customerId = user.get().getCustomer().getId();
+            Optional<Customer> customer = customerRepository.findById(customerId);
+            return customer.map(List::of).orElseGet(List::of);
+        }
+
+        return List.of();
+    }
+
+
+
+    public Customer saveCustomer(Customer customer, Principal principal) throws UserNotFoundException, PermissionDeniedException {
+        getUserDetails(principal);
+
+        if (isUser()) {
+            throw new PermissionDeniedException("Accesso negato");
+        }
+        if (isDistributor()) {
+
+        }
+
+        return customerRepository.save(customer);
+    }
+
+    public void deleteCustomer(Integer id, Principal principal) throws PermissionDeniedException, UserNotFoundException, NotFoundException {
+        getUserDetails(principal);
+
+        if (isUser()) {
+            throw new PermissionDeniedException("Accesso negato");
+        }
+
+        Customer customer = customerRepository.findById(id).orElse(null);
+        if (customer == null) {
+            throw new NotFoundException("Cliente non trovato");
+        }
+
+        customerRepository.deleteById(id);
+
+    }
+}

+ 134 - 0
src/main/java/it/bgates/remotebe/service/DeviceService.java

@@ -0,0 +1,134 @@
+package it.bgates.remotebe.service;
+
+import it.bgates.remotebe.config.BGatesUserDetails;
+import it.bgates.remotebe.entities.Customer;
+import it.bgates.remotebe.entities.Device;
+import it.bgates.remotebe.entities.Distributor;
+import it.bgates.remotebe.entities.User;
+import it.bgates.remotebe.exception.UserNotFoundException;
+import it.bgates.remotebe.repository.DeviceRepository;
+import it.bgates.remotebe.repository.UserRepository;
+import jakarta.persistence.EntityManager;
+import jakarta.persistence.Query;
+import jakarta.persistence.TypedQuery;
+import lombok.RequiredArgsConstructor;
+import org.springframework.stereotype.Service;
+
+import java.security.Principal;
+import java.util.List;
+import java.util.Optional;
+
+@Service
+@RequiredArgsConstructor
+public class DeviceService extends BaseService {
+
+    private final DeviceRepository deviceRepository;
+    private final UserRepository userRepository;
+    private final UserService userService;
+    private final EntityManager entityManager;
+
+    /***
+     * returns the list of devices accessible the currently logged user
+     * If the user is an admin, returns all the devices
+     * If the user is a distributor, returns only the devices assigned to him
+     * @param principal
+     * @return
+     */
+    public List<Device> getDevices(Principal principal) throws UserNotFoundException {
+        BGatesUserDetails userDetails = getUserDetails(principal);
+
+        Optional<User> user = userRepository.findByUsername(userDetails.getUsername());
+        if (user.isEmpty()) {
+            return List.of();
+        }
+
+        if (isSuperUser()) {
+            return deviceRepository.findAllByOrderByDescription();
+        }
+        if (isDistributor() ) {
+            if (user.isEmpty()) {
+                return List.of();
+            }
+            Customer customer = user.get().getCustomer();
+            Distributor distributor = user.get().getDistributor();
+
+            return deviceRepository.findAllByDistributorOrderByDescription(distributor);
+        }
+
+        if (isUser()) {
+            Customer customer = user.get().getCustomer();
+            return deviceRepository.findAllByOwnerOrderByDescription(customer);
+        }
+
+        return List.of();
+    }
+
+    public List<Device> filter(String filter, Principal principal) throws UserNotFoundException {
+        getUserDetails(principal);
+
+        Optional<User> user = userRepository.findByUsername(userDetails.getUsername());
+        if (user.isEmpty()) {
+            return List.of();
+        }
+
+        StringBuilder filterBuilder = new StringBuilder();
+
+        if (isDistributor()) {
+            filterBuilder.append("WHERE d.distributor = :distributor");
+        } else if (isSuperUser()){
+            filterBuilder.append("WHERE true");
+        } else {
+            filterBuilder.append("WHERE false"); // return nothing if not super user or distributor
+        }
+
+
+
+        List<String> params = buildFilter(filterBuilder, filter,  new String[] {
+                "serialNumber",
+                "description",
+                "owner.description",
+                "owner.name"
+        });
+
+
+        String sql = "SELECT d FROM Device d " + filterBuilder.toString();
+
+        TypedQuery<Device> query = entityManager.createQuery(sql, Device.class);
+        for (int i = 0; i < params.size(); i++) {
+            query.setParameter("param_" + i, params.get(i));
+        }
+
+        if (isDistributor()) {
+            query.setParameter("distributor", user.get().getDistributor());
+        }
+
+
+        List<Device> devices = query.getResultList();
+
+        return devices;
+    }
+
+    public Device getDevice(Integer id, Principal principal) throws UserNotFoundException {
+        BGatesUserDetails userDetails = getUserDetails(principal);
+
+
+        return deviceRepository.findById(id).orElse(null);
+
+    }
+
+    public Device save(Device device, Principal principal) throws UserNotFoundException {
+        getUserDetails(principal);
+
+        if (isDistributor()) {
+            Optional<User> user = userService.getById(userDetails.getId());
+            if (user.isEmpty()) {
+                throw new UserNotFoundException("User not found");
+            }
+            device.setDistributor(user.get().getDistributor());
+        }
+
+        return deviceRepository.save(device);
+    }
+
+
+}

+ 107 - 0
src/main/java/it/bgates/remotebe/service/DistributorService.java

@@ -0,0 +1,107 @@
+package it.bgates.remotebe.service;
+
+import it.bgates.remotebe.entities.Distributor;
+import it.bgates.remotebe.entities.User;
+import it.bgates.remotebe.exception.PermissionDeniedException;
+import it.bgates.remotebe.exception.UserNotFoundException;
+import it.bgates.remotebe.repository.DistributorRepository;
+import it.bgates.remotebe.repository.UserRepository;
+import jakarta.persistence.EntityManager;
+import jakarta.persistence.TypedQuery;
+import lombok.RequiredArgsConstructor;
+import org.springframework.stereotype.Service;
+
+import java.security.Principal;
+import java.util.List;
+import java.util.Optional;
+
+@Service
+@RequiredArgsConstructor
+public class DistributorService extends BaseService {
+
+    private final DistributorRepository distributorRepository;
+    private final UserRepository userRepository;
+    private final EntityManager entityManager;
+
+    /***
+     * returns the list of distributors accessible the currently logged user
+     * If the user is an admin, returns all the distributors
+     * If the user is a distributor, returns only itself
+     * @param principal
+     * @return
+     */
+    public List<Distributor> getDistributors(Principal principal) throws UserNotFoundException {
+        getUserDetails(principal);
+
+        Optional<User> user = userRepository.findByUsername(userDetails.getUsername());
+        if (user.isEmpty()) {
+            return List.of();
+        }
+
+        if (isSuperUser()) {
+            return distributorRepository.findAllByOrderByName();
+        }
+        if (isDistributor()) {
+            return List.of(user.get().getDistributor());
+        }
+
+        return List.of();
+    }
+
+    public Distributor save(Distributor distributor, Principal principal) throws UserNotFoundException, PermissionDeniedException {
+        getUserDetails(principal);
+
+        if (!isSuperUser() && distributor.getId() == null) {
+            throw new PermissionDeniedException("Accesso negato");
+        }
+
+        return distributorRepository.save(distributor);
+    }
+
+    public Distributor getDistributorById(Integer id) {
+        return distributorRepository.findById(id).orElse(null);
+    }
+
+    public List<Distributor> filter(String filter, Principal principal) throws UserNotFoundException {
+        getUserDetails(principal);
+
+        Optional<User> user = userRepository.findByUsername(userDetails.getUsername());
+        if (user.isEmpty()) {
+            return List.of();
+        }
+
+        StringBuilder filterBuilder = new StringBuilder();
+
+        if (isDistributor()) {
+            filterBuilder.append("WHERE d = :distributor");
+        } else if (isSuperUser()) {
+            filterBuilder.append("WHERE true");
+        } else if (isUser()) {
+            filterBuilder.append("WHERE false");
+        }
+
+        List<String> params = buildFilter(filterBuilder, filter,  new String[] {
+                "name",
+                "vatNumber",
+                "city"
+        });
+
+
+        String sql = "SELECT d FROM Distributor d " + filterBuilder.toString();
+        TypedQuery<Distributor> query = entityManager.createQuery(sql, Distributor.class);
+        for (int i = 0; i < params.size(); i++) {
+            query.setParameter("param_" + i, params.get(i));
+        }
+
+        for (int i = 0; i < params.size(); i++) {
+            query.setParameter("param_" + i, params.get(i));
+        }
+
+        if (isDistributor()) {
+            query.setParameter("distributor", user.get().getDistributor());
+        }
+
+        List<Distributor> distributors = query.getResultList();
+        return distributors;
+    }
+}

+ 33 - 0
src/main/java/it/bgates/remotebe/service/InstallerService.java

@@ -0,0 +1,33 @@
+package it.bgates.remotebe.service;
+
+import it.bgates.remotebe.config.BGatesUserDetails;
+import it.bgates.remotebe.entities.Installer;
+import it.bgates.remotebe.exception.PermissionDeniedException;
+import it.bgates.remotebe.exception.UserNotFoundException;
+import it.bgates.remotebe.repository.InstallerRepository;
+import lombok.RequiredArgsConstructor;
+import org.springframework.stereotype.Service;
+
+import java.security.Principal;
+import java.util.List;
+
+@Service
+@RequiredArgsConstructor
+public class InstallerService extends BaseService {
+
+    private final InstallerRepository installerRepository;
+
+    public List<Installer> getAllInstallers(Principal principal) throws UserNotFoundException {
+        getUserDetails(principal);
+
+        return installerRepository.findAllOrderByName();
+    }
+
+    public Installer save(Installer installer, Principal principal) throws UserNotFoundException, PermissionDeniedException {
+        getUserDetails(principal);
+        if (isUser()){
+            throw new PermissionDeniedException("Accesso negato");
+        }
+        return installerRepository.save(installer);
+    }
+}

+ 127 - 0
src/main/java/it/bgates/remotebe/service/PhoneService.java

@@ -0,0 +1,127 @@
+package it.bgates.remotebe.service;
+
+import it.bgates.remotebe.entities.Device;
+import it.bgates.remotebe.entities.Phone;
+import it.bgates.remotebe.entities.User;
+import it.bgates.remotebe.exception.NotFoundException;
+import it.bgates.remotebe.exception.UserNotFoundException;
+import it.bgates.remotebe.repository.PhoneRepository;
+import it.bgates.remotebe.repository.UserRepository;
+import jakarta.persistence.EntityManager;
+import jakarta.persistence.TypedQuery;
+import jakarta.validation.Valid;
+import lombok.RequiredArgsConstructor;
+import org.aspectj.weaver.ast.Not;
+import org.springframework.stereotype.Service;
+
+import java.security.Principal;
+import java.time.LocalDateTime;
+import java.util.List;
+import java.util.Optional;
+
+import static org.springframework.data.jpa.domain.AbstractPersistable_.id;
+
+@Service
+@RequiredArgsConstructor
+public class PhoneService extends BaseService{
+    private final PhoneRepository phoneRepository;
+    private final DeviceService deviceService;
+    private final UserRepository userRepository;
+    private final EntityManager entityManager;
+
+    public List<Phone> getPhonesByDeviceId(Integer deviceId, Principal principal) throws UserNotFoundException, NotFoundException {
+        Device device = deviceService.getDevice(deviceId, principal);
+
+        if (device == null) {
+            throw new NotFoundException("Device not found");
+        }
+
+        return phoneRepository.findByDevice(device);
+    }
+
+    public Phone addPhone(@Valid Phone phone, Principal principal) {
+        if (phone.getId() == null) {
+            phone.setCreateDate(LocalDateTime.now());
+        }
+        return phoneRepository.save(phone);
+    }
+
+    public List<Phone> filter(String filter, Principal principal) throws UserNotFoundException {
+        getUserDetails(principal);
+
+        Optional<User> user = userRepository.findByUsername(userDetails.getUsername());
+        if (user.isEmpty()) {
+            return List.of();
+        }
+
+        StringBuilder filterBuilder = new StringBuilder();
+
+        String join = "";
+
+        if (isSuperUser()) {
+             filterBuilder.append("WHERE true");
+        } else if (isDistributor()) {
+            filterBuilder.append("join device d on d.id = p.device.id");
+            filterBuilder.append("WHERE d.distributor = :distributor");
+        } else if (isUser()) {
+            filterBuilder.append("join device d on d.id = p.device.id");
+            filterBuilder.append("join p.device.owner o on o.id = p.device.owner.id");
+            filterBuilder.append("WHERE o.id=:ownerId");
+
+        } else {
+            filterBuilder.append("WHERE false");
+        }
+
+
+        List<String> params = buildFilter(filterBuilder, filter,  new String[]{
+                "phoneNumber",
+                "description"
+        });
+
+        String sql = "SELECT p FROM Phone p" + System.lineSeparator() +
+                filterBuilder + System.lineSeparator() +
+                "ORDER BY p.description";
+
+        TypedQuery<Phone> query = entityManager.createQuery(sql, Phone.class);
+        for (int i = 0; i < params.size(); i++) {
+            query.setParameter("param_" + i, params.get(i));
+        }
+
+        if (isDistributor()) {
+            query.setParameter("distributor", user.get().getDistributor());
+        } else if (isUser()) {
+            query.setParameter("ownerId", user.get().getId());
+        }
+
+        List<Phone> phones = query.getResultList();
+        return phones;
+
+
+    }
+
+    public Boolean deactivatePhone(Integer phoneId, Principal principal) throws NotFoundException, UserNotFoundException {
+        getUserDetails(principal);
+
+        Optional<Phone> phone = phoneRepository.findById(phoneId);
+        if (phone.isPresent()) {
+            phone.get().setActive(false);
+            phoneRepository.save(phone.get());
+            return true;
+        }
+        throw new NotFoundException("Telefono non trovato");
+    }
+
+    public Boolean activatePhone(Integer phoneId, Principal principal) throws NotFoundException, UserNotFoundException {
+        getUserDetails(principal);
+
+        Optional<Phone> phone = phoneRepository.findById(phoneId);
+        if (phone.isPresent()) {
+            phone.get().setActive(true);
+            phoneRepository.save(phone.get());
+            return true;
+        }
+        throw new NotFoundException("Telefono non trovato");
+    }
+
+
+}

+ 9 - 0
src/main/java/it/bgates/remotebe/service/QueryParameter.java

@@ -0,0 +1,9 @@
+package it.bgates.remotebe.service;
+
+import lombok.Data;
+
+@Data
+public class QueryParameter {
+    private String paramName;
+    private String paramValue;
+}

+ 140 - 0
src/main/java/it/bgates/remotebe/service/UserService.java

@@ -0,0 +1,140 @@
+package it.bgates.remotebe.service;
+
+import it.bgates.remotebe.config.BGatesUserDetails;
+import it.bgates.remotebe.controller.auth.beans.NewUserBean;
+import it.bgates.remotebe.entities.Distributor;
+import it.bgates.remotebe.entities.Role;
+import it.bgates.remotebe.entities.User;
+import it.bgates.remotebe.entities.base.Person;
+import it.bgates.remotebe.entities.enums.BGatesUserType;
+import it.bgates.remotebe.exception.PermissionDeniedException;
+import it.bgates.remotebe.exception.UserNotFoundException;
+import it.bgates.remotebe.repository.UserRepository;
+import lombok.RequiredArgsConstructor;
+import org.springframework.stereotype.Service;
+
+import java.security.Principal;
+import java.util.List;
+import java.util.Optional;
+
+@Service
+@RequiredArgsConstructor
+public class UserService extends BaseService{
+
+    private final UserRepository userRepository;
+    private final DistributorService distributorService;
+
+    public Optional<User> getById(Integer id) {
+        return userRepository.findById(id);
+    }
+    public Optional<User> findByUsername(String username) {
+        return userRepository.findByUsername(username);
+    }
+
+    /***
+     * Save user
+     * @param user: user to save
+     * @param principal: logged user
+     * @return saves a new user or updates an existing one
+     * Check if the principal has authority to save the user
+     */
+    public User save(NewUserBean user, Principal principal) throws PermissionDeniedException, UserNotFoundException {
+        getUserDetails(principal);
+        if (user.getId() == null && !canCreateUsers(principal)) {
+            throw new PermissionDeniedException("Permesso negato");
+        }
+
+        User userToSave = user.getId() == null
+            ? new User()
+            : userRepository.findById(user.getId()).orElse(new User() );
+
+        if (userToSave.getPerson() == null) {
+            userToSave.setPerson(new Person());
+        }
+
+        userToSave.setUsername(user.getUsername());
+        userToSave.setPassword(user.getPassword());
+        userToSave.getPerson().setFirstname(user.getFirstname());
+        userToSave.getPerson().setLastname(user.getLastname());
+        userToSave.getPerson().setEmail(user.getEmail());
+        userToSave.getPerson().setPhone(user.getPhone());
+        userToSave.getPerson().setMobilePhone(user.getMobilePhone());
+        userToSave.getPerson().setAddress(user.getAddress());
+        userToSave.getPerson().setCity(user.getCity());
+        userToSave.getPerson().setZip(user.getZip());
+        userToSave.setEnabled(true);
+
+
+        if (isDistributor()) {
+            if (user.getUserType() == null || user.getUserType().equals(BGatesUserType.ADMIN.ordinal())) {
+                userToSave.setUserType(BGatesUserType.USER);
+            }
+
+            userToSave.setDistributor(userDetails.getDistributor());
+        } else if (isSuperUser()) {
+            Distributor distributor = distributorService.getDistributorById(user.getDistributorId());
+            if (distributor == null) {
+                throw new RuntimeException("Distributore non trovato");
+            }
+            userToSave.setDistributor(distributor);
+            userToSave.setUserType(BGatesUserType.values()[user.getUserType()]);
+        }
+
+        return userRepository.save(userToSave);
+    }
+
+    public boolean canCreateUsers(Principal principal) {
+        BGatesUserDetails userDetails = null;
+        try {
+            userDetails = getUserDetails(principal);
+        } catch (UserNotFoundException e) {
+            return false;
+        }
+        return userDetails.getAuthorities().stream()
+                .anyMatch(a -> {
+                    return a.getAuthority().equals(Role.SUPER_USER) ||
+                            a.getAuthority().equals(Role.DISTRIBUTOR);
+                });
+    }
+
+    public Boolean disableUser(Integer id, Principal principal) throws UserNotFoundException, PermissionDeniedException {
+        BGatesUserDetails userDetails = getUserDetails(principal);
+
+        User user = userRepository.findById(id).orElse(null);
+        if (user == null) {
+            throw new UserNotFoundException("Utente non trovato");
+        }
+
+        // if userDetails is super_admin -> disable user
+        // if userDetails is installer -> disable user if the user is in a company handled by the installer
+
+        if (isUser()) {
+            throw new PermissionDeniedException("Permesso negato");
+        }
+
+        if (isDistributor()) {
+            // user.getCustomer().get
+
+        }
+
+
+        if (userDetails.getUsername().equals(user.getUsername())) {
+            user.setEnabled(false);
+            userRepository.save(user);
+            return true;
+        } else {
+            return false;
+        }
+    }
+
+    public List<User> getUsers(Principal principal) throws UserNotFoundException {
+        userDetails = getUserDetails(principal);
+        if (isDistributor()){
+            return userRepository.findAllByDistributorOrderByUsername(userDetails.getDistributor());
+        }
+        if (isSuperUser()) {
+            return userRepository.findAllByOrderByUsername();
+        }
+        return List.of();
+    }
+}

+ 177 - 0
src/main/java/it/bgates/remotebe/service/auth/AuthService.java

@@ -0,0 +1,177 @@
+package it.bgates.remotebe.service.auth;
+
+import com.fasterxml.jackson.databind.ObjectMapper;
+import it.bgates.remotebe.config.BGatesUserDetailService;
+import it.bgates.remotebe.config.BGatesUserDetails;
+import it.bgates.remotebe.config.JwtService;
+import it.bgates.remotebe.controller.auth.beans.AuthenticationRequest;
+import it.bgates.remotebe.controller.auth.beans.AuthenticationResponse;
+import it.bgates.remotebe.controller.auth.beans.RefreshTokenRequest;
+import it.bgates.remotebe.entities.Role;
+import it.bgates.remotebe.entities.User;
+import it.bgates.remotebe.entities.token.RefreshToken;
+import it.bgates.remotebe.entities.token.Token;
+import it.bgates.remotebe.entities.token.TokenRepository;
+import it.bgates.remotebe.exception.AutorizationMissingException;
+import it.bgates.remotebe.exception.DisabledUserException;
+import it.bgates.remotebe.exception.UserNotFoundException;
+import it.bgates.remotebe.service.UserService;
+import jakarta.servlet.http.HttpServletRequest;
+import jakarta.servlet.http.HttpServletResponse;
+import jakarta.validation.Valid;
+import lombok.RequiredArgsConstructor;
+import org.springframework.http.HttpHeaders;
+import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
+import org.springframework.security.core.Authentication;
+import org.springframework.security.core.AuthenticationException;
+import org.springframework.security.core.authority.AuthorityUtils;
+import org.springframework.security.core.context.SecurityContextHolder;
+import org.springframework.security.core.userdetails.UserDetails;
+import org.springframework.security.core.userdetails.UsernameNotFoundException;
+import org.springframework.security.oauth2.jwt.Jwt;
+import org.springframework.stereotype.Service;
+
+import java.io.IOException;
+import java.security.Principal;
+import java.time.Instant;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Optional;
+import java.util.stream.Collectors;
+
+@Service
+@RequiredArgsConstructor
+public class AuthService {
+
+    private final BGatesUserDetailService authenticationProvider;
+    private final JwtService jwtService;
+    private final BGatesUserDetailService userDetailsService;
+    private final TokenRepository tokenRepository;
+    private final RefreshTokenService refreshTokenService;
+    private final UserService userService;
+
+    /***
+     *
+     * @param request (username, password)
+     * @return AuthenticationResponse con dettagli per l'autenticazione
+     *  accessToken, refreshToken, expirationTime, ...
+     */
+    public AuthenticationResponse authenticate(AuthenticationRequest request)
+            throws AuthenticationException, DisabledUserException, UserNotFoundException {
+
+        Authentication authentication = authenticationProvider.authenticate(
+                new UsernamePasswordAuthenticationToken(
+                        request.getUsername(),
+                        request.getPassword()
+                )
+        );
+
+        // recupera utente
+        UserDetails userDetails = (UserDetails) authentication.getPrincipal();
+        Optional<User> user = userService.findByUsername(userDetails.getUsername());
+
+        if (user.isEmpty()) {
+            throw new UserNotFoundException("User not found");
+        }
+
+        if (!user.get().getEnabled()) {
+            throw new DisabledUserException("User not enabled");
+        }
+
+        var jwtToken = jwtService.generateToken(userDetails);
+        var refreshToken = jwtService.generateRefreshToken(userDetails);
+        revokeAllUserTokens(userDetails);
+        saveUserToken(userDetails, jwtToken);
+
+        List<String> roles = user.get().getRoles().stream()
+                .map(Role::getName)
+                .collect(Collectors.toList());
+
+        List<String> authorities = new ArrayList<>();
+        for (Role role:  user.get().getRoles()) {
+            role.getPrivileges().forEach(privilege -> authorities.add(privilege.getName()));
+        }
+
+
+        return AuthenticationResponse.builder()
+                .accessToken(jwtToken)
+                .refreshToken(refreshToken)
+                .username(userDetails.getUsername())
+                .authorities(authorities)
+                .roles(roles)
+                .build();
+    }
+
+    /***
+     * Logout user
+     * @param name
+     */
+    public void logout(String name) {
+        tokenRepository.findAllValidTokenByUser(name).forEach(token -> {
+            token.setRevoked(true);
+            token.setExpired(true);
+            tokenRepository.save(token);
+        });
+    }
+
+
+
+    private void saveUserToken(UserDetails user, String jwtToken) {
+        var token = Token.builder()
+                .username(user.getUsername())
+                .token(jwtToken)
+                .expired(false)
+                .revoked(false)
+                .build();
+        tokenRepository.save(token);
+    }
+
+    private void revokeAllUserTokens(UserDetails user) {
+        var validUserTokens = tokenRepository.findAllValidTokenByUser(user.getUsername());
+        if (validUserTokens.isEmpty())
+            return;
+        validUserTokens.forEach(token -> {
+            token.setExpired(true);
+            token.setRevoked(true);
+        });
+        tokenRepository.saveAll(validUserTokens);
+    }
+
+    public void refreshToken(
+            HttpServletRequest request,
+            HttpServletResponse response
+    ) throws IOException {
+        final String authHeader = request.getHeader(HttpHeaders.AUTHORIZATION);
+        final String refreshToken;
+        final String username;
+        if (authHeader == null ||!authHeader.startsWith("Bearer ")) {
+            return;
+        }
+        refreshToken = authHeader.substring(7);
+        username = jwtService.extractUsername(refreshToken);
+        if (username != null) {
+            BGatesUserDetails userDetails = userDetailsService.loadUserByUsername(username);
+
+            if (jwtService.isTokenValid(refreshToken, userDetails)) {
+                var accessToken = jwtService.generateToken(userDetails);
+                revokeAllUserTokens(userDetails);
+                saveUserToken(userDetails, accessToken);
+                var authResponse = AuthenticationResponse.builder()
+                        .accessToken(accessToken)
+                        .refreshToken(refreshToken)
+                        .username(username)
+                        .build();
+                new ObjectMapper().writeValue(response.getOutputStream(), authResponse);
+            }
+        }
+    }
+
+    @org.springframework.transaction.annotation.Transactional(readOnly = true)
+    public BGatesUserDetails getCurrentUser() {
+        // System.out.println(SecurityContextHolder.getContext().getAuthentication().getPrincipal());
+        BGatesUserDetails principal = (BGatesUserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
+        return userDetailsService.loadUserByUsername(principal.getUsername());
+    }
+
+}
+

+ 47 - 0
src/main/java/it/bgates/remotebe/service/auth/RefreshTokenService.java

@@ -0,0 +1,47 @@
+package it.bgates.remotebe.service.auth;
+
+import it.bgates.remotebe.config.JwtService;
+import it.bgates.remotebe.entities.token.RefreshToken;
+import it.bgates.remotebe.entities.token.RefreshTokenRepository;
+import lombok.AllArgsConstructor;
+import org.springframework.stereotype.Service;
+import org.springframework.transaction.annotation.Transactional;
+
+import java.time.Instant;
+import java.util.UUID;
+
+@Service
+@AllArgsConstructor
+@Transactional
+public class RefreshTokenService {
+
+    private final RefreshTokenRepository refreshTokenRepository;
+    private final JwtService jwtService;
+
+    public RefreshToken generateRefreshToken() {
+        RefreshToken refreshToken = new RefreshToken();
+        refreshToken.setToken(UUID.randomUUID().toString());
+        refreshToken.setCreatedDate(Instant.now());
+
+        return refreshTokenRepository.save(refreshToken);
+    }
+
+    boolean validateRefreshToken(String token) {
+        RefreshToken refreshToken = refreshTokenRepository.findByToken(token)
+                .orElseThrow(() -> new RuntimeException("Invalid session"));
+
+        try {
+            Instant expiresAt = refreshToken.getCreatedDate().plusMillis(jwtService.getRefreshExpiration());
+            boolean isExpired = expiresAt.isBefore(Instant.now());
+            return !isExpired;
+        } catch (Exception e) {
+            throw new RuntimeException("Session expired");
+        }
+
+    }
+
+    public void deleteRefreshToken(String token) {
+        refreshTokenRepository.deleteByToken(token);
+    }
+
+}

+ 28 - 0
src/main/resources/app.key

@@ -0,0 +1,28 @@
+-----BEGIN PRIVATE KEY-----
+MIIEvwIBADANBgkqhkiG9w0BAQEFAASCBKkwggSlAgEAAoIBAQDcWWomvlNGyQhA
+iB0TcN3sP2VuhZ1xNRPxr58lHswC9Cbtdc2hiSbe/sxAvU1i0O8vaXwICdzRZ1JM
+g1TohG9zkqqjZDhyw1f1Ic6YR/OhE6NCpqERy97WMFeW6gJd1i5inHj/W19GAbqK
+LhSHGHqIjyo0wlBf58t+qFt9h/EFBVE/LAGQBsg/jHUQCxsLoVI2aSELGIw2oSDF
+oiljwLaQl0n9khX5ZbiegN3OkqodzCYHwWyu6aVVj8M1W9RIMiKmKr09s/gf31Nc
+3WjvjqhFo1rTuurWGgKAxJLL7zlJqAKjGWbIT4P6h/1Kwxjw6X23St3OmhsG6HIn
++jl1++MrAgMBAAECggEBAMf820wop3pyUOwI3aLcaH7YFx5VZMzvqJdNlvpg1jbE
+E2Sn66b1zPLNfOIxLcBG8x8r9Ody1Bi2Vsqc0/5o3KKfdgHvnxAB3Z3dPh2WCDek
+lCOVClEVoLzziTuuTdGO5/CWJXdWHcVzIjPxmK34eJXioiLaTYqN3XKqKMdpD0ZG
+mtNTGvGf+9fQ4i94t0WqIxpMpGt7NM4RHy3+Onggev0zLiDANC23mWrTsUgect/7
+62TYg8g1bKwLAb9wCBT+BiOuCc2wrArRLOJgUkj/F4/gtrR9ima34SvWUyoUaKA0
+bi4YBX9l8oJwFGHbU9uFGEMnH0T/V0KtIB7qetReywkCgYEA9cFyfBIQrYISV/OA
++Z0bo3vh2aL0QgKrSXZ924cLt7itQAHNZ2ya+e3JRlTczi5mnWfjPWZ6eJB/8MlH
+Gpn12o/POEkU+XjZZSPe1RWGt5g0S3lWqyx9toCS9ACXcN9tGbaqcFSVI73zVTRA
+8J9grR0fbGn7jaTlTX2tnlOTQ60CgYEA5YjYpEq4L8UUMFkuj+BsS3u0oEBnzuHd
+I9LEHmN+CMPosvabQu5wkJXLuqo2TxRnAznsA8R3pCLkdPGoWMCiWRAsCn979TdY
+QbqO2qvBAD2Q19GtY7lIu6C35/enQWzJUMQE3WW0OvjLzZ0l/9mA2FBRR+3F9A1d
+rBdnmv0c3TcCgYEAi2i+ggVZcqPbtgrLOk5WVGo9F1GqUBvlgNn30WWNTx4zIaEk
+HSxtyaOLTxtq2odV7Kr3LGiKxwPpn/T+Ief+oIp92YcTn+VfJVGw4Z3BezqbR8lA
+Uf/+HF5ZfpMrVXtZD4Igs3I33Duv4sCuqhEvLWTc44pHifVloozNxYfRfU0CgYBN
+HXa7a6cJ1Yp829l62QlJKtx6Ymj95oAnQu5Ez2ROiZMqXRO4nucOjGUP55Orac1a
+FiGm+mC/skFS0MWgW8evaHGDbWU180wheQ35hW6oKAb7myRHtr4q20ouEtQMdQIF
+snV39G1iyqeeAsf7dxWElydXpRi2b68i3BIgzhzebQKBgQCdUQuTsqV9y/JFpu6H
+c5TVvhG/ubfBspI5DhQqIGijnVBzFT//UfIYMSKJo75qqBEyP2EJSmCsunWsAFsM
+TszuiGTkrKcZy9G0wJqPztZZl2F2+bJgnA6nBEV7g5PA4Af+QSmaIhRwqGDAuROR
+47jndeyIaMTNETEmOnms+as17g==
+-----END PRIVATE KEY-----

+ 9 - 0
src/main/resources/app.pub

@@ -0,0 +1,9 @@
+-----BEGIN PUBLIC KEY-----
+MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA3FlqJr5TRskIQIgdE3Dd
+7D9lboWdcTUT8a+fJR7MAvQm7XXNoYkm3v7MQL1NYtDvL2l8CAnc0WdSTINU6IRv
+c5Kqo2Q4csNX9SHOmEfzoROjQqahEcve1jBXluoCXdYuYpx4/1tfRgG6ii4Uhxh6
+iI8qNMJQX+fLfqhbfYfxBQVRPywBkAbIP4x1EAsbC6FSNmkhCxiMNqEgxaIpY8C2
+kJdJ/ZIV+WW4noDdzpKqHcwmB8FsrumlVY/DNVvUSDIipiq9PbP4H99TXN1o746o
+RaNa07rq1hoCgMSSy+85SagCoxlmyE+D+of9SsMY8Ol9t0rdzpobBuhyJ/o5dfvj
+KwIDAQAB
+-----END PUBLIC KEY-----

+ 25 - 0
src/main/resources/application-dev.properties

@@ -0,0 +1,25 @@
+
+server.port = 9100
+
+#DB connection
+spring.datasource.url=jdbc:mariadb://127.0.0.1:3306/remote?autoReconnect=true&zeroDateTimeBehavior=convertToNull&serverTimezone=Europe/Rome
+spring.datasource.username=root
+spring.datasource.password=kranio-10
+
+spring.datasource.driver-class-name=org.mariadb.jdbc.Driver
+# spring.jpa.database-platform=org.hibernate.dialect.MariaDBDialect
+spring.jpa.show-sql=true
+
+spring.jpa.hibernate.ddl-auto=update
+#update
+spring.session.jdbc.initialize-schema=always
+
+#database pooling
+spring.datasource.hikari.maximum-pool-size=50
+
+# detailed error reporting
+server.error.include-message=always
+server.servlet.session.timeout=600s
+server.error.include-stacktrace=always
+
+

+ 26 - 0
src/main/resources/application-prod.properties

@@ -0,0 +1,26 @@
+spring.application.name=remote-be
+
+server.port = 9100
+
+spring.datasource.url=jdbc:mariadb://127.0.0.1:3306/remote?autoReconnect=true&zeroDateTimeBehavior=convertToNull&serverTimezone=Europe/Rome
+spring.datasource.username=remote
+spring.datasource.password=manager
+
+spring.datasource.driver-class-name=org.mariadb.jdbc.Driver
+# spring.jpa.database-platform=org.hibernate.dialect.MariaDBDialect
+spring.jpa.show-sql=true
+
+spring.jpa.hibernate.ddl-auto=update
+#update
+spring.session.jdbc.initialize-schema=always
+
+
+
+#database pooling
+spring.datasource.hikari.maximum-pool-size=50
+
+# detailed error reporting
+# server.error.include-stacktrace=never
+server.error.include-stacktrace=always
+server.error.include-message=always
+server.servlet.session.timeout=600s

+ 16 - 0
src/main/resources/application.properties

@@ -0,0 +1,16 @@
+spring.profiles.active=${SPRING_PROFILES_ACTIVE:dev}
+
+spring.application.name=remote-be
+
+
+application.security.jwt.secret-key=404E635266556A586E3272357538782F413F4428472B4B6250645367566B5970
+application.security.jwt.expiration=600000
+application.security.jwt.refresh-token.expiration=604800000
+
+spring.datasource.driver-class-name=org.mariadb.jdbc.Driver
+spring.jpa.database-platform=org.hibernate.dialect.MariaDBDialect
+
+# swagger-ui custom path
+springdoc.swagger-ui.path=/v3/swagger-ui.html
+
+

+ 13 - 0
src/test/java/it/bgates/remotebe/RemoteBeApplicationTests.java

@@ -0,0 +1,13 @@
+package it.bgates.remotebe;
+
+import org.junit.jupiter.api.Test;
+import org.springframework.boot.test.context.SpringBootTest;
+
+@SpringBootTest
+class RemoteBeApplicationTests {
+
+    @Test
+    void contextLoads() {
+    }
+
+}