initial commit
This commit is contained in:
9
backend/.gitignore
vendored
Normal file
9
backend/.gitignore
vendored
Normal file
@@ -0,0 +1,9 @@
|
||||
# IDE
|
||||
/.idea/
|
||||
|
||||
# Gradle
|
||||
/.gradle/
|
||||
/gradle.properties
|
||||
|
||||
# Kotlin
|
||||
/build/
|
||||
41
backend/build.gradle.kts
Normal file
41
backend/build.gradle.kts
Normal file
@@ -0,0 +1,41 @@
|
||||
group = "com.infendro.account"
|
||||
version = "0.0.1"
|
||||
|
||||
application {
|
||||
mainClass.set("com.infendro.account.ApplicationKt")
|
||||
}
|
||||
|
||||
repositories {
|
||||
maven("https://git.infendro.com/api/packages/Infendro/maven")
|
||||
mavenCentral()
|
||||
}
|
||||
|
||||
plugins {
|
||||
alias(libs.plugins.kotlin)
|
||||
alias(libs.plugins.ktor)
|
||||
alias(libs.plugins.serialization)
|
||||
}
|
||||
|
||||
dependencies {
|
||||
implementation(libs.ktor.server)
|
||||
implementation(libs.ktor.server.cio)
|
||||
implementation(libs.ktor.server.auth)
|
||||
implementation(libs.ktor.server.sessions)
|
||||
implementation(libs.ktor.server.resources)
|
||||
implementation(libs.ktor.server.statusPages)
|
||||
implementation(libs.ktor.server.contentNegotiation)
|
||||
implementation(libs.ktor.server.serialization)
|
||||
implementation(libs.ktor.server.validation)
|
||||
implementation(libs.exposed)
|
||||
implementation(libs.exposed.dao)
|
||||
implementation(libs.exposed.jdbc)
|
||||
implementation(libs.postgres)
|
||||
implementation(libs.flyway)
|
||||
implementation(libs.flyway.postgres)
|
||||
implementation(libs.koin)
|
||||
implementation(libs.koin.logger)
|
||||
implementation(libs.otp)
|
||||
implementation(libs.hash)
|
||||
implementation(libs.encoding)
|
||||
implementation(libs.logback)
|
||||
}
|
||||
43
backend/gradle/libs.versions.toml
Normal file
43
backend/gradle/libs.versions.toml
Normal file
@@ -0,0 +1,43 @@
|
||||
[versions]
|
||||
kotlin = "2.1.21"
|
||||
ktor = "3.1.3"
|
||||
exposed = "0.60.0"
|
||||
postgres = "42.7.5"
|
||||
flyway = "11.7.0"
|
||||
koin = "4.0.3"
|
||||
otp = "1.1.0"
|
||||
hash = "1.1.0"
|
||||
encoding = "1.1.0"
|
||||
logback = "1.5.18"
|
||||
|
||||
[plugins]
|
||||
kotlin = { id = "org.jetbrains.kotlin.jvm", version.ref = "kotlin" }
|
||||
ktor = { id = "io.ktor.plugin", version.ref = "ktor" }
|
||||
serialization = { id = "org.jetbrains.kotlin.plugin.serialization", version.ref = "kotlin" }
|
||||
|
||||
[libraries]
|
||||
ktor-server = { module = "io.ktor:ktor-server-core-jvm", version.ref = "ktor" }
|
||||
ktor-server-cio = { module = "io.ktor:ktor-server-cio", version.ref = "ktor" }
|
||||
ktor-server-auth = { module = "io.ktor:ktor-server-auth-jvm", version.ref = "ktor" }
|
||||
ktor-server-sessions = { module = "io.ktor:ktor-server-sessions-jvm", version.ref = "ktor" }
|
||||
ktor-server-resources = { module = "io.ktor:ktor-server-resources", version.ref = "ktor" }
|
||||
ktor-server-statusPages = { module = "io.ktor:ktor-server-status-pages", version.ref = "ktor" }
|
||||
ktor-server-contentNegotiation = { module = "io.ktor:ktor-server-content-negotiation-jvm", version.ref = "ktor" }
|
||||
ktor-server-serialization = { module = "io.ktor:ktor-serialization-kotlinx-json-jvm", version.ref = "ktor" }
|
||||
ktor-server-validation = { module = "io.ktor:ktor-server-request-validation", version.ref = "ktor" }
|
||||
|
||||
exposed = { module = "org.jetbrains.exposed:exposed-core", version.ref = "exposed" }
|
||||
exposed-dao = { module = "org.jetbrains.exposed:exposed-dao", version.ref = "exposed" }
|
||||
exposed-jdbc = { module = "org.jetbrains.exposed:exposed-jdbc", version.ref = "exposed" }
|
||||
postgres = { module = "org.postgresql:postgresql", version.ref = "postgres" }
|
||||
flyway = { module = "org.flywaydb:flyway-core", version.ref = "flyway" }
|
||||
flyway-postgres = { module = "org.flywaydb:flyway-database-postgresql", version.ref = "flyway" }
|
||||
|
||||
koin = { module = "io.insert-koin:koin-ktor", version.ref = "koin" }
|
||||
koin-logger = { module = "io.insert-koin:koin-logger-slf4j", version.ref = "koin" }
|
||||
|
||||
otp = { module = "com.infendro:otp", version.ref = "otp" }
|
||||
hash = { module = "com.infendro:hash", version.ref = "hash" }
|
||||
encoding = { module = "com.infendro:encoding", version.ref = "encoding" }
|
||||
|
||||
logback = { module = "ch.qos.logback:logback-classic", version.ref = "logback" }
|
||||
BIN
backend/gradle/wrapper/gradle-wrapper.jar
vendored
Normal file
BIN
backend/gradle/wrapper/gradle-wrapper.jar
vendored
Normal file
Binary file not shown.
7
backend/gradle/wrapper/gradle-wrapper.properties
vendored
Normal file
7
backend/gradle/wrapper/gradle-wrapper.properties
vendored
Normal file
@@ -0,0 +1,7 @@
|
||||
distributionBase=GRADLE_USER_HOME
|
||||
distributionPath=wrapper/dists
|
||||
distributionUrl=https\://services.gradle.org/distributions/gradle-8.8-bin.zip
|
||||
networkTimeout=10000
|
||||
validateDistributionUrl=true
|
||||
zipStoreBase=GRADLE_USER_HOME
|
||||
zipStorePath=wrapper/dists
|
||||
249
backend/gradlew
vendored
Executable file
249
backend/gradlew
vendored
Executable file
@@ -0,0 +1,249 @@
|
||||
#!/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.
|
||||
#
|
||||
|
||||
##############################################################################
|
||||
#
|
||||
# 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 "${APP_HOME:-./}" > /dev/null && pwd -P ) || 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" "$@"
|
||||
92
backend/gradlew.bat
vendored
Normal file
92
backend/gradlew.bat
vendored
Normal file
@@ -0,0 +1,92 @@
|
||||
@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
|
||||
|
||||
@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
|
||||
1
backend/settings.gradle.kts
Normal file
1
backend/settings.gradle.kts
Normal file
@@ -0,0 +1 @@
|
||||
rootProject.name = "backend"
|
||||
22
backend/src/main/kotlin/com/infendro/account/Application.kt
Normal file
22
backend/src/main/kotlin/com/infendro/account/Application.kt
Normal file
@@ -0,0 +1,22 @@
|
||||
package com.infendro.account
|
||||
|
||||
import com.infendro.account.config.*
|
||||
import com.infendro.account.model.initializeDatabase
|
||||
import io.ktor.server.application.*
|
||||
import io.ktor.server.cio.*
|
||||
|
||||
fun main(
|
||||
args: Array<String>,
|
||||
) = EngineMain.main(args)
|
||||
|
||||
fun Application.module() {
|
||||
configureDatabase()
|
||||
configureDependencyInjection()
|
||||
configureSecurity()
|
||||
configureSerialization()
|
||||
configureValidation()
|
||||
configureRouting()
|
||||
configureException()
|
||||
|
||||
initializeDatabase()
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
package com.infendro.account.config
|
||||
|
||||
import io.ktor.server.config.ApplicationConfig
|
||||
|
||||
data class DatabaseConfig(
|
||||
val host: String,
|
||||
val username: String,
|
||||
val password: String,
|
||||
) {
|
||||
val url: String
|
||||
get() = "jdbc:postgresql://${host}/account"
|
||||
}
|
||||
|
||||
data class SecurityConfig(
|
||||
val cookie: CookieConfig,
|
||||
)
|
||||
|
||||
data class CookieConfig(
|
||||
val domain: String,
|
||||
val path: String,
|
||||
val secure: Boolean,
|
||||
)
|
||||
|
||||
val ApplicationConfig.database: DatabaseConfig
|
||||
get() {
|
||||
val host = property("database.host").getString()
|
||||
val username = property("database.username").getString()
|
||||
val password = property("database.password").getString()
|
||||
|
||||
return DatabaseConfig(host, username, password)
|
||||
}
|
||||
|
||||
val ApplicationConfig.security: SecurityConfig
|
||||
get() {
|
||||
return SecurityConfig(cookie)
|
||||
}
|
||||
|
||||
private val ApplicationConfig.cookie: CookieConfig
|
||||
get() {
|
||||
val domain = property("security.cookie.domain").getString()
|
||||
val path = property("security.cookie.path").getString()
|
||||
val secure = property("security.cookie.secure").getString().toBooleanStrict()
|
||||
|
||||
return CookieConfig(domain, path, secure)
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
package com.infendro.account.config
|
||||
|
||||
import io.ktor.server.application.Application
|
||||
import org.flywaydb.core.Flyway
|
||||
import org.jetbrains.exposed.sql.Database
|
||||
|
||||
fun Application.configureDatabase() {
|
||||
val config = environment.config.database
|
||||
|
||||
Database.connect(
|
||||
url = config.url,
|
||||
user = config.username,
|
||||
password = config.password,
|
||||
)
|
||||
|
||||
val flyway = Flyway.configure()
|
||||
.dataSource(config.url, config.username, config.password)
|
||||
.load()
|
||||
flyway.migrate()
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
package com.infendro.account.config
|
||||
|
||||
import com.infendro.account.model.repository.AccessRepository
|
||||
import com.infendro.account.model.repository.AccountRepository
|
||||
import com.infendro.account.model.repository.InitializationRepository
|
||||
import com.infendro.account.model.repository.SessionRepository
|
||||
import com.infendro.account.service.AccessService
|
||||
import com.infendro.account.service.AccountService
|
||||
import com.infendro.account.service.RoleService
|
||||
import com.infendro.account.service.SessionService
|
||||
import io.ktor.server.application.*
|
||||
import org.koin.core.module.dsl.singleOf
|
||||
import org.koin.dsl.module
|
||||
import org.koin.ktor.plugin.koin
|
||||
import org.koin.logger.slf4jLogger
|
||||
|
||||
fun Application.configureDependencyInjection() {
|
||||
koin {
|
||||
slf4jLogger()
|
||||
modules(module)
|
||||
}
|
||||
}
|
||||
|
||||
private val module = module {
|
||||
singleOf(::InitializationRepository)
|
||||
singleOf(::AccessRepository)
|
||||
singleOf(::AccountRepository)
|
||||
singleOf(::SessionRepository)
|
||||
|
||||
singleOf(::AccessService)
|
||||
singleOf(::AccountService)
|
||||
singleOf(::RoleService)
|
||||
singleOf(::SessionService)
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
package com.infendro.account.config
|
||||
|
||||
import com.infendro.account.exception.StatusException
|
||||
import io.ktor.http.HttpStatusCode.Companion.BadRequest
|
||||
import io.ktor.server.application.*
|
||||
import io.ktor.server.plugins.requestvalidation.*
|
||||
import io.ktor.server.plugins.statuspages.*
|
||||
import io.ktor.server.response.*
|
||||
|
||||
fun Application.configureException() {
|
||||
install(StatusPages) {
|
||||
exception<StatusException> { call, exception ->
|
||||
call.respond(exception.status)
|
||||
}
|
||||
exception<RequestValidationException> { call, _ ->
|
||||
call.respond(BadRequest)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
package com.infendro.account.config
|
||||
|
||||
import com.infendro.account.routing.access
|
||||
import com.infendro.account.routing.account
|
||||
import com.infendro.account.routing.role
|
||||
import com.infendro.account.routing.session
|
||||
import io.ktor.server.application.*
|
||||
import io.ktor.server.resources.*
|
||||
import io.ktor.server.routing.*
|
||||
|
||||
fun Application.configureRouting() {
|
||||
install(Resources)
|
||||
routing {
|
||||
access()
|
||||
account()
|
||||
role()
|
||||
session()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,69 @@
|
||||
package com.infendro.account.config
|
||||
|
||||
import com.infendro.account.exception.client.UnauthorizedException
|
||||
import com.infendro.account.model.Role
|
||||
import com.infendro.account.model.entity.AccountEntity
|
||||
import com.infendro.account.model.entity.SessionEntity
|
||||
import com.infendro.account.model.entity.SessionTable
|
||||
import com.infendro.account.model.repository.SessionRepository
|
||||
import com.infendro.account.util.Hasher
|
||||
import io.ktor.server.application.Application
|
||||
import io.ktor.server.application.install
|
||||
import io.ktor.server.auth.Authentication
|
||||
import io.ktor.server.auth.session
|
||||
import io.ktor.server.sessions.*
|
||||
import kotlin.time.Duration.Companion.days
|
||||
import kotlinx.serialization.Serializable
|
||||
import org.jetbrains.exposed.sql.SqlExpressionBuilder.eq
|
||||
import org.koin.ktor.ext.inject
|
||||
|
||||
@Serializable
|
||||
data class AuthenticationSession(
|
||||
val token: String,
|
||||
)
|
||||
|
||||
data class AuthenticationPrincipal(
|
||||
val account: AccountEntity,
|
||||
val session: SessionEntity,
|
||||
) {
|
||||
val role: Role
|
||||
get() = account.role
|
||||
}
|
||||
|
||||
fun Application.configureSecurity() {
|
||||
val config = environment.config.security
|
||||
|
||||
install(Sessions) {
|
||||
cookie<AuthenticationSession>(
|
||||
"Authentication",
|
||||
SessionStorageMemory(),
|
||||
) {
|
||||
cookie.domain = config.cookie.domain
|
||||
cookie.path = config.cookie.path
|
||||
cookie.httpOnly = true
|
||||
cookie.secure = config.cookie.secure
|
||||
cookie.extensions["SameSite"] = "Strict"
|
||||
cookie.maxAge = 7.days
|
||||
}
|
||||
}
|
||||
install(Authentication) {
|
||||
session<AuthenticationSession> {
|
||||
validate { authenticationSession ->
|
||||
val sessionRepository by inject<SessionRepository>()
|
||||
|
||||
val session = sessionRepository
|
||||
.singleOrNull { SessionTable.tokenHash eq Hasher.hash(authenticationSession.token) }
|
||||
?: return@validate null
|
||||
|
||||
sessions.set(authenticationSession)
|
||||
|
||||
AuthenticationPrincipal(session.account(), session)
|
||||
}
|
||||
challenge {
|
||||
call.sessions.clear<AuthenticationSession>()
|
||||
|
||||
throw UnauthorizedException()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
package com.infendro.account.config
|
||||
|
||||
import io.ktor.serialization.kotlinx.json.*
|
||||
import io.ktor.server.application.*
|
||||
import io.ktor.server.plugins.contentnegotiation.*
|
||||
|
||||
fun Application.configureSerialization() {
|
||||
install(ContentNegotiation) {
|
||||
json()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
package com.infendro.account.config
|
||||
|
||||
import com.infendro.account.dto.request.validatePostAccountRequest
|
||||
import com.infendro.account.dto.request.validatePutAccountCurrentPasswordRequest
|
||||
import com.infendro.account.dto.request.validatePutAccountCurrentUsernameRequest
|
||||
import io.ktor.server.application.*
|
||||
import io.ktor.server.plugins.requestvalidation.*
|
||||
|
||||
fun Application.configureValidation() {
|
||||
install(RequestValidation) {
|
||||
validatePostAccountRequest()
|
||||
validatePutAccountCurrentUsernameRequest()
|
||||
validatePutAccountCurrentPasswordRequest()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
package com.infendro.account.dto.request
|
||||
|
||||
import com.infendro.account.util.REGEX_PASSWORD
|
||||
import com.infendro.account.util.REGEX_USERNAME
|
||||
import io.ktor.server.plugins.requestvalidation.RequestValidationConfig
|
||||
import io.ktor.server.plugins.requestvalidation.ValidationResult.Invalid
|
||||
import io.ktor.server.plugins.requestvalidation.ValidationResult.Valid
|
||||
import kotlinx.serialization.Serializable
|
||||
|
||||
@Serializable
|
||||
data class PostAccountRequest(
|
||||
val username: String,
|
||||
val password: String,
|
||||
val access: PostAccountRequestAccess,
|
||||
)
|
||||
|
||||
@Serializable
|
||||
data class PostAccountRequestAccess(
|
||||
val token: String,
|
||||
)
|
||||
|
||||
fun RequestValidationConfig.validatePostAccountRequest() {
|
||||
validate<PostAccountRequest> { request ->
|
||||
when {
|
||||
!REGEX_USERNAME.matches(request.username) -> Invalid("")
|
||||
!REGEX_PASSWORD.matches(request.password) -> Invalid("")
|
||||
else -> Valid
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
package com.infendro.account.dto.request
|
||||
|
||||
import kotlinx.serialization.Serializable
|
||||
|
||||
@Serializable
|
||||
data class PostSessionRequest(
|
||||
val username: String,
|
||||
val password: String,
|
||||
val otp: String,
|
||||
)
|
||||
@@ -0,0 +1,21 @@
|
||||
package com.infendro.account.dto.request
|
||||
|
||||
import com.infendro.account.util.REGEX_PASSWORD
|
||||
import io.ktor.server.plugins.requestvalidation.*
|
||||
import io.ktor.server.plugins.requestvalidation.ValidationResult.*
|
||||
import kotlinx.serialization.Serializable
|
||||
|
||||
@Serializable
|
||||
data class PutAccountCurrentPasswordRequest(
|
||||
val password: String,
|
||||
val otp: String,
|
||||
)
|
||||
|
||||
fun RequestValidationConfig.validatePutAccountCurrentPasswordRequest() {
|
||||
validate<PutAccountCurrentPasswordRequest> { request ->
|
||||
when {
|
||||
!REGEX_PASSWORD.matches(request.password) -> Invalid("")
|
||||
else -> Valid
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
package com.infendro.account.dto.request
|
||||
|
||||
import com.infendro.account.util.REGEX_USERNAME
|
||||
import io.ktor.server.plugins.requestvalidation.*
|
||||
import io.ktor.server.plugins.requestvalidation.ValidationResult.*
|
||||
import kotlinx.serialization.Serializable
|
||||
|
||||
@Serializable
|
||||
data class PutAccountCurrentUsernameRequest(
|
||||
val username: String,
|
||||
val otp: String,
|
||||
)
|
||||
|
||||
fun RequestValidationConfig.validatePutAccountCurrentUsernameRequest() {
|
||||
validate<PutAccountCurrentUsernameRequest> { request ->
|
||||
when {
|
||||
!REGEX_USERNAME.matches(request.username) -> Invalid("")
|
||||
else -> Valid
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
package com.infendro.account.dto.request
|
||||
|
||||
import com.infendro.account.model.Role
|
||||
import kotlinx.serialization.Serializable
|
||||
|
||||
@Serializable
|
||||
data class PutAccountIdRoleRequest(
|
||||
val role: Role,
|
||||
)
|
||||
@@ -0,0 +1,13 @@
|
||||
package com.infendro.account.dto.response
|
||||
|
||||
import com.infendro.account.model.entity.AccessEntity
|
||||
import kotlinx.serialization.Serializable
|
||||
|
||||
@Serializable
|
||||
data class AccessResponse(
|
||||
val id: Long,
|
||||
)
|
||||
|
||||
fun AccessEntity.toResponse() = AccessResponse(
|
||||
id = id.value,
|
||||
)
|
||||
@@ -0,0 +1,23 @@
|
||||
package com.infendro.account.dto.response
|
||||
|
||||
import com.infendro.account.model.Role
|
||||
import com.infendro.account.model.entity.AccountEntity
|
||||
import com.infendro.account.model.entity.SessionEntity
|
||||
import kotlinx.serialization.Serializable
|
||||
|
||||
@Serializable
|
||||
data class AccountResponse(
|
||||
val id: Long,
|
||||
val username: String,
|
||||
val role: Role,
|
||||
val sessions: List<SessionResponse>,
|
||||
)
|
||||
|
||||
fun AccountEntity.toResponse(): AccountResponse {
|
||||
return AccountResponse(
|
||||
id = id.value,
|
||||
username = username,
|
||||
role = role,
|
||||
sessions = sessions().map(SessionEntity::toResponse),
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
package com.infendro.account.dto.response
|
||||
|
||||
import kotlinx.serialization.Serializable
|
||||
|
||||
@Serializable
|
||||
data class PostAccessResponse(
|
||||
val token: String,
|
||||
)
|
||||
@@ -0,0 +1,8 @@
|
||||
package com.infendro.account.dto.response
|
||||
|
||||
import kotlinx.serialization.Serializable
|
||||
|
||||
@Serializable
|
||||
data class PostAccountResponse(
|
||||
val secret: String,
|
||||
)
|
||||
@@ -0,0 +1,15 @@
|
||||
package com.infendro.account.dto.response
|
||||
|
||||
import com.infendro.account.model.Role
|
||||
import kotlinx.serialization.Serializable
|
||||
|
||||
@Serializable
|
||||
data class RoleResponse(
|
||||
val role: Role,
|
||||
val children: List<Role>,
|
||||
)
|
||||
|
||||
fun Role.toResponse() = RoleResponse(
|
||||
role = this,
|
||||
children = children,
|
||||
)
|
||||
@@ -0,0 +1,17 @@
|
||||
package com.infendro.account.dto.response
|
||||
|
||||
import com.infendro.account.model.entity.SessionEntity
|
||||
import kotlinx.serialization.Serializable
|
||||
|
||||
@Serializable
|
||||
data class SessionResponse(
|
||||
val id: Long,
|
||||
val accountId: Long,
|
||||
)
|
||||
|
||||
fun SessionEntity.toResponse(): SessionResponse {
|
||||
return SessionResponse(
|
||||
id = id.value,
|
||||
accountId = account().id.value,
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
package com.infendro.account.exception
|
||||
|
||||
import io.ktor.http.HttpStatusCode
|
||||
|
||||
abstract class StatusException(
|
||||
val status: HttpStatusCode,
|
||||
) : Exception()
|
||||
@@ -0,0 +1,6 @@
|
||||
package com.infendro.account.exception.client
|
||||
|
||||
import com.infendro.account.exception.StatusException
|
||||
import io.ktor.http.HttpStatusCode.Companion.BadRequest
|
||||
|
||||
class BadRequestException : StatusException(BadRequest)
|
||||
@@ -0,0 +1,6 @@
|
||||
package com.infendro.account.exception.client
|
||||
|
||||
import com.infendro.account.exception.StatusException
|
||||
import io.ktor.http.HttpStatusCode.Companion.Conflict
|
||||
|
||||
class ConflictException : StatusException(Conflict)
|
||||
@@ -0,0 +1,6 @@
|
||||
package com.infendro.account.exception.client
|
||||
|
||||
import com.infendro.account.exception.StatusException
|
||||
import io.ktor.http.HttpStatusCode.Companion.Forbidden
|
||||
|
||||
class ForbiddenException : StatusException(Forbidden)
|
||||
@@ -0,0 +1,6 @@
|
||||
package com.infendro.account.exception.client
|
||||
|
||||
import com.infendro.account.exception.StatusException
|
||||
import io.ktor.http.HttpStatusCode.Companion.NotFound
|
||||
|
||||
class NotFoundException : StatusException(NotFound)
|
||||
@@ -0,0 +1,6 @@
|
||||
package com.infendro.account.exception.client
|
||||
|
||||
import com.infendro.account.exception.StatusException
|
||||
import io.ktor.http.HttpStatusCode.Companion.Unauthorized
|
||||
|
||||
class UnauthorizedException : StatusException(Unauthorized)
|
||||
@@ -0,0 +1,6 @@
|
||||
package com.infendro.account.exception.server
|
||||
|
||||
import com.infendro.account.exception.StatusException
|
||||
import io.ktor.http.HttpStatusCode.Companion.InternalServerError
|
||||
|
||||
class InternalServerErrorException : StatusException(InternalServerError)
|
||||
@@ -0,0 +1,6 @@
|
||||
package com.infendro.account.exception.server
|
||||
|
||||
import com.infendro.account.exception.StatusException
|
||||
import io.ktor.http.HttpStatusCode.Companion.NotImplemented
|
||||
|
||||
class NotImplementedException : StatusException(NotImplemented)
|
||||
@@ -0,0 +1,44 @@
|
||||
package com.infendro.account.model
|
||||
|
||||
import com.infendro.account.model.entity.InitializationTable
|
||||
import com.infendro.account.model.repository.AccountRepository
|
||||
import com.infendro.account.model.repository.InitializationRepository
|
||||
import com.infendro.account.util.SecureHasher
|
||||
import io.ktor.server.application.Application
|
||||
import org.jetbrains.exposed.sql.SqlExpressionBuilder.eq
|
||||
import org.koin.ktor.ext.inject
|
||||
|
||||
fun Application.initializeDatabase() {
|
||||
owner()
|
||||
}
|
||||
|
||||
private fun Application.owner() = initialize("owner") {
|
||||
val accountRepository by inject<AccountRepository>()
|
||||
|
||||
accountRepository.insert {
|
||||
val salt = SecureHasher.generateSalt()
|
||||
|
||||
this.username = "infendro"
|
||||
this.passwordHash = SecureHasher.hash("password", salt)
|
||||
this.passwordSalt = salt
|
||||
this.secret = "deadbeef"
|
||||
this.role = Role.OWNER
|
||||
}
|
||||
}
|
||||
|
||||
private fun Application.initialize(
|
||||
name: String,
|
||||
block: () -> Unit,
|
||||
) {
|
||||
val initializationRepository by inject<InitializationRepository>()
|
||||
|
||||
initializationRepository
|
||||
.singleOrNull { InitializationTable.name eq name }
|
||||
?.run { return }
|
||||
|
||||
block()
|
||||
|
||||
initializationRepository.insert {
|
||||
this.name = name
|
||||
}
|
||||
}
|
||||
34
backend/src/main/kotlin/com/infendro/account/model/Role.kt
Normal file
34
backend/src/main/kotlin/com/infendro/account/model/Role.kt
Normal file
@@ -0,0 +1,34 @@
|
||||
package com.infendro.account.model
|
||||
|
||||
enum class Role(
|
||||
val children: List<Role> = listOf(),
|
||||
) {
|
||||
USER,
|
||||
OWNER(
|
||||
children = listOf(USER),
|
||||
);
|
||||
|
||||
fun hasChild(
|
||||
role: Role,
|
||||
): Boolean {
|
||||
return children.contains(role)
|
||||
}
|
||||
|
||||
companion object {
|
||||
val ALL = entries.toList()
|
||||
}
|
||||
}
|
||||
|
||||
infix fun List<Role>.except(
|
||||
roles: List<Role>,
|
||||
): List<Role> {
|
||||
return filterNot { it in roles }
|
||||
.toList()
|
||||
}
|
||||
|
||||
infix fun List<Role>.except(
|
||||
role: Role,
|
||||
): List<Role> {
|
||||
return filterNot { it == role }
|
||||
.toList()
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
package com.infendro.account.model.entity
|
||||
|
||||
import org.jetbrains.exposed.dao.LongEntity
|
||||
import org.jetbrains.exposed.dao.LongEntityClass
|
||||
import org.jetbrains.exposed.dao.id.EntityID
|
||||
import org.jetbrains.exposed.dao.id.LongIdTable
|
||||
|
||||
object AccessTable : LongIdTable("access", "id") {
|
||||
val tokenHash = text("token_hash")
|
||||
}
|
||||
|
||||
class AccessEntity(id: EntityID<Long>) : LongEntity(id) {
|
||||
companion object : LongEntityClass<AccessEntity>(AccessTable)
|
||||
|
||||
var tokenHash by AccessTable.tokenHash
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
package com.infendro.account.model.entity
|
||||
|
||||
import com.infendro.account.model.Role
|
||||
import org.jetbrains.exposed.dao.LongEntity
|
||||
import org.jetbrains.exposed.dao.LongEntityClass
|
||||
import org.jetbrains.exposed.dao.id.EntityID
|
||||
import org.jetbrains.exposed.dao.id.LongIdTable
|
||||
import org.jetbrains.exposed.sql.transactions.transaction
|
||||
|
||||
object AccountTable : LongIdTable("account", "id") {
|
||||
val username = text("username")
|
||||
val passwordHash = text("password_hash")
|
||||
val passwordSalt = text("password_salt")
|
||||
val secret = text("secret")
|
||||
val role = customEnumeration(
|
||||
"role",
|
||||
fromDb = {
|
||||
when (it) {
|
||||
is String -> Role.valueOf(it)
|
||||
else -> throw Error()
|
||||
}
|
||||
},
|
||||
toDb = { it.name }
|
||||
)
|
||||
}
|
||||
|
||||
class AccountEntity(id: EntityID<Long>) : LongEntity(id) {
|
||||
companion object : LongEntityClass<AccountEntity>(AccountTable)
|
||||
|
||||
var username by AccountTable.username
|
||||
var passwordHash by AccountTable.passwordHash
|
||||
var passwordSalt by AccountTable.passwordSalt
|
||||
var secret by AccountTable.secret
|
||||
var role by AccountTable.role
|
||||
|
||||
val sessions by SessionEntity referrersOn SessionTable.accountId
|
||||
|
||||
fun sessions() = transaction { sessions.toList() }
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
package com.infendro.account.model.entity
|
||||
|
||||
import org.jetbrains.exposed.dao.LongEntity
|
||||
import org.jetbrains.exposed.dao.LongEntityClass
|
||||
import org.jetbrains.exposed.dao.id.EntityID
|
||||
import org.jetbrains.exposed.dao.id.LongIdTable
|
||||
|
||||
object InitializationTable : LongIdTable("initialization", "id") {
|
||||
val name = text("name")
|
||||
}
|
||||
|
||||
class InitializationEntity(id: EntityID<Long>) : LongEntity(id) {
|
||||
companion object : LongEntityClass<InitializationEntity>(InitializationTable)
|
||||
|
||||
var name by InitializationTable.name
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
package com.infendro.account.model.entity
|
||||
|
||||
import org.jetbrains.exposed.dao.LongEntity
|
||||
import org.jetbrains.exposed.dao.LongEntityClass
|
||||
import org.jetbrains.exposed.dao.id.EntityID
|
||||
import org.jetbrains.exposed.dao.id.LongIdTable
|
||||
import org.jetbrains.exposed.sql.transactions.transaction
|
||||
|
||||
object SessionTable : LongIdTable("session", "id") {
|
||||
val tokenHash = text("token_hash")
|
||||
val accountId = reference("account_id", AccountTable.id)
|
||||
}
|
||||
|
||||
class SessionEntity(id: EntityID<Long>) : LongEntity(id) {
|
||||
companion object : LongEntityClass<SessionEntity>(SessionTable)
|
||||
|
||||
var tokenHash by SessionTable.tokenHash
|
||||
var account by AccountEntity referencedOn SessionTable.accountId
|
||||
|
||||
fun account() = transaction { account }
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
package com.infendro.account.model.repository
|
||||
|
||||
import com.infendro.account.model.entity.AccessEntity
|
||||
|
||||
class AccessRepository : Repository<AccessEntity>(AccessEntity)
|
||||
@@ -0,0 +1,5 @@
|
||||
package com.infendro.account.model.repository
|
||||
|
||||
import com.infendro.account.model.entity.AccountEntity
|
||||
|
||||
class AccountRepository : Repository<AccountEntity>(AccountEntity)
|
||||
@@ -0,0 +1,5 @@
|
||||
package com.infendro.account.model.repository
|
||||
|
||||
import com.infendro.account.model.entity.InitializationEntity
|
||||
|
||||
class InitializationRepository : Repository<InitializationEntity>(InitializationEntity)
|
||||
@@ -0,0 +1,124 @@
|
||||
package com.infendro.account.model.repository
|
||||
|
||||
import org.jetbrains.exposed.dao.LongEntity
|
||||
import org.jetbrains.exposed.dao.LongEntityClass
|
||||
import org.jetbrains.exposed.sql.Op
|
||||
import org.jetbrains.exposed.sql.transactions.transaction
|
||||
|
||||
abstract class Repository<ENTITY : LongEntity>(
|
||||
private val entityClass: LongEntityClass<ENTITY>,
|
||||
) {
|
||||
fun all(): List<ENTITY> = transaction {
|
||||
entityClass.all().toList()
|
||||
}
|
||||
|
||||
fun all(
|
||||
where: Op<Boolean>,
|
||||
): List<ENTITY> = transaction {
|
||||
entityClass.find(where).toList()
|
||||
}
|
||||
|
||||
fun all(
|
||||
where: () -> Op<Boolean>,
|
||||
): List<ENTITY> {
|
||||
return all(where())
|
||||
}
|
||||
|
||||
fun single(
|
||||
where: Op<Boolean>,
|
||||
): ENTITY = transaction {
|
||||
entityClass.find(where).single()
|
||||
}
|
||||
|
||||
fun single(
|
||||
where: () -> Op<Boolean>,
|
||||
): ENTITY {
|
||||
return single(where())
|
||||
}
|
||||
|
||||
fun singleOrNull(
|
||||
where: Op<Boolean>,
|
||||
): ENTITY? = transaction {
|
||||
entityClass.find(where).singleOrNull()
|
||||
}
|
||||
|
||||
fun singleOrNull(
|
||||
where: () -> Op<Boolean>,
|
||||
): ENTITY? {
|
||||
return singleOrNull(where())
|
||||
}
|
||||
|
||||
fun exists(
|
||||
where: Op<Boolean>,
|
||||
): Boolean {
|
||||
return all(where).isNotEmpty()
|
||||
}
|
||||
|
||||
fun exists(
|
||||
where: () -> Op<Boolean>,
|
||||
): Boolean {
|
||||
return exists(where())
|
||||
}
|
||||
|
||||
fun insert(
|
||||
block: ENTITY.() -> Unit,
|
||||
): Unit = transaction {
|
||||
entityClass.new(block)
|
||||
}
|
||||
|
||||
fun update(
|
||||
entity: ENTITY,
|
||||
block: ENTITY.() -> Unit,
|
||||
): Unit = transaction {
|
||||
entity.block()
|
||||
}
|
||||
|
||||
fun update(
|
||||
entities: Iterable<ENTITY>,
|
||||
block: ENTITY.() -> Unit,
|
||||
) {
|
||||
for (entity in entities) {
|
||||
update(entity, block)
|
||||
}
|
||||
}
|
||||
|
||||
fun update(
|
||||
where: Op<Boolean>,
|
||||
block: ENTITY.() -> Unit,
|
||||
) {
|
||||
update(all(where), block)
|
||||
}
|
||||
|
||||
fun update(
|
||||
where: () -> Op<Boolean>,
|
||||
block: ENTITY.() -> Unit,
|
||||
) {
|
||||
update(where(), block)
|
||||
}
|
||||
|
||||
fun delete(
|
||||
entity: ENTITY,
|
||||
): Unit = transaction {
|
||||
entity.delete()
|
||||
}
|
||||
|
||||
fun delete(
|
||||
entities: Iterable<ENTITY>,
|
||||
) {
|
||||
for (entity in entities) {
|
||||
delete(entity)
|
||||
}
|
||||
}
|
||||
|
||||
fun delete(
|
||||
where: Op<Boolean>,
|
||||
) {
|
||||
delete(all(where))
|
||||
}
|
||||
|
||||
fun delete(
|
||||
where: () -> Op<Boolean>,
|
||||
) {
|
||||
delete(where())
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
package com.infendro.account.model.repository
|
||||
|
||||
import com.infendro.account.model.entity.SessionEntity
|
||||
|
||||
class SessionRepository : Repository<SessionEntity>(SessionEntity)
|
||||
@@ -0,0 +1,56 @@
|
||||
package com.infendro.account.routing
|
||||
|
||||
import com.infendro.account.config.AuthenticationPrincipal
|
||||
import com.infendro.account.service.AccessService
|
||||
import io.ktor.http.HttpStatusCode.Companion.OK
|
||||
import io.ktor.resources.Resource
|
||||
import io.ktor.server.auth.authenticate
|
||||
import io.ktor.server.auth.principal
|
||||
import io.ktor.server.resources.delete
|
||||
import io.ktor.server.resources.get
|
||||
import io.ktor.server.resources.post
|
||||
import io.ktor.server.response.respond
|
||||
import io.ktor.server.routing.Routing
|
||||
import org.koin.ktor.ext.inject
|
||||
|
||||
@Resource("/access")
|
||||
private class Access {
|
||||
@Resource("/all")
|
||||
class All(
|
||||
val parent: Access,
|
||||
)
|
||||
|
||||
@Resource("/{id}")
|
||||
class Id(
|
||||
val parent: Access,
|
||||
val id: Long,
|
||||
)
|
||||
}
|
||||
|
||||
fun Routing.access() {
|
||||
val accessService by inject<AccessService>()
|
||||
|
||||
authenticate {
|
||||
post<Access> {
|
||||
val principal = call.principal<AuthenticationPrincipal>()!!
|
||||
|
||||
accessService.post(principal)
|
||||
.also { call.respond(it) }
|
||||
}
|
||||
|
||||
get<Access.All> {
|
||||
val principal = call.principal<AuthenticationPrincipal>()!!
|
||||
|
||||
accessService.getAll(principal)
|
||||
.also { call.respond(it) }
|
||||
}
|
||||
|
||||
delete<Access.Id> { resource ->
|
||||
val principal = call.principal<AuthenticationPrincipal>()!!
|
||||
val id = resource.id
|
||||
|
||||
accessService.deleteId(principal, id)
|
||||
call.respond(OK)
|
||||
}
|
||||
}
|
||||
}
|
||||
153
backend/src/main/kotlin/com/infendro/account/routing/Account.kt
Normal file
153
backend/src/main/kotlin/com/infendro/account/routing/Account.kt
Normal file
@@ -0,0 +1,153 @@
|
||||
package com.infendro.account.routing
|
||||
|
||||
import com.infendro.account.config.AuthenticationPrincipal
|
||||
import com.infendro.account.dto.request.PostAccountRequest
|
||||
import com.infendro.account.dto.request.PutAccountCurrentPasswordRequest
|
||||
import com.infendro.account.dto.request.PutAccountCurrentUsernameRequest
|
||||
import com.infendro.account.dto.request.PutAccountIdRoleRequest
|
||||
import com.infendro.account.service.AccountService
|
||||
import io.ktor.http.HttpStatusCode.Companion.OK
|
||||
import io.ktor.resources.Resource
|
||||
import io.ktor.server.auth.authenticate
|
||||
import io.ktor.server.auth.principal
|
||||
import io.ktor.server.request.receive
|
||||
import io.ktor.server.resources.delete
|
||||
import io.ktor.server.resources.get
|
||||
import io.ktor.server.resources.post
|
||||
import io.ktor.server.resources.put
|
||||
import io.ktor.server.response.respond
|
||||
import io.ktor.server.routing.Routing
|
||||
import io.ktor.server.sessions.sessions
|
||||
import org.koin.ktor.ext.inject
|
||||
|
||||
@Resource("/account")
|
||||
private class Account {
|
||||
@Resource("/all")
|
||||
class All(
|
||||
val parent: Account,
|
||||
)
|
||||
|
||||
@Resource("/current")
|
||||
class Current(
|
||||
val parent: Account,
|
||||
) {
|
||||
@Resource("/username")
|
||||
class Username(
|
||||
val parent: Current,
|
||||
)
|
||||
|
||||
@Resource("/password")
|
||||
class Password(
|
||||
val parent: Current,
|
||||
)
|
||||
|
||||
@Resource("/session")
|
||||
class Session(
|
||||
val parent: Current,
|
||||
) {
|
||||
@Resource("/all")
|
||||
class All(
|
||||
val parent: Session,
|
||||
)
|
||||
|
||||
@Resource("/{id}")
|
||||
class Id(
|
||||
val parent: Session,
|
||||
val id: Long,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@Resource("/{id}")
|
||||
class Id(
|
||||
val parent: Account,
|
||||
val id: Long,
|
||||
) {
|
||||
@Resource("/role")
|
||||
class Role(
|
||||
val parent: Id,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
fun Routing.account() {
|
||||
val accountService by inject<AccountService>()
|
||||
|
||||
post<Account> {
|
||||
val request = call.receive<PostAccountRequest>()
|
||||
|
||||
accountService.post(request)
|
||||
.also { call.respond(it) }
|
||||
}
|
||||
|
||||
authenticate {
|
||||
get<Account.All> {
|
||||
val principal = call.principal<AuthenticationPrincipal>()!!
|
||||
|
||||
accountService.getAll(principal)
|
||||
.also { call.respond(it) }
|
||||
}
|
||||
|
||||
get<Account.Current> {
|
||||
val principal = call.principal<AuthenticationPrincipal>()!!
|
||||
|
||||
accountService.getCurrent(principal)
|
||||
.also { call.respond(it) }
|
||||
}
|
||||
|
||||
delete<Account.Current> {
|
||||
val principal = call.principal<AuthenticationPrincipal>()!!
|
||||
|
||||
accountService.deleteCurrent(principal)
|
||||
call.respond(OK)
|
||||
}
|
||||
|
||||
put<Account.Current.Username> {
|
||||
val principal = call.principal<AuthenticationPrincipal>()!!
|
||||
val request = call.receive<PutAccountCurrentUsernameRequest>()
|
||||
|
||||
accountService.putCurrentUsername(principal, call.sessions, request)
|
||||
call.respond(OK)
|
||||
}
|
||||
|
||||
put<Account.Current.Password> {
|
||||
val principal = call.principal<AuthenticationPrincipal>()!!
|
||||
val request = call.receive<PutAccountCurrentPasswordRequest>()
|
||||
|
||||
accountService.putCurrentPassword(principal, call.sessions, request)
|
||||
call.respond(OK)
|
||||
}
|
||||
|
||||
get<Account.Current.Session.All> {
|
||||
val principal = call.principal<AuthenticationPrincipal>()!!
|
||||
|
||||
accountService.getCurrentSessionAll(principal)
|
||||
.also { call.respond(it) }
|
||||
}
|
||||
|
||||
delete<Account.Current.Session.Id> { resource ->
|
||||
val principal = call.principal<AuthenticationPrincipal>()!!
|
||||
val id = resource.id
|
||||
|
||||
accountService.deleteCurrentSessionId(principal, call.sessions, id)
|
||||
call.respond(OK)
|
||||
}
|
||||
|
||||
delete<Account.Id> { resource ->
|
||||
val principal = call.principal<AuthenticationPrincipal>()!!
|
||||
val id = resource.id
|
||||
|
||||
accountService.deleteId(principal, id)
|
||||
call.respond(OK)
|
||||
}
|
||||
|
||||
put<Account.Id.Role> { resource ->
|
||||
val principal = call.principal<AuthenticationPrincipal>()!!
|
||||
val id = resource.parent.id
|
||||
val request = call.receive<PutAccountIdRoleRequest>()
|
||||
|
||||
accountService.putIdRole(principal, id, request)
|
||||
call.respond(OK)
|
||||
}
|
||||
}
|
||||
}
|
||||
25
backend/src/main/kotlin/com/infendro/account/routing/Role.kt
Normal file
25
backend/src/main/kotlin/com/infendro/account/routing/Role.kt
Normal file
@@ -0,0 +1,25 @@
|
||||
package com.infendro.account.routing
|
||||
|
||||
import com.infendro.account.service.RoleService
|
||||
import io.ktor.resources.Resource
|
||||
import io.ktor.server.resources.get
|
||||
import io.ktor.server.response.respond
|
||||
import io.ktor.server.routing.Routing
|
||||
import org.koin.ktor.ext.inject
|
||||
|
||||
@Resource("/role")
|
||||
private class Role {
|
||||
@Resource("/all")
|
||||
class All(
|
||||
val parent: Role,
|
||||
)
|
||||
}
|
||||
|
||||
fun Routing.role() {
|
||||
val roleService by inject<RoleService>()
|
||||
|
||||
get<Role.All> {
|
||||
roleService.getAll()
|
||||
.also { call.respond(it) }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,78 @@
|
||||
package com.infendro.account.routing
|
||||
|
||||
import com.infendro.account.config.AuthenticationPrincipal
|
||||
import com.infendro.account.dto.request.PostSessionRequest
|
||||
import com.infendro.account.service.SessionService
|
||||
import io.ktor.http.HttpStatusCode.Companion.OK
|
||||
import io.ktor.resources.Resource
|
||||
import io.ktor.server.auth.authenticate
|
||||
import io.ktor.server.auth.principal
|
||||
import io.ktor.server.request.receive
|
||||
import io.ktor.server.resources.delete
|
||||
import io.ktor.server.resources.get
|
||||
import io.ktor.server.resources.post
|
||||
import io.ktor.server.response.respond
|
||||
import io.ktor.server.routing.Routing
|
||||
import io.ktor.server.sessions.sessions
|
||||
import org.koin.ktor.ext.inject
|
||||
|
||||
@Resource("/session")
|
||||
private class Session {
|
||||
@Resource("/all")
|
||||
class All(
|
||||
val parent: Session,
|
||||
)
|
||||
|
||||
@Resource("/{id}")
|
||||
class Id(
|
||||
val parent: Session,
|
||||
val id: Long,
|
||||
)
|
||||
|
||||
@Resource("/current")
|
||||
class Current(
|
||||
val parent: Session,
|
||||
)
|
||||
}
|
||||
|
||||
fun Routing.session() {
|
||||
val sessionService by inject<SessionService>()
|
||||
|
||||
post<Session> {
|
||||
val request = call.receive<PostSessionRequest>()
|
||||
|
||||
sessionService.post(call.sessions, request)
|
||||
call.respond(OK)
|
||||
}
|
||||
|
||||
authenticate {
|
||||
get<Session.All> {
|
||||
val principal = call.principal<AuthenticationPrincipal>()!!
|
||||
|
||||
sessionService.getAll(principal)
|
||||
.also { call.respond(it) }
|
||||
}
|
||||
|
||||
delete<Session.Id> { resource ->
|
||||
val principal = call.principal<AuthenticationPrincipal>()!!
|
||||
val id = resource.id
|
||||
|
||||
sessionService.deleteId(principal, id)
|
||||
call.respond(OK)
|
||||
}
|
||||
|
||||
get<Session.Current> {
|
||||
val principal = call.principal<AuthenticationPrincipal>()!!
|
||||
|
||||
sessionService.getCurrent(principal)
|
||||
.also { call.respond(it) }
|
||||
}
|
||||
|
||||
delete<Session.Current> {
|
||||
val principal = call.principal<AuthenticationPrincipal>()!!
|
||||
|
||||
sessionService.deleteCurrent(principal, call.sessions)
|
||||
call.respond(OK)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
package com.infendro.account.service
|
||||
|
||||
import com.infendro.account.config.AuthenticationPrincipal
|
||||
import com.infendro.account.dto.response.AccessResponse
|
||||
import com.infendro.account.dto.response.PostAccessResponse
|
||||
import com.infendro.account.dto.response.toResponse
|
||||
import com.infendro.account.exception.client.ForbiddenException
|
||||
import com.infendro.account.exception.client.NotFoundException
|
||||
import com.infendro.account.model.Role.OWNER
|
||||
import com.infendro.account.model.entity.AccessTable
|
||||
import com.infendro.account.model.repository.AccessRepository
|
||||
import com.infendro.account.util.Hasher
|
||||
import com.infendro.account.util.TokenGenerator
|
||||
import org.jetbrains.exposed.sql.SqlExpressionBuilder.eq
|
||||
|
||||
class AccessService(
|
||||
private val accessRepository: AccessRepository,
|
||||
) {
|
||||
fun post(
|
||||
principal: AuthenticationPrincipal,
|
||||
): PostAccessResponse {
|
||||
if (principal.role != OWNER)
|
||||
throw ForbiddenException()
|
||||
|
||||
val token = TokenGenerator.generate()
|
||||
accessRepository.insert {
|
||||
this.tokenHash = Hasher.hash(token)
|
||||
}
|
||||
|
||||
return PostAccessResponse(
|
||||
token = token
|
||||
)
|
||||
}
|
||||
|
||||
fun getAll(
|
||||
principal: AuthenticationPrincipal,
|
||||
): List<AccessResponse> {
|
||||
if (principal.role != OWNER)
|
||||
throw ForbiddenException()
|
||||
|
||||
return accessRepository
|
||||
.all()
|
||||
.map { it.toResponse() }
|
||||
}
|
||||
|
||||
fun deleteId(
|
||||
principal: AuthenticationPrincipal,
|
||||
id: Long,
|
||||
) {
|
||||
if (principal.role != OWNER)
|
||||
throw ForbiddenException()
|
||||
|
||||
val access = accessRepository
|
||||
.singleOrNull { AccessTable.id eq id }
|
||||
?: throw NotFoundException()
|
||||
|
||||
accessRepository.delete(access)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,189 @@
|
||||
package com.infendro.account.service
|
||||
|
||||
import com.infendro.account.config.AuthenticationPrincipal
|
||||
import com.infendro.account.config.AuthenticationSession
|
||||
import com.infendro.account.dto.request.PostAccountRequest
|
||||
import com.infendro.account.dto.request.PutAccountCurrentPasswordRequest
|
||||
import com.infendro.account.dto.request.PutAccountCurrentUsernameRequest
|
||||
import com.infendro.account.dto.request.PutAccountIdRoleRequest
|
||||
import com.infendro.account.dto.response.AccountResponse
|
||||
import com.infendro.account.dto.response.PostAccountResponse
|
||||
import com.infendro.account.dto.response.SessionResponse
|
||||
import com.infendro.account.dto.response.toResponse
|
||||
import com.infendro.account.exception.client.ConflictException
|
||||
import com.infendro.account.exception.client.ForbiddenException
|
||||
import com.infendro.account.exception.client.NotFoundException
|
||||
import com.infendro.account.exception.client.UnauthorizedException
|
||||
import com.infendro.account.model.Role.OWNER
|
||||
import com.infendro.account.model.Role.USER
|
||||
import com.infendro.account.model.entity.AccessTable
|
||||
import com.infendro.account.model.entity.AccountEntity
|
||||
import com.infendro.account.model.entity.AccountTable
|
||||
import com.infendro.account.model.entity.SessionTable
|
||||
import com.infendro.account.model.repository.AccessRepository
|
||||
import com.infendro.account.model.repository.AccountRepository
|
||||
import com.infendro.account.model.repository.SessionRepository
|
||||
import com.infendro.account.util.Hasher
|
||||
import com.infendro.account.util.OTP
|
||||
import com.infendro.account.util.SecureHasher
|
||||
import io.ktor.server.sessions.CurrentSession
|
||||
import io.ktor.server.sessions.clear
|
||||
import org.jetbrains.exposed.sql.SqlExpressionBuilder.eq
|
||||
|
||||
class AccountService(
|
||||
private val accessRepository: AccessRepository,
|
||||
private val accountRepository: AccountRepository,
|
||||
private val sessionRepository: SessionRepository,
|
||||
) {
|
||||
fun post(
|
||||
request: PostAccountRequest,
|
||||
): PostAccountResponse {
|
||||
val access = accessRepository
|
||||
.singleOrNull { AccessTable.tokenHash eq Hasher.hash(request.access.token) }
|
||||
?: throw UnauthorizedException()
|
||||
|
||||
accountRepository
|
||||
.singleOrNull { AccountTable.username eq request.username }
|
||||
?.run { throw ConflictException() }
|
||||
|
||||
accessRepository.delete(access)
|
||||
|
||||
val secret = OTP.generateSecret()
|
||||
accountRepository.insert {
|
||||
val salt = SecureHasher.generateSalt()
|
||||
|
||||
this.username = request.username
|
||||
this.passwordHash = SecureHasher.hash(request.password, salt)
|
||||
this.passwordSalt = salt
|
||||
this.secret = secret
|
||||
this.role = USER
|
||||
}
|
||||
|
||||
return PostAccountResponse(
|
||||
secret = secret
|
||||
)
|
||||
}
|
||||
|
||||
fun getAll(
|
||||
principal: AuthenticationPrincipal,
|
||||
): List<AccountResponse> {
|
||||
if (principal.role != OWNER)
|
||||
throw ForbiddenException()
|
||||
|
||||
return accountRepository
|
||||
.all()
|
||||
.map(AccountEntity::toResponse)
|
||||
}
|
||||
|
||||
fun getCurrent(
|
||||
principal: AuthenticationPrincipal,
|
||||
): AccountResponse {
|
||||
val (account, _) = principal
|
||||
|
||||
return account.toResponse()
|
||||
}
|
||||
|
||||
fun deleteCurrent(
|
||||
principal: AuthenticationPrincipal,
|
||||
) {
|
||||
if (principal.role == OWNER)
|
||||
throw ForbiddenException()
|
||||
|
||||
accountRepository.delete(principal.account)
|
||||
}
|
||||
|
||||
fun putCurrentUsername(
|
||||
principal: AuthenticationPrincipal,
|
||||
sessions: CurrentSession,
|
||||
request: PutAccountCurrentUsernameRequest,
|
||||
) {
|
||||
if (!OTP.verify(principal.account.secret, request.otp))
|
||||
throw UnauthorizedException()
|
||||
|
||||
accountRepository.update(principal.account) {
|
||||
this.username = request.username
|
||||
}
|
||||
sessionRepository.delete(principal.account.sessions())
|
||||
|
||||
sessions.clear<AuthenticationSession>()
|
||||
|
||||
}
|
||||
|
||||
fun putCurrentPassword(
|
||||
principal: AuthenticationPrincipal,
|
||||
sessions: CurrentSession,
|
||||
request: PutAccountCurrentPasswordRequest,
|
||||
) {
|
||||
if (!OTP.verify(principal.account.secret, request.otp))
|
||||
throw UnauthorizedException()
|
||||
|
||||
accountRepository.update(principal.account) {
|
||||
val salt = SecureHasher.generateSalt()
|
||||
|
||||
this.passwordHash = SecureHasher.hash(request.password, salt)
|
||||
this.passwordSalt = salt
|
||||
}
|
||||
sessionRepository.delete(principal.account.sessions())
|
||||
|
||||
sessions.clear<AuthenticationSession>()
|
||||
}
|
||||
|
||||
fun getCurrentSessionAll(
|
||||
principal: AuthenticationPrincipal,
|
||||
): List<SessionResponse> {
|
||||
return principal.account.sessions()
|
||||
.map { it.toResponse() }
|
||||
}
|
||||
|
||||
fun deleteCurrentSessionId(
|
||||
principal: AuthenticationPrincipal,
|
||||
sessions: CurrentSession,
|
||||
id: Long,
|
||||
) {
|
||||
val session = sessionRepository
|
||||
.singleOrNull { SessionTable.id eq id }
|
||||
?: throw NotFoundException()
|
||||
|
||||
if (session.account().id != principal.account.id)
|
||||
throw ForbiddenException()
|
||||
|
||||
sessionRepository.delete(session)
|
||||
|
||||
if (session.id == principal.session.id)
|
||||
sessions.clear<AuthenticationSession>()
|
||||
}
|
||||
|
||||
fun deleteId(
|
||||
principal: AuthenticationPrincipal,
|
||||
id: Long,
|
||||
) {
|
||||
val account = accountRepository
|
||||
.singleOrNull { AccountTable.id eq id }
|
||||
?: throw NotFoundException()
|
||||
|
||||
if (!principal.role.hasChild(account.role))
|
||||
throw ForbiddenException()
|
||||
|
||||
accountRepository.delete(account)
|
||||
}
|
||||
|
||||
fun putIdRole(
|
||||
principal: AuthenticationPrincipal,
|
||||
id: Long,
|
||||
request: PutAccountIdRoleRequest,
|
||||
) {
|
||||
val account = accountRepository
|
||||
.singleOrNull { AccountTable.id eq id }
|
||||
?: throw NotFoundException()
|
||||
|
||||
if (!principal.role.hasChild(account.role))
|
||||
throw ForbiddenException()
|
||||
|
||||
if (!principal.role.hasChild(request.role))
|
||||
throw ForbiddenException()
|
||||
|
||||
accountRepository.update(account) {
|
||||
role = request.role
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
package com.infendro.account.service
|
||||
|
||||
import com.infendro.account.dto.response.RoleResponse
|
||||
import com.infendro.account.dto.response.toResponse
|
||||
import com.infendro.account.model.Role
|
||||
|
||||
class RoleService {
|
||||
fun getAll(): List<RoleResponse> {
|
||||
return Role.ALL
|
||||
.map { it.toResponse() }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,96 @@
|
||||
package com.infendro.account.service
|
||||
|
||||
import com.infendro.account.config.AuthenticationPrincipal
|
||||
import com.infendro.account.config.AuthenticationSession
|
||||
import com.infendro.account.dto.request.PostSessionRequest
|
||||
import com.infendro.account.dto.response.SessionResponse
|
||||
import com.infendro.account.dto.response.toResponse
|
||||
import com.infendro.account.exception.client.ForbiddenException
|
||||
import com.infendro.account.exception.client.NotFoundException
|
||||
import com.infendro.account.exception.client.UnauthorizedException
|
||||
import com.infendro.account.model.Role.USER
|
||||
import com.infendro.account.model.entity.AccountTable
|
||||
import com.infendro.account.model.entity.SessionTable
|
||||
import com.infendro.account.model.repository.AccountRepository
|
||||
import com.infendro.account.model.repository.SessionRepository
|
||||
import com.infendro.account.util.Hasher
|
||||
import com.infendro.account.util.OTP
|
||||
import com.infendro.account.util.SecureHasher
|
||||
import com.infendro.account.util.TokenGenerator
|
||||
import io.ktor.server.sessions.CurrentSession
|
||||
import io.ktor.server.sessions.clear
|
||||
import io.ktor.server.sessions.set
|
||||
import org.jetbrains.exposed.sql.SqlExpressionBuilder.eq
|
||||
import org.jetbrains.exposed.sql.SqlExpressionBuilder.inList
|
||||
|
||||
class SessionService(
|
||||
private val accountRepository: AccountRepository,
|
||||
private val sessionRepository: SessionRepository,
|
||||
) {
|
||||
fun post(
|
||||
sessions: CurrentSession,
|
||||
request: PostSessionRequest,
|
||||
) {
|
||||
val account = accountRepository
|
||||
.singleOrNull { AccountTable.username eq request.username }
|
||||
?: throw NotFoundException()
|
||||
|
||||
if (!OTP.verify(account.secret, request.otp))
|
||||
throw UnauthorizedException()
|
||||
|
||||
if (account.passwordHash != SecureHasher.hash(request.password, account.passwordSalt))
|
||||
throw UnauthorizedException()
|
||||
|
||||
val token = TokenGenerator.generate()
|
||||
sessionRepository.insert {
|
||||
this.tokenHash = Hasher.hash(token)
|
||||
this.account = account
|
||||
}
|
||||
|
||||
sessions.set(AuthenticationSession(token))
|
||||
}
|
||||
|
||||
fun getAll(
|
||||
principal: AuthenticationPrincipal,
|
||||
): List<SessionResponse> {
|
||||
if (principal.role == USER)
|
||||
throw ForbiddenException()
|
||||
|
||||
return accountRepository
|
||||
.all { AccountTable.role inList principal.role.children }
|
||||
.flatMap { it.sessions() }
|
||||
.map { it.toResponse() }
|
||||
}
|
||||
|
||||
fun deleteId(
|
||||
principal: AuthenticationPrincipal,
|
||||
id: Long,
|
||||
) {
|
||||
if (principal.role == USER)
|
||||
throw ForbiddenException()
|
||||
|
||||
val session = sessionRepository
|
||||
.singleOrNull { SessionTable.id eq id }
|
||||
?: throw NotFoundException()
|
||||
|
||||
if (session.account().role !in principal.role.children)
|
||||
throw ForbiddenException()
|
||||
|
||||
sessionRepository.delete(session)
|
||||
}
|
||||
|
||||
fun getCurrent(
|
||||
principal: AuthenticationPrincipal,
|
||||
): SessionResponse {
|
||||
return principal.session.toResponse()
|
||||
}
|
||||
|
||||
fun deleteCurrent(
|
||||
principal: AuthenticationPrincipal,
|
||||
sessions: CurrentSession,
|
||||
) {
|
||||
sessionRepository.delete(principal.session)
|
||||
|
||||
sessions.clear<AuthenticationSession>()
|
||||
}
|
||||
}
|
||||
13
backend/src/main/kotlin/com/infendro/account/util/Hasher.kt
Normal file
13
backend/src/main/kotlin/com/infendro/account/util/Hasher.kt
Normal file
@@ -0,0 +1,13 @@
|
||||
package com.infendro.account.util
|
||||
|
||||
import com.infendro.encoding.Hex
|
||||
import com.infendro.hash.SHA256
|
||||
|
||||
object Hasher {
|
||||
fun hash(
|
||||
value: String,
|
||||
): String {
|
||||
val bytes = SHA256.hash(value.toByteArray())
|
||||
return Hex.encode(bytes).toString()
|
||||
}
|
||||
}
|
||||
31
backend/src/main/kotlin/com/infendro/account/util/OTP.kt
Normal file
31
backend/src/main/kotlin/com/infendro/account/util/OTP.kt
Normal file
@@ -0,0 +1,31 @@
|
||||
package com.infendro.account.util
|
||||
|
||||
import com.infendro.encoding.Base32
|
||||
import com.infendro.hash.SHA256
|
||||
import com.infendro.otp.SecretGenerator
|
||||
import com.infendro.otp.TOTP
|
||||
import kotlin.time.Clock
|
||||
import kotlin.time.Duration.Companion.seconds
|
||||
import kotlin.time.ExperimentalTime
|
||||
|
||||
@OptIn(ExperimentalTime::class)
|
||||
object OTP {
|
||||
private val totp = TOTP(
|
||||
function = SHA256,
|
||||
length = 8,
|
||||
period = 30.seconds,
|
||||
)
|
||||
|
||||
fun verify(
|
||||
secret: String,
|
||||
otp: String,
|
||||
): Boolean {
|
||||
val bytes = Base32.decode(secret.toByteArray())
|
||||
return totp.verify(bytes, Clock.System.now(), otp)
|
||||
}
|
||||
|
||||
fun generateSecret(): String {
|
||||
val bytes = SecretGenerator.generate(totp.hotp.function)
|
||||
return Base32.encode(bytes).toString()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
package com.infendro.account.util
|
||||
|
||||
val REGEX_USERNAME = """^(?=.{1,32}$)[a-z0-9]+([\-._][a-z0-9]+)*$""".toRegex()
|
||||
val REGEX_PASSWORD = """^(?=.{8,}$)[a-zA-Z0-9!"#$%&'()*+,\-./:;<=>?@\[\\\]^_`{|}~]*$""".toRegex()
|
||||
@@ -0,0 +1,26 @@
|
||||
package com.infendro.account.util
|
||||
|
||||
import com.infendro.encoding.Hex
|
||||
import javax.crypto.SecretKeyFactory
|
||||
import javax.crypto.spec.PBEKeySpec
|
||||
import kotlin.random.Random
|
||||
|
||||
// TODO implement PBKDF2
|
||||
object SecureHasher {
|
||||
private val factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA256")
|
||||
private val random = Random.Default
|
||||
|
||||
fun hash(
|
||||
value: String,
|
||||
salt: String,
|
||||
): String {
|
||||
val spec = PBEKeySpec(value.toCharArray(), Hex.decode(salt.toByteArray()), 100_000, 256)
|
||||
return factory.generateSecret(spec).encoded
|
||||
.let { Hex.encode(it).toString() }
|
||||
}
|
||||
|
||||
fun generateSalt(): String {
|
||||
return ByteArray(16).also { random.nextBytes(it) }
|
||||
.let { Hex.encode(it).toString() }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
package com.infendro.account.util
|
||||
|
||||
import com.infendro.encoding.Hex
|
||||
import kotlin.random.Random
|
||||
|
||||
// TODO implement secure random
|
||||
object TokenGenerator {
|
||||
private val random = Random.Default
|
||||
|
||||
fun generate(): String {
|
||||
val bytes = ByteArray(32)
|
||||
.also { random.nextBytes(it) }
|
||||
return Hex.encode(bytes).toString()
|
||||
}
|
||||
}
|
||||
20
backend/src/main/resources/application.conf
Normal file
20
backend/src/main/resources/application.conf
Normal file
@@ -0,0 +1,20 @@
|
||||
ktor {
|
||||
deployment {
|
||||
port = 8080
|
||||
}
|
||||
application {
|
||||
modules = [com.infendro.account.ApplicationKt.module]
|
||||
}
|
||||
}
|
||||
database {
|
||||
host = ${DATABASE_HOST}
|
||||
username = ${DATABASE_USERNAME}
|
||||
password = ${DATABASE_PASSWORD}
|
||||
}
|
||||
security {
|
||||
cookie {
|
||||
domain = ${COOKIE_DOMAIN}
|
||||
path = ${COOKIE_PATH}
|
||||
secure = ${COOKIE_SECURE}
|
||||
}
|
||||
}
|
||||
44
backend/src/main/resources/db/migration/V1__Initial.sql
Normal file
44
backend/src/main/resources/db/migration/V1__Initial.sql
Normal file
@@ -0,0 +1,44 @@
|
||||
CREATE TABLE initialization
|
||||
(
|
||||
id BIGSERIAL
|
||||
PRIMARY KEY,
|
||||
name TEXT
|
||||
UNIQUE
|
||||
NOT NULL
|
||||
);
|
||||
|
||||
CREATE TABLE access
|
||||
(
|
||||
id BIGSERIAL
|
||||
PRIMARY KEY,
|
||||
token_hash TEXT
|
||||
NOT NULL
|
||||
);
|
||||
|
||||
CREATE TABLE account
|
||||
(
|
||||
id BIGSERIAL
|
||||
PRIMARY KEY,
|
||||
username TEXT
|
||||
UNIQUE
|
||||
NOT NULL,
|
||||
password_hash TEXT
|
||||
NOT NULL,
|
||||
password_salt TEXT
|
||||
NOT NULL,
|
||||
secret TEXT
|
||||
NOT NULL,
|
||||
role TEXT
|
||||
NOT NULL
|
||||
);
|
||||
|
||||
CREATE TABLE session
|
||||
(
|
||||
id BIGSERIAL
|
||||
PRIMARY KEY,
|
||||
token_hash TEXT
|
||||
NOT NULL,
|
||||
account_id BIGINT
|
||||
REFERENCES account (id) ON DELETE CASCADE
|
||||
NOT NULL
|
||||
);
|
||||
10
backend/src/main/resources/logback.xml
Normal file
10
backend/src/main/resources/logback.xml
Normal file
@@ -0,0 +1,10 @@
|
||||
<configuration>
|
||||
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
|
||||
<encoder>
|
||||
<pattern>%date{YYYY-MM-dd HH:mm:ss.SSS} %highlight(%level) %logger{0} - %message%n</pattern>
|
||||
</encoder>
|
||||
</appender>
|
||||
<root level="INFO">
|
||||
<appender-ref ref="STDOUT"/>
|
||||
</root>
|
||||
</configuration>
|
||||
Reference in New Issue
Block a user