commit 4869b53c3c984df67461bc0f46a241f4c739b2ca Author: Jari Date: Mon Mar 10 22:54:26 2025 +0100 base commit diff --git a/lorca-core/.env b/lorca-core/.env new file mode 100644 index 0000000..a3e2f88 --- /dev/null +++ b/lorca-core/.env @@ -0,0 +1,5 @@ +POSTGRES_USER=lorca_usr +POSTGRES_PW=lorca_pwd +POSTGRES_DB=lorca_db +PGADMIN_MAIL=scijar@gmail.com +PGADMIN_PW=lorcapwd diff --git a/lorca-core/.gitattributes b/lorca-core/.gitattributes new file mode 100644 index 0000000..8af972c --- /dev/null +++ b/lorca-core/.gitattributes @@ -0,0 +1,3 @@ +/gradlew text eol=lf +*.bat text eol=crlf +*.jar binary diff --git a/lorca-core/.gitignore b/lorca-core/.gitignore new file mode 100644 index 0000000..5a979af --- /dev/null +++ b/lorca-core/.gitignore @@ -0,0 +1,40 @@ +HELP.md +.gradle +build/ +!gradle/wrapper/gradle-wrapper.jar +!**/src/main/**/build/ +!**/src/test/**/build/ + +### STS ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans +.sts4-cache +bin/ +!**/src/main/**/bin/ +!**/src/test/**/bin/ + +### IntelliJ IDEA ### +.idea +*.iws +*.iml +*.ipr +out/ +!**/src/main/**/out/ +!**/src/test/**/out/ + +### NetBeans ### +/nbproject/private/ +/nbbuild/ +/dist/ +/nbdist/ +/.nb-gradle/ + +### VS Code ### +.vscode/ + +### Kotlin ### +.kotlin diff --git a/lorca-core/Dockerfile b/lorca-core/Dockerfile new file mode 100644 index 0000000..58fb3eb --- /dev/null +++ b/lorca-core/Dockerfile @@ -0,0 +1,31 @@ +# Step 1: Build the application using Eclipse Temurin JDK 21 +FROM maven:3.9.8-eclipse-temurin-21 AS build + +WORKDIR /app + +# Copy Gradle wrapper and dependencies for caching +COPY gradle gradle +COPY gradlew . +COPY build.gradle.kts . +COPY settings.gradle.kts . +COPY src src + +# Give execution permission to Gradle wrapper +RUN chmod +x ./gradlew + +# Build the JAR file +RUN ./gradlew bootJar + +# Step 2: Create a minimal runtime image (JDK is required for Spring Boot) + +FROM openjdk:21 +WORKDIR /app + +# Copy the built JAR from the builder stage +COPY --from=build /app/build/libs/*.jar app.jar + +# Expose port 8080 +EXPOSE 8080 + +# Run the application +ENTRYPOINT ["java", "-jar", "/app/app.jar"] diff --git a/lorca-core/build.gradle.kts b/lorca-core/build.gradle.kts new file mode 100644 index 0000000..5678e4c --- /dev/null +++ b/lorca-core/build.gradle.kts @@ -0,0 +1,79 @@ +plugins { + kotlin("jvm") version "1.9.25" + kotlin("plugin.spring") version "1.9.25" + id("org.springframework.boot") version "3.4.3" + id("io.spring.dependency-management") version "1.1.7" + kotlin("plugin.jpa") version "1.9.25" + kotlin("kapt") version "1.9.25" + +} + +group = "org.js" +version = "0.0.1-SNAPSHOT" + + +java { + toolchain { + languageVersion = JavaLanguageVersion.of(21) + } +} + +configurations { + compileOnly { + extendsFrom(configurations.annotationProcessor.get()) + } +} + +kapt { + correctErrorTypes = true +} + +repositories { + mavenCentral() +} + +dependencies { + implementation("org.springframework.boot:spring-boot-starter-data-jpa") + implementation("org.springframework.boot:spring-boot-starter-mail") + implementation("org.springframework.boot:spring-boot-starter-security") + implementation("org.springframework.boot:spring-boot-starter-web") + implementation("com.fasterxml.jackson.module:jackson-module-kotlin") + implementation("org.springframework.boot:spring-boot-starter") + implementation("org.springframework.boot:spring-boot-starter-validation") + implementation("org.springframework.boot:spring-boot-starter-actuator") + developmentOnly("org.springframework.boot:spring-boot-devtools") + implementation("org.postgresql:postgresql:42.7.2") + implementation("org.jetbrains.kotlin:kotlin-reflect") + compileOnly("org.projectlombok:lombok") + annotationProcessor("org.projectlombok:lombok") + + implementation("org.mapstruct:mapstruct:1.6.0") + kapt("org.mapstruct:mapstruct-processor:1.6.0") + implementation("org.springframework.boot:spring-boot-starter-web") + implementation("org.jetbrains.kotlin:kotlin-reflect") + kapt("org.springframework.boot:spring-boot-configuration-processor") + + implementation("io.jsonwebtoken:jjwt-api:0.12.6") + runtimeOnly("io.jsonwebtoken:jjwt-impl:0.12.6") + runtimeOnly("io.jsonwebtoken:jjwt-gson:0.12.6") +} + +kotlin { + compilerOptions { + freeCompilerArgs.addAll("-Xjsr305=strict") + } +} + +allOpen { + annotation("jakarta.persistence.Entity") + annotation("jakarta.persistence.MappedSuperclass") + annotation("jakarta.persistence.Embeddable") +} + +tasks.withType { + useJUnitPlatform() +} + +tasks.register("testJeko") { + commandLine("docker", "build", "-t", "be-local:$version", ".") +} diff --git a/lorca-core/compose.yaml b/lorca-core/compose.yaml new file mode 100644 index 0000000..e2f7eb8 --- /dev/null +++ b/lorca-core/compose.yaml @@ -0,0 +1,38 @@ +services: + app: + image: be-local + container_name: be + ports: + - "8080:8081" + environment: + SPRING_DATASOURCE_URL: jdbc:postgresql://db:5432/lorca_db + SPRING_DATASOURCE_USERNAME: lorca_usr + SPRING_DATASOURCE_PASSWORD: lorca_pwd + depends_on: + - db + + db: + container_name: postgres + image: postgres:latest + restart: always + environment: + - POSTGRES_USER=${POSTGRES_USER} + - POSTGRES_PASSWORD=${POSTGRES_PW} + - POSTGRES_DB=${POSTGRES_DB} + ports: + - "5432:5432" + volumes: + - pgdata:/var/lib/postgresql/data + + pgadmin: + container_name: pgadmin + image: dpage/pgadmin4:latest + environment: + - PGADMIN_DEFAULT_EMAIL=${PGADMIN_MAIL} + - PGADMIN_DEFAULT_PASSWORD=${PGADMIN_PW} + ports: + - "5050:80" + restart: always + +volumes: + pgdata: \ No newline at end of file diff --git a/lorca-core/gradle/wrapper/gradle-wrapper.jar b/lorca-core/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 0000000..a4b76b9 Binary files /dev/null and b/lorca-core/gradle/wrapper/gradle-wrapper.jar differ diff --git a/lorca-core/gradle/wrapper/gradle-wrapper.properties b/lorca-core/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 0000000..e18bc25 --- /dev/null +++ b/lorca-core/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,7 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-8.12.1-bin.zip +networkTimeout=10000 +validateDistributionUrl=true +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/lorca-core/gradlew b/lorca-core/gradlew new file mode 100644 index 0000000..f5feea6 --- /dev/null +++ b/lorca-core/gradlew @@ -0,0 +1,252 @@ +#!/bin/sh + +# +# Copyright © 2015-2021 the original authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# SPDX-License-Identifier: Apache-2.0 +# + +############################################################################## +# +# Gradle start up script for POSIX generated by Gradle. +# +# Important for running: +# +# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is +# noncompliant, but you have some other compliant shell such as ksh or +# bash, then to run this script, type that shell name before the whole +# command line, like: +# +# ksh Gradle +# +# Busybox and similar reduced shells will NOT work, because this script +# requires all of these POSIX shell features: +# * functions; +# * expansions «$var», «${var}», «${var:-default}», «${var+SET}», +# «${var#prefix}», «${var%suffix}», and «$( cmd )»; +# * compound commands having a testable exit status, especially «case»; +# * various built-in commands including «command», «set», and «ulimit». +# +# Important for patching: +# +# (2) This script targets any POSIX shell, so it avoids extensions provided +# by Bash, Ksh, etc; in particular arrays are avoided. +# +# The "traditional" practice of packing multiple parameters into a +# space-separated string is a well documented source of bugs and security +# problems, so this is (mostly) avoided, by progressively accumulating +# options in "$@", and eventually passing that to Java. +# +# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, +# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; +# see the in-line comments for details. +# +# There are tweaks for specific operating systems such as AIX, CygWin, +# Darwin, MinGW, and NonStop. +# +# (3) This script is generated from the Groovy template +# https://github.com/gradle/gradle/blob/HEAD/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt +# within the Gradle project. +# +# You can find Gradle at https://github.com/gradle/gradle/. +# +############################################################################## + +# Attempt to set APP_HOME + +# Resolve links: $0 may be a link +app_path=$0 + +# Need this for daisy-chained symlinks. +while + APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path + [ -h "$app_path" ] +do + ls=$( ls -ld "$app_path" ) + link=${ls#*' -> '} + case $link in #( + /*) app_path=$link ;; #( + *) app_path=$APP_HOME$link ;; + esac +done + +# This is normally unused +# shellcheck disable=SC2034 +APP_BASE_NAME=${0##*/} +# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036) +APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s +' "$PWD" ) || exit + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD=maximum + +warn () { + echo "$*" +} >&2 + +die () { + echo + echo "$*" + echo + exit 1 +} >&2 + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +nonstop=false +case "$( uname )" in #( + CYGWIN* ) cygwin=true ;; #( + Darwin* ) darwin=true ;; #( + MSYS* | MINGW* ) msys=true ;; #( + NONSTOP* ) nonstop=true ;; +esac + +CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar + + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD=$JAVA_HOME/jre/sh/java + else + JAVACMD=$JAVA_HOME/bin/java + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD=java + if ! command -v java >/dev/null 2>&1 + then + die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +fi + +# Increase the maximum file descriptors if we can. +if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then + case $MAX_FD in #( + max*) + # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + MAX_FD=$( ulimit -H -n ) || + warn "Could not query maximum file descriptor limit" + esac + case $MAX_FD in #( + '' | soft) :;; #( + *) + # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + ulimit -n "$MAX_FD" || + warn "Could not set maximum file descriptor limit to $MAX_FD" + esac +fi + +# Collect all arguments for the java command, stacking in reverse order: +# * args from the command line +# * the main class name +# * -classpath +# * -D...appname settings +# * --module-path (only if needed) +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. + +# For Cygwin or MSYS, switch paths to Windows format before running java +if "$cygwin" || "$msys" ; then + APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) + CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) + + JAVACMD=$( cygpath --unix "$JAVACMD" ) + + # Now convert the arguments - kludge to limit ourselves to /bin/sh + for arg do + if + case $arg in #( + -*) false ;; # don't mess with options #( + /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath + [ -e "$t" ] ;; #( + *) false ;; + esac + then + arg=$( cygpath --path --ignore --mixed "$arg" ) + fi + # Roll the args list around exactly as many times as the number of + # args, so each arg winds up back in the position where it started, but + # possibly modified. + # + # NB: a `for` loop captures its iteration list before it begins, so + # changing the positional parameters here affects neither the number of + # iterations, nor the values presented in `arg`. + shift # remove old arg + set -- "$@" "$arg" # push replacement arg + done +fi + + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' + +# Collect all arguments for the java command: +# * DEFAULT_JVM_OPTS, JAVA_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments, +# and any embedded shellness will be escaped. +# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be +# treated as '${Hostname}' itself on the command line. + +set -- \ + "-Dorg.gradle.appname=$APP_BASE_NAME" \ + -classpath "$CLASSPATH" \ + org.gradle.wrapper.GradleWrapperMain \ + "$@" + +# Stop when "xargs" is not available. +if ! command -v xargs >/dev/null 2>&1 +then + die "xargs is not available" +fi + +# Use "xargs" to parse quoted args. +# +# With -n1 it outputs one arg per line, with the quotes and backslashes removed. +# +# In Bash we could simply go: +# +# readarray ARGS < <( xargs -n1 <<<"$var" ) && +# set -- "${ARGS[@]}" "$@" +# +# but POSIX shell has neither arrays nor command substitution, so instead we +# post-process each arg (as a line of input to sed) to backslash-escape any +# character that might be a shell metacharacter, then use eval to reverse +# that process (while maintaining the separation between arguments), and wrap +# the whole thing up as a single "set" statement. +# +# This will of course break if any of these variables contains a newline or +# an unmatched quote. +# + +eval "set -- $( + printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | + xargs -n1 | + sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | + tr '\n' ' ' + )" '"$@"' + +exec "$JAVACMD" "$@" diff --git a/lorca-core/gradlew.bat b/lorca-core/gradlew.bat new file mode 100644 index 0000000..9d21a21 --- /dev/null +++ b/lorca-core/gradlew.bat @@ -0,0 +1,94 @@ +@rem +@rem Copyright 2015 the original author or authors. +@rem +@rem Licensed under the Apache License, Version 2.0 (the "License"); +@rem you may not use this file except in compliance with the License. +@rem You may obtain a copy of the License at +@rem +@rem https://www.apache.org/licenses/LICENSE-2.0 +@rem +@rem Unless required by applicable law or agreed to in writing, software +@rem distributed under the License is distributed on an "AS IS" BASIS, +@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +@rem See the License for the specific language governing permissions and +@rem limitations under the License. +@rem +@rem SPDX-License-Identifier: Apache-2.0 +@rem + +@if "%DEBUG%"=="" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +set DIRNAME=%~dp0 +if "%DIRNAME%"=="" set DIRNAME=. +@rem This is normally unused +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Resolve any "." and ".." in APP_HOME to make it shorter. +for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if %ERRORLEVEL% equ 0 goto execute + +echo. 1>&2 +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto execute + +echo. 1>&2 +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 + +goto fail + +:execute +@rem Setup the command line + +set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar + + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* + +:end +@rem End local scope for the variables with windows NT shell +if %ERRORLEVEL% equ 0 goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +set EXIT_CODE=%ERRORLEVEL% +if %EXIT_CODE% equ 0 set EXIT_CODE=1 +if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE% +exit /b %EXIT_CODE% + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/lorca-core/settings.gradle.kts b/lorca-core/settings.gradle.kts new file mode 100644 index 0000000..737d50f --- /dev/null +++ b/lorca-core/settings.gradle.kts @@ -0,0 +1 @@ +rootProject.name = "lorca-core" diff --git a/lorca-core/src/main/kotlin/org/js/lorca_core/LorcaCoreApplication.kt b/lorca-core/src/main/kotlin/org/js/lorca_core/LorcaCoreApplication.kt new file mode 100644 index 0000000..fde5ec1 --- /dev/null +++ b/lorca-core/src/main/kotlin/org/js/lorca_core/LorcaCoreApplication.kt @@ -0,0 +1,11 @@ +package org.js.lorca_core + +import org.springframework.boot.autoconfigure.SpringBootApplication +import org.springframework.boot.runApplication + +@SpringBootApplication(scanBasePackages = ["org.js.lorca_core"]) +class LorcaCoreApplication + +fun main(args: Array) { + runApplication(*args) +} diff --git a/lorca-core/src/main/kotlin/org/js/lorca_core/business/mappers/ClientMapper.kt b/lorca-core/src/main/kotlin/org/js/lorca_core/business/mappers/ClientMapper.kt new file mode 100644 index 0000000..05e0677 --- /dev/null +++ b/lorca-core/src/main/kotlin/org/js/lorca_core/business/mappers/ClientMapper.kt @@ -0,0 +1,8 @@ +package org.js.lorca_core.business.mappers + +import org.js.lorca_core.business.models.Client +import org.js.lorca_core.db.entities.ClientEntity +import org.mapstruct.Mapper + +@Mapper(componentModel = "spring") +interface ClientMapper : GenericMapper \ No newline at end of file diff --git a/lorca-core/src/main/kotlin/org/js/lorca_core/business/mappers/GenericMapper.kt b/lorca-core/src/main/kotlin/org/js/lorca_core/business/mappers/GenericMapper.kt new file mode 100644 index 0000000..65d1638 --- /dev/null +++ b/lorca-core/src/main/kotlin/org/js/lorca_core/business/mappers/GenericMapper.kt @@ -0,0 +1,13 @@ +package org.js.lorca_core.business.mappers + +interface GenericMapper { + + fun toEntity(model: M): E + fun toModel(entity: E): M + + fun toEntities(models: MutableList): MutableList = + models.map { toEntity(it) }.toMutableList() + + fun toModels(entities: MutableList): MutableList = + entities.map { toModel(it) }.toMutableList() +} \ No newline at end of file diff --git a/lorca-core/src/main/kotlin/org/js/lorca_core/business/mappers/UserAuthClaimMapper.kt b/lorca-core/src/main/kotlin/org/js/lorca_core/business/mappers/UserAuthClaimMapper.kt new file mode 100644 index 0000000..a9203fd --- /dev/null +++ b/lorca-core/src/main/kotlin/org/js/lorca_core/business/mappers/UserAuthClaimMapper.kt @@ -0,0 +1,8 @@ +package org.js.lorca_core.business.mappers + +import org.js.lorca_core.business.models.UserAuthClaim +import org.js.lorca_core.db.entities.UserAuthClaimEntity +import org.mapstruct.Mapper + +@Mapper(componentModel = "spring") +interface UserAuthClaimMapper : GenericMapper \ No newline at end of file diff --git a/lorca-core/src/main/kotlin/org/js/lorca_core/business/models/Client.kt b/lorca-core/src/main/kotlin/org/js/lorca_core/business/models/Client.kt new file mode 100644 index 0000000..efc5dc6 --- /dev/null +++ b/lorca-core/src/main/kotlin/org/js/lorca_core/business/models/Client.kt @@ -0,0 +1,7 @@ +package org.js.lorca_core.business.models + +data class Client( + var id: Long?, + var name: String, + var surname: String +) \ No newline at end of file diff --git a/lorca-core/src/main/kotlin/org/js/lorca_core/business/models/UserAuthClaim.kt b/lorca-core/src/main/kotlin/org/js/lorca_core/business/models/UserAuthClaim.kt new file mode 100644 index 0000000..6704f2b --- /dev/null +++ b/lorca-core/src/main/kotlin/org/js/lorca_core/business/models/UserAuthClaim.kt @@ -0,0 +1,8 @@ +package org.js.lorca_core.business.models + +import org.js.lorca_core.common.enums.EUserRoles + +data class UserAuthClaim( + var id: Long, + var name: EUserRoles +) \ No newline at end of file diff --git a/lorca-core/src/main/kotlin/org/js/lorca_core/business/repositories/ClientRepository.kt b/lorca-core/src/main/kotlin/org/js/lorca_core/business/repositories/ClientRepository.kt new file mode 100644 index 0000000..1044a9a --- /dev/null +++ b/lorca-core/src/main/kotlin/org/js/lorca_core/business/repositories/ClientRepository.kt @@ -0,0 +1,10 @@ +package org.js.lorca_core.business.repositories + +import org.js.lorca_core.business.models.Client + +interface ClientRepository { + fun createClient(client: Client): Client + fun getAll(): MutableList + fun getById(id: Long): Client + +} \ No newline at end of file diff --git a/lorca-core/src/main/kotlin/org/js/lorca_core/business/repositories/UserAuthRepository.kt b/lorca-core/src/main/kotlin/org/js/lorca_core/business/repositories/UserAuthRepository.kt new file mode 100644 index 0000000..a2cb5c8 --- /dev/null +++ b/lorca-core/src/main/kotlin/org/js/lorca_core/business/repositories/UserAuthRepository.kt @@ -0,0 +1,10 @@ +package org.js.lorca_core.business.repositories + +import org.js.lorca_core.common.enums.EUserRoles +import org.js.lorca_core.db.entities.UserAuthEntity + +interface UserAuthRepository { + fun getByUsername(username: String): UserAuthEntity + fun save(userAuth: UserAuthEntity): UserAuthEntity + fun getClaimsForuser(user: UserAuthEntity): List +} \ No newline at end of file diff --git a/lorca-core/src/main/kotlin/org/js/lorca_core/business/repositories/impl/ClientRepositoryImpl.kt b/lorca-core/src/main/kotlin/org/js/lorca_core/business/repositories/impl/ClientRepositoryImpl.kt new file mode 100644 index 0000000..48d8e4f --- /dev/null +++ b/lorca-core/src/main/kotlin/org/js/lorca_core/business/repositories/impl/ClientRepositoryImpl.kt @@ -0,0 +1,36 @@ +package org.js.lorca_core.business.repositories.impl + +import org.js.lorca_core.business.mappers.ClientMapper +import org.js.lorca_core.business.models.Client +import org.js.lorca_core.business.repositories.ClientRepository +import org.js.lorca_core.common.enums.EBusinessException +import org.js.lorca_core.common.exceptions.LorcaException +import org.js.lorca_core.db.ClientJpa +import org.springframework.stereotype.Component + +@Component +class ClientRepositoryImpl( + protected val jpa: ClientJpa, + protected val mapper: ClientMapper +) : ClientRepository { + override fun createClient(client: Client): Client { + return mapper.toModel(jpa.save(mapper.toEntity(client))) + } + + + override fun getAll(): MutableList { + return mapper.toModels(jpa.findAll()) + } + + override fun getById(id: Long): Client { + return mapper.toModel( + jpa.findById(id).orElseThrow { + LorcaException.create( + EBusinessException.ENTITY_WITH_ID_NOT_FOUND, + Client::class.java.simpleName, + id + ) + }) + } + +} \ No newline at end of file diff --git a/lorca-core/src/main/kotlin/org/js/lorca_core/business/repositories/impl/UserAuthRepositoryImpl.kt b/lorca-core/src/main/kotlin/org/js/lorca_core/business/repositories/impl/UserAuthRepositoryImpl.kt new file mode 100644 index 0000000..8ed7ac8 --- /dev/null +++ b/lorca-core/src/main/kotlin/org/js/lorca_core/business/repositories/impl/UserAuthRepositoryImpl.kt @@ -0,0 +1,30 @@ +package org.js.lorca_core.business.repositories.impl + +import org.js.lorca_core.business.mappers.UserAuthClaimMapper +import org.js.lorca_core.business.repositories.UserAuthRepository +import org.js.lorca_core.common.enums.EBusinessException +import org.js.lorca_core.common.enums.EUserRoles +import org.js.lorca_core.common.exceptions.LorcaException +import org.js.lorca_core.db.UserAuthJpa +import org.js.lorca_core.db.entities.UserAuthEntity +import org.springframework.stereotype.Component + +@Component +class UserAuthRepositoryImpl( + protected val jpa: UserAuthJpa, + protected val claimMapper: UserAuthClaimMapper +) : UserAuthRepository { + override fun getByUsername(username: String): UserAuthEntity { + return jpa.findByUsr(username) + .orElseThrow { LorcaException.create(EBusinessException.USER_NOT_FOUND, username) } + } + + override fun save(userAuth: UserAuthEntity): UserAuthEntity { + return jpa.save(userAuth) + } + + override fun getClaimsForuser(user: UserAuthEntity): List { + return claimMapper.toModels(user.claims).map { it.name }.toList() + } + +} \ No newline at end of file diff --git a/lorca-core/src/main/kotlin/org/js/lorca_core/common/enums/EBusinessException.kt b/lorca-core/src/main/kotlin/org/js/lorca_core/common/enums/EBusinessException.kt new file mode 100644 index 0000000..ce02438 --- /dev/null +++ b/lorca-core/src/main/kotlin/org/js/lorca_core/common/enums/EBusinessException.kt @@ -0,0 +1,7 @@ +package org.js.lorca_core.common.enums + +enum class EBusinessException(val msg: String) { + USER_NOT_FOUND("Username: '%s' not found"), + ENTITY_WITH_ID_NOT_FOUND("%s with id %s not found"), + INVALID_REQUEST("Invalid request for %s with reason: %s") +} \ No newline at end of file diff --git a/lorca-core/src/main/kotlin/org/js/lorca_core/common/enums/EUserRoles.kt b/lorca-core/src/main/kotlin/org/js/lorca_core/common/enums/EUserRoles.kt new file mode 100644 index 0000000..ad9cc00 --- /dev/null +++ b/lorca-core/src/main/kotlin/org/js/lorca_core/common/enums/EUserRoles.kt @@ -0,0 +1,8 @@ +package org.js.lorca_core.common.enums + +enum class EUserRoles(val role: String) { + FISIO("FISIO"), + PSICO("PSICO"), + ALL("ALL"), + ADMIN("ADMIN") +} \ No newline at end of file diff --git a/lorca-core/src/main/kotlin/org/js/lorca_core/common/enums/EWorkerCategory.kt b/lorca-core/src/main/kotlin/org/js/lorca_core/common/enums/EWorkerCategory.kt new file mode 100644 index 0000000..1fc7171 --- /dev/null +++ b/lorca-core/src/main/kotlin/org/js/lorca_core/common/enums/EWorkerCategory.kt @@ -0,0 +1,5 @@ +package org.js.lorca_core.common.enums + +enum class EWorkerCategory(name: String) { + FISIO("FISIO") +} \ No newline at end of file diff --git a/lorca-core/src/main/kotlin/org/js/lorca_core/common/exceptions/LorcaException.kt b/lorca-core/src/main/kotlin/org/js/lorca_core/common/exceptions/LorcaException.kt new file mode 100644 index 0000000..ccdf920 --- /dev/null +++ b/lorca-core/src/main/kotlin/org/js/lorca_core/common/exceptions/LorcaException.kt @@ -0,0 +1,13 @@ +package org.js.lorca_core.common.exceptions + +import org.js.lorca_core.common.enums.EBusinessException + +class LorcaException(val ex: EBusinessException, override val message: String) : Exception() { + + companion object { + fun create(exc: EBusinessException, vararg args: Any): LorcaException { + return LorcaException(exc, exc.msg.format(*args)) + } + } + +} \ No newline at end of file diff --git a/lorca-core/src/main/kotlin/org/js/lorca_core/config/SecurityConfig.kt b/lorca-core/src/main/kotlin/org/js/lorca_core/config/SecurityConfig.kt new file mode 100644 index 0000000..10fc2a0 --- /dev/null +++ b/lorca-core/src/main/kotlin/org/js/lorca_core/config/SecurityConfig.kt @@ -0,0 +1,38 @@ +package org.js.lorca_core.config + +import org.js.lorca_core.config.auth.JwtAuthenticationFilter +import org.springframework.context.annotation.Bean +import org.springframework.context.annotation.Configuration +import org.springframework.security.authentication.AuthenticationProvider +import org.springframework.security.config.annotation.web.builders.HttpSecurity +import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity +import org.springframework.security.config.http.SessionCreationPolicy +import org.springframework.security.web.SecurityFilterChain +import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter + + +@Configuration +@EnableWebSecurity +class SecurityConfig( + val authenticationProvider: AuthenticationProvider, + val jwtAuthenticationFilter: JwtAuthenticationFilter +) { + + @Bean + fun securityFilterChain(http: HttpSecurity): SecurityFilterChain { + http + .authorizeHttpRequests { auth -> + auth + .requestMatchers("/**").permitAll() + .anyRequest().authenticated() + } + .sessionManagement { session -> + session.sessionCreationPolicy(SessionCreationPolicy.STATELESS) + }.authenticationProvider(authenticationProvider) + .addFilterBefore(jwtAuthenticationFilter, UsernamePasswordAuthenticationFilter::class.java) + .csrf { it.disable() } + + return http.build() + } +} + diff --git a/lorca-core/src/main/kotlin/org/js/lorca_core/config/auth/JwtAuthConfiguration.kt b/lorca-core/src/main/kotlin/org/js/lorca_core/config/auth/JwtAuthConfiguration.kt new file mode 100644 index 0000000..d0614d2 --- /dev/null +++ b/lorca-core/src/main/kotlin/org/js/lorca_core/config/auth/JwtAuthConfiguration.kt @@ -0,0 +1,46 @@ +package org.js.lorca_core.config.auth + +import org.js.lorca_core.business.repositories.UserAuthRepository +import org.springframework.context.annotation.Bean +import org.springframework.context.annotation.Configuration +import org.springframework.security.authentication.AuthenticationManager +import org.springframework.security.authentication.AuthenticationProvider +import org.springframework.security.authentication.dao.DaoAuthenticationProvider +import org.springframework.security.config.annotation.authentication.configuration.AuthenticationConfiguration +import org.springframework.security.core.userdetails.UserDetailsService +import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder + + +@Configuration +class JwtAuthConfiguration( + val userAuthRepository: UserAuthRepository +) { + + @Bean + fun userDetailsService(): UserDetailsService { + return UserDetailsService { username: String? -> + userAuthRepository.getByUsername(username ?: "") + } + } + + @Bean + fun passwordEncoder(): BCryptPasswordEncoder { + return BCryptPasswordEncoder() + } + + @Bean + @Throws(Exception::class) + fun authenticationManager(config: AuthenticationConfiguration): AuthenticationManager { + return config.authenticationManager + } + + @Bean + fun authenticationProvider(): AuthenticationProvider { + val authProvider = DaoAuthenticationProvider() + + authProvider.setUserDetailsService(userDetailsService()) + authProvider.setPasswordEncoder(passwordEncoder()) + + return authProvider + } +} \ No newline at end of file diff --git a/lorca-core/src/main/kotlin/org/js/lorca_core/config/auth/JwtAuthenticationFilter.kt b/lorca-core/src/main/kotlin/org/js/lorca_core/config/auth/JwtAuthenticationFilter.kt new file mode 100644 index 0000000..93662ba --- /dev/null +++ b/lorca-core/src/main/kotlin/org/js/lorca_core/config/auth/JwtAuthenticationFilter.kt @@ -0,0 +1,64 @@ +package org.js.lorca_core.config.auth + +import jakarta.servlet.FilterChain +import jakarta.servlet.ServletException +import jakarta.servlet.http.HttpServletRequest +import jakarta.servlet.http.HttpServletResponse +import org.js.lorca_core.services.JwtService +import org.springframework.lang.NonNull +import org.springframework.security.authentication.UsernamePasswordAuthenticationToken +import org.springframework.security.core.Authentication +import org.springframework.security.core.context.SecurityContextHolder +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 org.springframework.web.servlet.HandlerExceptionResolver +import java.io.IOException + +@Component +class JwtAuthenticationFilter( + private val jwtService: JwtService, + private val userDetailsService: UserDetailsService, + private val handlerExceptionResolver: HandlerExceptionResolver +) : OncePerRequestFilter() { + @Throws(ServletException::class, IOException::class) + override fun doFilterInternal( + @NonNull request: HttpServletRequest, + @NonNull response: HttpServletResponse, + @NonNull filterChain: FilterChain + ) { + val authHeader = request.getHeader("Authorization") + + if (authHeader == null || !authHeader.startsWith("Bearer ")) { + filterChain.doFilter(request, response) + return + } + + try { + val jwt = authHeader.substring(7) + val userEmail = jwtService.extractUsername(jwt) + + val authentication: Authentication? = SecurityContextHolder.getContext().authentication + + if (authentication == null) { + val userDetails = userDetailsService.loadUserByUsername(userEmail) + + if (jwtService.isTokenValid(jwt, userDetails)) { + val authToken = UsernamePasswordAuthenticationToken( + userDetails, + null, + userDetails.authorities + ) + + authToken.details = WebAuthenticationDetailsSource().buildDetails(request) + SecurityContextHolder.getContext().authentication = authToken + } + } + + filterChain.doFilter(request, response) + } catch (exception: Exception) { + handlerExceptionResolver.resolveException(request, response, null, exception) + } + } +} \ No newline at end of file diff --git a/lorca-core/src/main/kotlin/org/js/lorca_core/db/ClientJpa.kt b/lorca-core/src/main/kotlin/org/js/lorca_core/db/ClientJpa.kt new file mode 100644 index 0000000..525d81f --- /dev/null +++ b/lorca-core/src/main/kotlin/org/js/lorca_core/db/ClientJpa.kt @@ -0,0 +1,6 @@ +package org.js.lorca_core.db + +import org.js.lorca_core.db.entities.ClientEntity +import org.springframework.data.jpa.repository.JpaRepository + +interface ClientJpa : JpaRepository \ No newline at end of file diff --git a/lorca-core/src/main/kotlin/org/js/lorca_core/db/UserAuthJpa.kt b/lorca-core/src/main/kotlin/org/js/lorca_core/db/UserAuthJpa.kt new file mode 100644 index 0000000..4e36b3c --- /dev/null +++ b/lorca-core/src/main/kotlin/org/js/lorca_core/db/UserAuthJpa.kt @@ -0,0 +1,9 @@ +package org.js.lorca_core.db + +import org.js.lorca_core.db.entities.UserAuthEntity +import org.springframework.data.jpa.repository.JpaRepository +import java.util.* + +interface UserAuthJpa : JpaRepository { + fun findByUsr(username: String): Optional +} \ No newline at end of file diff --git a/lorca-core/src/main/kotlin/org/js/lorca_core/db/WorkerJpa.kt b/lorca-core/src/main/kotlin/org/js/lorca_core/db/WorkerJpa.kt new file mode 100644 index 0000000..bf7ffd9 --- /dev/null +++ b/lorca-core/src/main/kotlin/org/js/lorca_core/db/WorkerJpa.kt @@ -0,0 +1,11 @@ +package org.js.lorca_core.db + +import org.js.lorca_core.common.enums.EWorkerCategory +import org.js.lorca_core.db.entities.WorkerEntity +import org.springframework.data.jpa.repository.JpaRepository +import org.springframework.data.repository.query.Param + +interface WorkerJpa : JpaRepository { + + fun findAllByCategoryName(@Param("category") category: EWorkerCategory): MutableList +} \ No newline at end of file diff --git a/lorca-core/src/main/kotlin/org/js/lorca_core/db/entities/ClientEntity.kt b/lorca-core/src/main/kotlin/org/js/lorca_core/db/entities/ClientEntity.kt new file mode 100644 index 0000000..2154de6 --- /dev/null +++ b/lorca-core/src/main/kotlin/org/js/lorca_core/db/entities/ClientEntity.kt @@ -0,0 +1,14 @@ +package org.js.lorca_core.db.entities + +import jakarta.persistence.Entity +import jakarta.persistence.GeneratedValue +import jakarta.persistence.GenerationType +import jakarta.persistence.Id + +@Entity(name = "clients") +data class ClientEntity( + @Id @GeneratedValue(strategy = GenerationType.IDENTITY) + var id: Long = 0L, + var name: String, + var surname: String +) \ No newline at end of file diff --git a/lorca-core/src/main/kotlin/org/js/lorca_core/db/entities/ReportEntity.kt b/lorca-core/src/main/kotlin/org/js/lorca_core/db/entities/ReportEntity.kt new file mode 100644 index 0000000..e6ff5ad --- /dev/null +++ b/lorca-core/src/main/kotlin/org/js/lorca_core/db/entities/ReportEntity.kt @@ -0,0 +1,17 @@ +package org.js.lorca_core.db.entities + +import jakarta.persistence.* +import java.util.* + +@Entity(name = "reports") +data class ReportEntity( + @Id @GeneratedValue(strategy = GenerationType.IDENTITY) + var id: Long = 0L, + var reportDate: Date, + + @ManyToOne(fetch = FetchType.LAZY, cascade = [CascadeType.DETACH]) + val filedBy: WorkerEntity, + + @OneToMany(fetch = FetchType.LAZY, cascade = [CascadeType.DETACH]) + val clientEntities: MutableList = mutableListOf() +) \ No newline at end of file diff --git a/lorca-core/src/main/kotlin/org/js/lorca_core/db/entities/UserAuthClaimEntity.kt b/lorca-core/src/main/kotlin/org/js/lorca_core/db/entities/UserAuthClaimEntity.kt new file mode 100644 index 0000000..d9fc7be --- /dev/null +++ b/lorca-core/src/main/kotlin/org/js/lorca_core/db/entities/UserAuthClaimEntity.kt @@ -0,0 +1,14 @@ +package org.js.lorca_core.db.entities + +import jakarta.persistence.Entity +import jakarta.persistence.GeneratedValue +import jakarta.persistence.GenerationType +import jakarta.persistence.Id +import org.js.lorca_core.common.enums.EUserRoles + +@Entity(name = "user_auth_claims") +data class UserAuthClaimEntity( + @Id @GeneratedValue(strategy = GenerationType.IDENTITY) + var id: Long = 0L, + var name: EUserRoles +) \ No newline at end of file diff --git a/lorca-core/src/main/kotlin/org/js/lorca_core/db/entities/UserAuthEntity.kt b/lorca-core/src/main/kotlin/org/js/lorca_core/db/entities/UserAuthEntity.kt new file mode 100644 index 0000000..18a0f0d --- /dev/null +++ b/lorca-core/src/main/kotlin/org/js/lorca_core/db/entities/UserAuthEntity.kt @@ -0,0 +1,54 @@ +package org.js.lorca_core.db.entities + +import jakarta.persistence.* +import org.springframework.security.core.GrantedAuthority +import org.springframework.security.core.userdetails.UserDetails + +@Entity(name = "user_auth") +class UserAuthEntity : UserDetails { + @Id + @GeneratedValue + var id: Long? = null + var usr: String? = null + var pwd: String? = null + + @ManyToMany(cascade = [CascadeType.DETACH]) + var claims: MutableList = mutableListOf() + + override fun getAuthorities(): Collection { + return listOf() + } + + fun setPassword(password: String) { + pwd = password + } + + fun setUsername(user: String) { + usr = user + } + + override fun getPassword(): String { + return pwd!! + } + + override fun getUsername(): String { + return usr!! + } + + override fun isAccountNonExpired(): Boolean { + return true + } + + override fun isAccountNonLocked(): Boolean { + return true + } + + override fun isCredentialsNonExpired(): Boolean { + return true + } + + override fun isEnabled(): Boolean { + return true + } + +} \ No newline at end of file diff --git a/lorca-core/src/main/kotlin/org/js/lorca_core/db/entities/WorkerCategoryEntity.kt b/lorca-core/src/main/kotlin/org/js/lorca_core/db/entities/WorkerCategoryEntity.kt new file mode 100644 index 0000000..4fcbf50 --- /dev/null +++ b/lorca-core/src/main/kotlin/org/js/lorca_core/db/entities/WorkerCategoryEntity.kt @@ -0,0 +1,14 @@ +package org.js.lorca_core.db.entities + +import jakarta.persistence.Entity +import jakarta.persistence.GeneratedValue +import jakarta.persistence.GenerationType +import jakarta.persistence.Id +import org.js.lorca_core.common.enums.EWorkerCategory + +@Entity(name = "worker_categories") +data class WorkerCategoryEntity( + @Id @GeneratedValue(strategy = GenerationType.IDENTITY) + var id: Long = 0L, + var name: EWorkerCategory +) \ No newline at end of file diff --git a/lorca-core/src/main/kotlin/org/js/lorca_core/db/entities/WorkerEntity.kt b/lorca-core/src/main/kotlin/org/js/lorca_core/db/entities/WorkerEntity.kt new file mode 100644 index 0000000..bbc5847 --- /dev/null +++ b/lorca-core/src/main/kotlin/org/js/lorca_core/db/entities/WorkerEntity.kt @@ -0,0 +1,13 @@ +package org.js.lorca_core.db.entities + +import jakarta.persistence.* + +@Entity(name = "workers") +data class WorkerEntity( + @Id @GeneratedValue(strategy = GenerationType.IDENTITY) + var id: Long = 0L, + var name: String, + var surname: String, + @ManyToOne(fetch = FetchType.LAZY) + val category: WorkerCategoryEntity +) \ No newline at end of file diff --git a/lorca-core/src/main/kotlin/org/js/lorca_core/services/AuthenticationService.kt b/lorca-core/src/main/kotlin/org/js/lorca_core/services/AuthenticationService.kt new file mode 100644 index 0000000..1003930 --- /dev/null +++ b/lorca-core/src/main/kotlin/org/js/lorca_core/services/AuthenticationService.kt @@ -0,0 +1,13 @@ +package org.js.lorca_core.services + +import org.js.lorca_core.common.enums.EUserRoles +import org.js.lorca_core.db.entities.UserAuthEntity +import org.js.lorca_core.web.dtos.UserAuthDto + +interface AuthenticationService { + fun register(input: UserAuthDto): Boolean + + fun login(input: UserAuthDto): UserAuthEntity + + fun getClaimsForUser(user: UserAuthEntity): List +} \ No newline at end of file diff --git a/lorca-core/src/main/kotlin/org/js/lorca_core/services/ClientService.kt b/lorca-core/src/main/kotlin/org/js/lorca_core/services/ClientService.kt new file mode 100644 index 0000000..01dc115 --- /dev/null +++ b/lorca-core/src/main/kotlin/org/js/lorca_core/services/ClientService.kt @@ -0,0 +1,10 @@ +package org.js.lorca_core.services + +import org.js.lorca_core.business.models.Client +import org.js.lorca_core.web.dtos.ClientDto + +interface ClientService { + fun getAllClients(name: String?, surname: String?): MutableList + fun getClientById(id: Long): Client + fun createClient(clientDto: ClientDto): Client +} \ No newline at end of file diff --git a/lorca-core/src/main/kotlin/org/js/lorca_core/services/JwtService.kt b/lorca-core/src/main/kotlin/org/js/lorca_core/services/JwtService.kt new file mode 100644 index 0000000..978d2f0 --- /dev/null +++ b/lorca-core/src/main/kotlin/org/js/lorca_core/services/JwtService.kt @@ -0,0 +1,20 @@ +package org.js.lorca_core.services + +import io.jsonwebtoken.Claims +import org.springframework.security.core.userdetails.UserDetails +import java.util.function.Function + +interface JwtService { + + fun extractUsername(token: String): String + + fun extractClaim(token: String, claimsResolver: Function): T + + fun generateToken(userDetails: UserDetails): String + + fun generateToken(extraClaims: Map, userDetails: UserDetails): String + + fun getExpirationTime(): Long + + fun isTokenValid(token: String, userDetails: UserDetails): Boolean +} diff --git a/lorca-core/src/main/kotlin/org/js/lorca_core/services/impl/AuthenticationServiceImpl.kt b/lorca-core/src/main/kotlin/org/js/lorca_core/services/impl/AuthenticationServiceImpl.kt new file mode 100644 index 0000000..6dfc0f2 --- /dev/null +++ b/lorca-core/src/main/kotlin/org/js/lorca_core/services/impl/AuthenticationServiceImpl.kt @@ -0,0 +1,44 @@ +package org.js.lorca_core.services.impl + +import org.js.lorca_core.business.repositories.UserAuthRepository +import org.js.lorca_core.common.enums.EUserRoles +import org.js.lorca_core.db.entities.UserAuthEntity +import org.js.lorca_core.services.AuthenticationService +import org.js.lorca_core.web.dtos.UserAuthDto +import org.springframework.security.authentication.AuthenticationManager +import org.springframework.security.authentication.UsernamePasswordAuthenticationToken +import org.springframework.security.crypto.password.PasswordEncoder +import org.springframework.stereotype.Service + + +@Service +class AuthenticationServiceImpl( + private val userAuthRepository: UserAuthRepository, + private val authenticationManager: AuthenticationManager, + private val passwordEncoder: PasswordEncoder +) : AuthenticationService { + + override fun register(input: UserAuthDto): Boolean { + val user = UserAuthEntity() + user.username = input.username + user.password = passwordEncoder.encode(input.password) + userAuthRepository.save(user) + return true + } + + override fun login(input: UserAuthDto): UserAuthEntity { + authenticationManager.authenticate( + UsernamePasswordAuthenticationToken( + input.username, + input.password + ) + ) + + return userAuthRepository.getByUsername(input.username) + } + + override fun getClaimsForUser(user: UserAuthEntity): List { + return userAuthRepository.getClaimsForuser(user) + } + +} \ No newline at end of file diff --git a/lorca-core/src/main/kotlin/org/js/lorca_core/services/impl/ClientServiceImpl.kt b/lorca-core/src/main/kotlin/org/js/lorca_core/services/impl/ClientServiceImpl.kt new file mode 100644 index 0000000..4a87346 --- /dev/null +++ b/lorca-core/src/main/kotlin/org/js/lorca_core/services/impl/ClientServiceImpl.kt @@ -0,0 +1,22 @@ +package org.js.lorca_core.services.impl + +import org.js.lorca_core.business.models.Client +import org.js.lorca_core.business.repositories.ClientRepository +import org.js.lorca_core.services.ClientService +import org.js.lorca_core.web.dtos.ClientDto +import org.springframework.stereotype.Service + +@Service +class ClientServiceImpl(val repo: ClientRepository) : ClientService { + override fun getAllClients(name: String?, surname: String?): MutableList { + return repo.getAll() + } + + override fun getClientById(id: Long): Client { + return repo.getById(id) + } + + override fun createClient(clientDto: ClientDto): Client { + return repo.createClient(Client(null, clientDto.name, clientDto.surname)) + } +} \ No newline at end of file diff --git a/lorca-core/src/main/kotlin/org/js/lorca_core/services/impl/JwtServiceImpl.kt b/lorca-core/src/main/kotlin/org/js/lorca_core/services/impl/JwtServiceImpl.kt new file mode 100644 index 0000000..6441b30 --- /dev/null +++ b/lorca-core/src/main/kotlin/org/js/lorca_core/services/impl/JwtServiceImpl.kt @@ -0,0 +1,84 @@ +package org.js.lorca_core.services.impl + +import io.jsonwebtoken.Claims +import io.jsonwebtoken.Jwts +import io.jsonwebtoken.io.Decoders +import io.jsonwebtoken.security.Keys +import org.js.lorca_core.services.JwtService +import org.springframework.beans.factory.annotation.Value +import org.springframework.security.core.userdetails.UserDetails +import org.springframework.stereotype.Service +import java.util.* +import java.util.function.Function +import javax.crypto.SecretKey + +@Service +class JwtServiceImpl : JwtService { + + @Value("\${security.jwt.secret-key}") + private lateinit var secretKey: String + + @Value("\${security.jwt.expiration-time}") + private var jwtExpiration: Long = 0 + + override fun extractUsername(token: String): String { + return extractClaim(token, Claims::getSubject) + } + + override fun extractClaim(token: String, claimsResolver: Function): T { + val claims: Claims = extractAllClaims(token) + return claimsResolver.apply(claims) + } + + override fun generateToken(userDetails: UserDetails): String { + return generateToken(emptyMap(), userDetails) + } + + override fun generateToken(extraClaims: Map, userDetails: UserDetails): String { + return buildToken(extraClaims, userDetails, jwtExpiration) + } + + override fun getExpirationTime(): Long { + return jwtExpiration + } + + private fun buildToken( + extraClaims: Map, + userDetails: UserDetails, + expiration: Long + ): String { + return Jwts.builder() + .claims(extraClaims) + .subject(userDetails.username) + .issuedAt(Date(System.currentTimeMillis())) + .expiration(Date(System.currentTimeMillis() + expiration)) + .signWith(getSignInKey(), Jwts.SIG.HS256) + .compact() + } + + override fun isTokenValid(token: String, userDetails: UserDetails): Boolean { + val username = extractUsername(token) + return (username == userDetails.username) && !isTokenExpired(token) + } + + private fun isTokenExpired(token: String): Boolean { + return extractExpiration(token).before(Date()) + } + + private fun extractExpiration(token: String): Date { + return extractClaim(token, Claims::getExpiration) + } + + private fun extractAllClaims(token: String): Claims { + return Jwts.parser() + .verifyWith(getSignInKey()) + .build() + .parseSignedClaims(token) + .payload + } + + private fun getSignInKey(): SecretKey { + val keyBytes = Decoders.BASE64.decode(secretKey) + return Keys.hmacShaKeyFor(keyBytes) + } +} diff --git a/lorca-core/src/main/kotlin/org/js/lorca_core/web/advices/BaseAdvice.kt b/lorca-core/src/main/kotlin/org/js/lorca_core/web/advices/BaseAdvice.kt new file mode 100644 index 0000000..922e533 --- /dev/null +++ b/lorca-core/src/main/kotlin/org/js/lorca_core/web/advices/BaseAdvice.kt @@ -0,0 +1,113 @@ +package org.js.lorca_core.web.advices + +import org.js.lorca_core.common.enums.EBusinessException +import org.js.lorca_core.common.exceptions.LorcaException +import org.springframework.http.HttpStatus +import org.springframework.http.converter.HttpMessageNotReadableException +import org.springframework.web.HttpRequestMethodNotSupportedException +import org.springframework.web.bind.MethodArgumentNotValidException +import org.springframework.web.bind.annotation.ExceptionHandler +import org.springframework.web.bind.annotation.RestControllerAdvice +import org.springframework.web.context.request.ServletWebRequest +import org.springframework.web.context.request.WebRequest +import org.springframework.web.servlet.resource.NoResourceFoundException + +@RestControllerAdvice +class BaseAdvice { + + @ExceptionHandler(LorcaException::class) + fun handleLorcaBusinessException( + ex: LorcaException, + request: WebRequest + ): WebResponse { + return WebResponse.ko( + deductStatus(ex.ex), + ex.message + ) + } + + private fun deductStatus(ex: EBusinessException): HttpStatus { + return when (ex) { + EBusinessException.USER_NOT_FOUND -> HttpStatus.NOT_FOUND + EBusinessException.ENTITY_WITH_ID_NOT_FOUND -> HttpStatus.NOT_FOUND + EBusinessException.INVALID_REQUEST -> HttpStatus.BAD_REQUEST + } + } + + @ExceptionHandler(NumberFormatException::class) + fun handleNumberFormatException( + ex: NumberFormatException, + request: WebRequest + ): WebResponse { + return WebResponse.ko( + HttpStatus.BAD_REQUEST, + "${HttpStatus.BAD_REQUEST.reasonPhrase}: ${ex.message}" + ) + } + + + @ExceptionHandler(NoResourceFoundException::class) + fun handleNoResourceFoundException( + ex: NoResourceFoundException, + request: WebRequest + ): WebResponse { + return WebResponse.ko( + HttpStatus.NOT_FOUND, + "${HttpStatus.NOT_FOUND.reasonPhrase}: ${(request as ServletWebRequest).request.requestURI}" + + ) + } + + @ExceptionHandler(HttpRequestMethodNotSupportedException::class) + fun handleHttpRequestMethodNotSupportedException( + ex: HttpRequestMethodNotSupportedException, + request: WebRequest + ): WebResponse { + return WebResponse.ko( + HttpStatus.METHOD_NOT_ALLOWED, + "${HttpStatus.METHOD_NOT_ALLOWED.reasonPhrase}: ${(request as ServletWebRequest).request.requestURI}" + + ) + } + + + @ExceptionHandler(MethodArgumentNotValidException::class) + fun handleMethodArgumentNotValidException( + ex: MethodArgumentNotValidException, + request: WebRequest + ): WebResponse { + val errors = + ex.bindingResult.fieldErrors.map { + "${it.field} - ${it.defaultMessage}" + } + return WebResponse.ko( + HttpStatus.NOT_ACCEPTABLE, + errors + ) + } + + + @ExceptionHandler(HttpMessageNotReadableException::class) + fun handleHttpMessageNotReadableException( + ex: HttpMessageNotReadableException, + request: WebRequest + ): WebResponse { + return WebResponse.ko( + HttpStatus.NOT_ACCEPTABLE, + "${HttpStatus.NOT_ACCEPTABLE.reasonPhrase}: JSON parse error" + + ) + } + + + @ExceptionHandler(Exception::class) + fun handleException( + ex: Exception, + request: WebRequest + ): WebResponse { + return WebResponse.ko( + HttpStatus.INTERNAL_SERVER_ERROR, + ex.message + ) + } +} \ No newline at end of file diff --git a/lorca-core/src/main/kotlin/org/js/lorca_core/web/advices/LoggingAspect.kt b/lorca-core/src/main/kotlin/org/js/lorca_core/web/advices/LoggingAspect.kt new file mode 100644 index 0000000..666892d --- /dev/null +++ b/lorca-core/src/main/kotlin/org/js/lorca_core/web/advices/LoggingAspect.kt @@ -0,0 +1,39 @@ +package org.js.lorca_core.web.advices + + +//@Aspect +//@Component +class LoggingAspect { +// @Around("execution(* org.js.lorca_core.web.controllers.*.*(..))") +// @Throws(Throwable::class) +// fun logMethodDetails(proceedingJoinPoint: ProceedingJoinPoint): Any? { +// val methodName = proceedingJoinPoint.signature.toShortString() +// val arguments = proceedingJoinPoint.args +// +// // Log method entry and arguments +// logger.info("Entering method: {} with arguments: {}", methodName, Arrays.toString(arguments)) +// +// var result: Any? = null +// +// try { +// // Proceed with method execution +// result = proceedingJoinPoint.proceed() +// logger.info("Exiting method: {} with result: {}", methodName, result) +// } catch (ex: Throwable) { +// // Handle exception logging +// logger.error( +// "Exception in method: {} with arguments: {} and exception: {}", +// methodName, +// arguments.contentToString(), +// ex.message +// ) +// throw ex // Re-throw the exception so that Spring's exception resolver can handle it +// } +// +// return result +// } +// +// companion object { +// private val logger: Logger = LoggerFactory.getLogger(LoggingAspect::class.java) +// } +} \ No newline at end of file diff --git a/lorca-core/src/main/kotlin/org/js/lorca_core/web/advices/WebResponse.kt b/lorca-core/src/main/kotlin/org/js/lorca_core/web/advices/WebResponse.kt new file mode 100644 index 0000000..73377ec --- /dev/null +++ b/lorca-core/src/main/kotlin/org/js/lorca_core/web/advices/WebResponse.kt @@ -0,0 +1,30 @@ +package org.js.lorca_core.web.advices + +import org.springframework.http.HttpStatus + + +data class WebResponse( + val status: HttpStatus, + val error: String? = null, + val data: T? = null +) { + + companion object { + fun ok(): WebResponse { + return WebResponse(status = HttpStatus.OK) + } + + fun ok(data: T): WebResponse { + return WebResponse(status = HttpStatus.OK, data = data) + } + + fun ko(status: HttpStatus, error: String?): WebResponse { + return WebResponse(status = status, error = error) + } + + fun ko(status: HttpStatus, errors: List): WebResponse { + return WebResponse(status = status, error = errors.toString()) + } + } + +} \ No newline at end of file diff --git a/lorca-core/src/main/kotlin/org/js/lorca_core/web/controllers/AuthController.kt b/lorca-core/src/main/kotlin/org/js/lorca_core/web/controllers/AuthController.kt new file mode 100644 index 0000000..acf3360 --- /dev/null +++ b/lorca-core/src/main/kotlin/org/js/lorca_core/web/controllers/AuthController.kt @@ -0,0 +1,42 @@ +package org.js.lorca_core.web.controllers + +import jakarta.validation.Valid +import lombok.AllArgsConstructor +import org.js.lorca_core.services.AuthenticationService +import org.js.lorca_core.services.JwtService +import org.js.lorca_core.web.advices.WebResponse +import org.js.lorca_core.web.dtos.UserAuthDto +import org.js.lorca_core.web.responses.LoginResponse +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 + + +@RestController +@RequestMapping("/auth") +@AllArgsConstructor +class AuthController( + val authenticationService: AuthenticationService, + val jwtService: JwtService +) { + + @PostMapping("/register") + fun register(@Valid @RequestBody registerUserDto: UserAuthDto): WebResponse { + authenticationService.register(registerUserDto) + return WebResponse.ok() + } + + @PostMapping("/login") + fun authenticate(@Valid @RequestBody loginUserDto: UserAuthDto): WebResponse { + val user = authenticationService.login(loginUserDto) + return WebResponse.ok( + LoginResponse( + jwtService.generateToken(user), + jwtService.getExpirationTime(), + authenticationService.getClaimsForUser(user) + ) + ) + } + +} \ No newline at end of file diff --git a/lorca-core/src/main/kotlin/org/js/lorca_core/web/controllers/ClientController.kt b/lorca-core/src/main/kotlin/org/js/lorca_core/web/controllers/ClientController.kt new file mode 100644 index 0000000..ad5a950 --- /dev/null +++ b/lorca-core/src/main/kotlin/org/js/lorca_core/web/controllers/ClientController.kt @@ -0,0 +1,36 @@ +package org.js.lorca_core.web.controllers + +import jakarta.validation.Valid +import lombok.AllArgsConstructor +import org.js.lorca_core.business.models.Client +import org.js.lorca_core.services.ClientService +import org.js.lorca_core.web.advices.WebResponse +import org.js.lorca_core.web.dtos.ClientDto +import org.springframework.web.bind.annotation.* + +@RestController +@RequestMapping("/clients") +@AllArgsConstructor +class ClientController( + val clientService: ClientService +) { + + @GetMapping + fun getAllClients( + @RequestParam("name", required = false, defaultValue = "") name: String, + @RequestParam("surname", required = false, defaultValue = "") surname: String + ): WebResponse> { + return WebResponse.ok(clientService.getAllClients(name, surname)) + } + + @PostMapping + fun createClient(@Valid @RequestBody clientDto: ClientDto): WebResponse { + return WebResponse.ok(clientService.createClient(clientDto)) + } + + @GetMapping("/{id}") + fun getClient(@PathVariable("id") id: String): WebResponse { + return WebResponse.ok(clientService.getClientById(id.toLong())) + } + +} \ No newline at end of file diff --git a/lorca-core/src/main/kotlin/org/js/lorca_core/web/dtos/ClientDto.kt b/lorca-core/src/main/kotlin/org/js/lorca_core/web/dtos/ClientDto.kt new file mode 100644 index 0000000..579aa47 --- /dev/null +++ b/lorca-core/src/main/kotlin/org/js/lorca_core/web/dtos/ClientDto.kt @@ -0,0 +1,10 @@ +package org.js.lorca_core.web.dtos + +import org.js.lorca_core.web.dtos.validators.NameValidator + +data class ClientDto( + @field:NameValidator.Validate + val name: String, + @field:NameValidator.Validate + val surname: String +) \ No newline at end of file diff --git a/lorca-core/src/main/kotlin/org/js/lorca_core/web/dtos/UserAuthDto.kt b/lorca-core/src/main/kotlin/org/js/lorca_core/web/dtos/UserAuthDto.kt new file mode 100644 index 0000000..828613d --- /dev/null +++ b/lorca-core/src/main/kotlin/org/js/lorca_core/web/dtos/UserAuthDto.kt @@ -0,0 +1,11 @@ +package org.js.lorca_core.web.dtos + +import org.js.lorca_core.web.dtos.validators.B64Validator +import org.js.lorca_core.web.dtos.validators.UsernameValidator + +data class UserAuthDto( + @field:UsernameValidator.Validate + val username: String, + @field:B64Validator.Validate + val password: String +) \ No newline at end of file diff --git a/lorca-core/src/main/kotlin/org/js/lorca_core/web/dtos/validators/B64Validator.kt b/lorca-core/src/main/kotlin/org/js/lorca_core/web/dtos/validators/B64Validator.kt new file mode 100644 index 0000000..a7f81a1 --- /dev/null +++ b/lorca-core/src/main/kotlin/org/js/lorca_core/web/dtos/validators/B64Validator.kt @@ -0,0 +1,33 @@ +package org.js.lorca_core.web.dtos.validators + +import jakarta.validation.Constraint +import jakarta.validation.ConstraintValidator +import jakarta.validation.ConstraintValidatorContext +import jakarta.validation.Payload +import kotlin.reflect.KClass + + +class B64Validator : ConstraintValidator { + override fun isValid(value: String?, context: ConstraintValidatorContext): Boolean { + val pattern = Regex("^[-A-Za-z0-9+/]*={0,3}\$") + if (value == null || value.matches(pattern)) { + return true + } + + context.disableDefaultConstraintViolation() + context.buildConstraintViolationWithTemplate("Invalid value '$value' : Only 4 to 16 lowercase letters are allowed") + .addConstraintViolation() + + return false + } + + @Target(AnnotationTarget.FIELD, AnnotationTarget.PROPERTY, AnnotationTarget.VALUE_PARAMETER) + @Retention(AnnotationRetention.RUNTIME) + @MustBeDocumented + @Constraint(validatedBy = [B64Validator::class]) + annotation class Validate( + val message: String = "", + val groups: Array> = [], + val payload: Array> = [] + ) +} \ No newline at end of file diff --git a/lorca-core/src/main/kotlin/org/js/lorca_core/web/dtos/validators/NameValidator.kt b/lorca-core/src/main/kotlin/org/js/lorca_core/web/dtos/validators/NameValidator.kt new file mode 100644 index 0000000..00d198d --- /dev/null +++ b/lorca-core/src/main/kotlin/org/js/lorca_core/web/dtos/validators/NameValidator.kt @@ -0,0 +1,34 @@ +package org.js.lorca_core.web.dtos.validators + +import jakarta.validation.Constraint +import jakarta.validation.ConstraintValidator +import jakarta.validation.ConstraintValidatorContext +import jakarta.validation.Payload +import kotlin.reflect.KClass + + +class NameValidator : ConstraintValidator { + override fun isValid(value: String?, context: ConstraintValidatorContext): Boolean { + val pattern = Regex("^[A-Za-zÁÉÍÓÚÜÑáéíóúüñ]+(?:[-' ][A-Za-zÁÉÍÓÚÜÑáéíóúüñ]+)*$") + + if (value == null || value.matches(pattern)) { + return true + } + + context.disableDefaultConstraintViolation() + context.buildConstraintViolationWithTemplate("Invalid value '$value' : Only letters, spaces, and dashes are allowed.") + .addConstraintViolation() + + return false + } + + @Target(AnnotationTarget.FIELD, AnnotationTarget.PROPERTY, AnnotationTarget.VALUE_PARAMETER) + @Retention(AnnotationRetention.RUNTIME) + @MustBeDocumented + @Constraint(validatedBy = [NameValidator::class]) + annotation class Validate( + val message: String = "", + val groups: Array> = [], + val payload: Array> = [] + ) +} \ No newline at end of file diff --git a/lorca-core/src/main/kotlin/org/js/lorca_core/web/dtos/validators/UsernameValidator.kt b/lorca-core/src/main/kotlin/org/js/lorca_core/web/dtos/validators/UsernameValidator.kt new file mode 100644 index 0000000..2e4028d --- /dev/null +++ b/lorca-core/src/main/kotlin/org/js/lorca_core/web/dtos/validators/UsernameValidator.kt @@ -0,0 +1,33 @@ +package org.js.lorca_core.web.dtos.validators + +import jakarta.validation.Constraint +import jakarta.validation.ConstraintValidator +import jakarta.validation.ConstraintValidatorContext +import jakarta.validation.Payload +import kotlin.reflect.KClass + + +class UsernameValidator : ConstraintValidator { + override fun isValid(value: String?, context: ConstraintValidatorContext): Boolean { + val pattern = Regex("[a-z]{4,16}") + if (value == null || value.matches(pattern)) { + return true + } + + context.disableDefaultConstraintViolation() + context.buildConstraintViolationWithTemplate("Invalid value '$value' : Only 4 to 16 lowercase letters are allowed") + .addConstraintViolation() + + return false + } + + @Target(AnnotationTarget.FIELD, AnnotationTarget.PROPERTY, AnnotationTarget.VALUE_PARAMETER) + @Retention(AnnotationRetention.RUNTIME) + @MustBeDocumented + @Constraint(validatedBy = [UsernameValidator::class]) + annotation class Validate( + val message: String = "", + val groups: Array> = [], + val payload: Array> = [] + ) +} \ No newline at end of file diff --git a/lorca-core/src/main/kotlin/org/js/lorca_core/web/responses/LoginResponse.kt b/lorca-core/src/main/kotlin/org/js/lorca_core/web/responses/LoginResponse.kt new file mode 100644 index 0000000..2f76d5e --- /dev/null +++ b/lorca-core/src/main/kotlin/org/js/lorca_core/web/responses/LoginResponse.kt @@ -0,0 +1,9 @@ +package org.js.lorca_core.web.responses + +import org.js.lorca_core.common.enums.EUserRoles + +data class LoginResponse( + val token: String, + val expiresIn: Long, + val claims: List +) \ No newline at end of file diff --git a/lorca-core/src/main/resources/application.properties b/lorca-core/src/main/resources/application.properties new file mode 100644 index 0000000..acae0cd --- /dev/null +++ b/lorca-core/src/main/resources/application.properties @@ -0,0 +1,14 @@ +server.servlet.context-path=/api +spring.application.name=lorca-core +spring.datasource.url=jdbc:postgresql://0.0.0.0:5432/lorca_db +spring.datasource.username=lorca_usr +spring.datasource.password=lorca_pwd +spring.datasource.driver-class-name=org.postgresql.Driver +spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.PostgreSQLDialect +spring.jpa.generate-ddl=true +spring.jpa.hibernate.ddl-auto=update +# HOW TO GENERATE THIS KEY AT : +# PLAIN TEXT: Boh che cazzo ne so bel testo per complimenti +# SECRET KEY: Ma che minchia ne so quale puo essere una bella chiave segreta dio negraccio +security.jwt.secret-key=93d5326c5ae622c9332f291c6a9868d237e6b41fc47c5f2581448d4d90e90a1a +security.jwt.expiration-time=3600000 \ No newline at end of file diff --git a/lorca-core/src/test/kotlin/org/js/lorca_core/LorcaCoreApplicationTests.kt b/lorca-core/src/test/kotlin/org/js/lorca_core/LorcaCoreApplicationTests.kt new file mode 100644 index 0000000..1d704bc --- /dev/null +++ b/lorca-core/src/test/kotlin/org/js/lorca_core/LorcaCoreApplicationTests.kt @@ -0,0 +1,13 @@ +package org.js.lorca_core + +import org.js.lorca_core.db.entities.WorkerEntity +import org.springframework.boot.test.context.SpringBootTest + +@SpringBootTest +class LorcaCoreApplicationTests { + + @WorkerEntity + fun contextLoads() { + } + +} diff --git a/psql/.gitignore b/psql/.gitignore new file mode 100644 index 0000000..4c49bd7 --- /dev/null +++ b/psql/.gitignore @@ -0,0 +1 @@ +.env diff --git a/psql/compose.yaml b/psql/compose.yaml new file mode 100644 index 0000000..5aece9f --- /dev/null +++ b/psql/compose.yaml @@ -0,0 +1,21 @@ +services: + postgres: + container_name: postgres + image: postgres:latest + environment: + - POSTGRES_USER=${POSTGRES_USER} + - POSTGRES_PASSWORD=${POSTGRES_PW} + - POSTGRES_DB=${POSTGRES_DB} + ports: + - "5432:5432" + restart: always + + pgadmin: + container_name: pgadmin + image: dpage/pgadmin4:latest + environment: + - PGADMIN_DEFAULT_EMAIL=${PGADMIN_MAIL} + - PGADMIN_DEFAULT_PASSWORD=${PGADMIN_PW} + ports: + - "5050:80" + restart: always