base commit

This commit is contained in:
Jari 2025-03-10 22:54:26 +01:00
commit 4869b53c3c
58 changed files with 1656 additions and 0 deletions

5
lorca-core/.env Normal file
View File

@ -0,0 +1,5 @@
POSTGRES_USER=lorca_usr
POSTGRES_PW=lorca_pwd
POSTGRES_DB=lorca_db
PGADMIN_MAIL=scijar@gmail.com
PGADMIN_PW=lorcapwd

3
lorca-core/.gitattributes vendored Normal file
View File

@ -0,0 +1,3 @@
/gradlew text eol=lf
*.bat text eol=crlf
*.jar binary

40
lorca-core/.gitignore vendored Normal file
View File

@ -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

31
lorca-core/Dockerfile Normal file
View File

@ -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"]

View File

@ -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<Test> {
useJUnitPlatform()
}
tasks.register<Exec>("testJeko") {
commandLine("docker", "build", "-t", "be-local:$version", ".")
}

38
lorca-core/compose.yaml Normal file
View File

@ -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:

Binary file not shown.

View File

@ -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

252
lorca-core/gradlew vendored Normal file
View File

@ -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" "$@"

94
lorca-core/gradlew.bat vendored Normal file
View File

@ -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

View File

@ -0,0 +1 @@
rootProject.name = "lorca-core"

View File

@ -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<String>) {
runApplication<LorcaCoreApplication>(*args)
}

View File

@ -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<Client, ClientEntity>

View File

@ -0,0 +1,13 @@
package org.js.lorca_core.business.mappers
interface GenericMapper<M, E> {
fun toEntity(model: M): E
fun toModel(entity: E): M
fun toEntities(models: MutableList<M>): MutableList<E> =
models.map { toEntity(it) }.toMutableList()
fun toModels(entities: MutableList<E>): MutableList<M> =
entities.map { toModel(it) }.toMutableList()
}

View File

@ -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<UserAuthClaim, UserAuthClaimEntity>

View File

@ -0,0 +1,7 @@
package org.js.lorca_core.business.models
data class Client(
var id: Long?,
var name: String,
var surname: String
)

View File

@ -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
)

View File

@ -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<Client>
fun getById(id: Long): Client
}

View File

@ -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<EUserRoles>
}

View File

@ -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<Client> {
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
)
})
}
}

View File

@ -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<EUserRoles> {
return claimMapper.toModels(user.claims).map { it.name }.toList()
}
}

View File

@ -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")
}

View File

@ -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")
}

View File

@ -0,0 +1,5 @@
package org.js.lorca_core.common.enums
enum class EWorkerCategory(name: String) {
FISIO("FISIO")
}

View File

@ -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))
}
}
}

View File

@ -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()
}
}

View File

@ -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
}
}

View File

@ -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)
}
}
}

View File

@ -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<ClientEntity, Long>

View File

@ -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<UserAuthEntity, Long> {
fun findByUsr(username: String): Optional<UserAuthEntity>
}

View File

@ -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<WorkerEntity, Long> {
fun findAllByCategoryName(@Param("category") category: EWorkerCategory): MutableList<WorkerEntity>
}

View File

@ -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
)

View File

@ -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<ClientEntity> = mutableListOf()
)

View File

@ -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
)

View File

@ -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<UserAuthClaimEntity> = mutableListOf()
override fun getAuthorities(): Collection<GrantedAuthority> {
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
}
}

View File

@ -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
)

View File

@ -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
)

View File

@ -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<EUserRoles>
}

View File

@ -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<Client>
fun getClientById(id: Long): Client
fun createClient(clientDto: ClientDto): Client
}

View File

@ -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 <T> extractClaim(token: String, claimsResolver: Function<Claims, T>): T
fun generateToken(userDetails: UserDetails): String
fun generateToken(extraClaims: Map<String, Any>, userDetails: UserDetails): String
fun getExpirationTime(): Long
fun isTokenValid(token: String, userDetails: UserDetails): Boolean
}

View File

@ -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<EUserRoles> {
return userAuthRepository.getClaimsForuser(user)
}
}

View File

@ -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<Client> {
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))
}
}

View File

@ -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 <T> extractClaim(token: String, claimsResolver: Function<Claims, T>): 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<String, Any>, userDetails: UserDetails): String {
return buildToken(extraClaims, userDetails, jwtExpiration)
}
override fun getExpirationTime(): Long {
return jwtExpiration
}
private fun buildToken(
extraClaims: Map<String, Any>,
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)
}
}

View File

@ -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<Nothing> {
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<Nothing> {
return WebResponse.ko(
HttpStatus.BAD_REQUEST,
"${HttpStatus.BAD_REQUEST.reasonPhrase}: ${ex.message}"
)
}
@ExceptionHandler(NoResourceFoundException::class)
fun handleNoResourceFoundException(
ex: NoResourceFoundException,
request: WebRequest
): WebResponse<Nothing> {
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<Nothing> {
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<Nothing> {
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<Nothing> {
return WebResponse.ko(
HttpStatus.NOT_ACCEPTABLE,
"${HttpStatus.NOT_ACCEPTABLE.reasonPhrase}: JSON parse error"
)
}
@ExceptionHandler(Exception::class)
fun handleException(
ex: Exception,
request: WebRequest
): WebResponse<Nothing> {
return WebResponse.ko(
HttpStatus.INTERNAL_SERVER_ERROR,
ex.message
)
}
}

View File

@ -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)
// }
}

View File

@ -0,0 +1,30 @@
package org.js.lorca_core.web.advices
import org.springframework.http.HttpStatus
data class WebResponse<T>(
val status: HttpStatus,
val error: String? = null,
val data: T? = null
) {
companion object {
fun <T> ok(): WebResponse<T> {
return WebResponse(status = HttpStatus.OK)
}
fun <T> ok(data: T): WebResponse<T> {
return WebResponse(status = HttpStatus.OK, data = data)
}
fun <T> ko(status: HttpStatus, error: String?): WebResponse<T> {
return WebResponse(status = status, error = error)
}
fun <T> ko(status: HttpStatus, errors: List<String>): WebResponse<T> {
return WebResponse(status = status, error = errors.toString())
}
}
}

View File

@ -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<Nothing> {
authenticationService.register(registerUserDto)
return WebResponse.ok()
}
@PostMapping("/login")
fun authenticate(@Valid @RequestBody loginUserDto: UserAuthDto): WebResponse<LoginResponse> {
val user = authenticationService.login(loginUserDto)
return WebResponse.ok(
LoginResponse(
jwtService.generateToken(user),
jwtService.getExpirationTime(),
authenticationService.getClaimsForUser(user)
)
)
}
}

View File

@ -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<List<Client>> {
return WebResponse.ok(clientService.getAllClients(name, surname))
}
@PostMapping
fun createClient(@Valid @RequestBody clientDto: ClientDto): WebResponse<Client> {
return WebResponse.ok(clientService.createClient(clientDto))
}
@GetMapping("/{id}")
fun getClient(@PathVariable("id") id: String): WebResponse<Client> {
return WebResponse.ok(clientService.getClientById(id.toLong()))
}
}

View File

@ -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
)

View File

@ -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
)

View File

@ -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<B64Validator.Validate, String> {
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<KClass<*>> = [],
val payload: Array<KClass<out Payload>> = []
)
}

View File

@ -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<NameValidator.Validate, String> {
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<KClass<*>> = [],
val payload: Array<KClass<out Payload>> = []
)
}

View File

@ -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<UsernameValidator.Validate, String> {
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<KClass<*>> = [],
val payload: Array<KClass<out Payload>> = []
)
}

View File

@ -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<EUserRoles>
)

View File

@ -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

View File

@ -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() {
}
}

1
psql/.gitignore vendored Normal file
View File

@ -0,0 +1 @@
.env

21
psql/compose.yaml Normal file
View File

@ -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