Compare commits
19 Commits
sql
...
90f1a3ce08
| Author | SHA1 | Date | |
|---|---|---|---|
| 90f1a3ce08 | |||
| f1b3fb34bd | |||
| 5d8bfa236d | |||
| a0024def2e | |||
| d2458633db | |||
| 5b9d2366db | |||
| a30eb52f3f | |||
| 175c86d787 | |||
| 3541528e77 | |||
| 62fe88abdf | |||
| 61bfdf273a | |||
| 4a17b4f528 | |||
| 50607a8c42 | |||
| 3bb8c33094 | |||
| 1bc5932793 | |||
| 8d1b0f2a3c | |||
| 224fe18639 | |||
| d32062a485 | |||
| 0b54384258 |
33
Dockerfile
33
Dockerfile
@@ -1,31 +1,20 @@
|
||||
# ---------- build stage ----------
|
||||
FROM gradle:jdk17-ubi AS build
|
||||
WORKDIR /app
|
||||
COPY gradlew gradlew
|
||||
COPY gradle gradle
|
||||
COPY build.gradle.kts settings.gradle.kts ./
|
||||
COPY src src
|
||||
RUN ./gradlew --no-daemon dependencies
|
||||
RUN ./gradlew --no-daemon clean bootJar
|
||||
|
||||
# ---------- run stage ----------
|
||||
FROM eclipse-temurin:17.0.16_8-jre AS runtime
|
||||
FROM eclipse-temurin:17-jre AS runtime
|
||||
WORKDIR /app
|
||||
|
||||
# Create non-root user with a higher UID/GID to avoid conflicts
|
||||
RUN groupadd --system --gid 1001 app && \
|
||||
useradd --system --gid app --uid 1001 --shell /bin/bash --create-home app
|
||||
|
||||
# Создаём директорию и меняем владельца ДО переключения пользователя
|
||||
# (Опционально) установить curl для healthcheck
|
||||
USER root
|
||||
RUN apt-get update && apt-get install -y --no-install-recommends curl && rm -rf /var/lib/apt/lists/*
|
||||
RUN groupadd --system --gid 1001 app && useradd --system --gid app --uid 1001 --shell /bin/bash --create-home app
|
||||
RUN mkdir -p /app/static && chown -R app:app /app
|
||||
|
||||
USER app
|
||||
|
||||
COPY --from=build /app/build/libs/*.jar /app/app.jar
|
||||
# ❗ копируем jar, собранный локально
|
||||
COPY build/libs/*.jar /app/app.jar
|
||||
|
||||
# Настройки JVM (Java 17)
|
||||
ENV JAVA_TOOL_OPTIONS="-XX:+UseContainerSupport -XX:MaxRAMPercentage=75.0"
|
||||
|
||||
EXPOSE 8080
|
||||
HEALTHCHECK --interval=20s --timeout=3s --retries=3 CMD wget -qO- http://localhost:8080/actuator/health || exit 1
|
||||
ENTRYPOINT ["java","-jar","/app/app.jar"]
|
||||
|
||||
HEALTHCHECK --interval=20s --timeout=3s --retries=3 CMD curl -fsS http://localhost:8080/actuator/health || exit 1
|
||||
|
||||
ENTRYPOINT ["java", "-jar", "/app/app.jar"]
|
||||
BIN
build/libs/luminic-space-v2.jar
Normal file
BIN
build/libs/luminic-space-v2.jar
Normal file
Binary file not shown.
19
docker-compose.yml
Normal file
19
docker-compose.yml
Normal file
@@ -0,0 +1,19 @@
|
||||
networks:
|
||||
postgres-net:
|
||||
external: true
|
||||
|
||||
services:
|
||||
app:
|
||||
build:
|
||||
context: .
|
||||
dockerfile: Dockerfile
|
||||
environment:
|
||||
SPRING_DATASOURCE_URL: jdbc:postgresql://postgres:5432/luminic-space-db
|
||||
SPRING_DATASOURCE_USERNAME: luminicspace
|
||||
SPRING_DATASOURCE_PASSWORD: LS1q2w3e4r!
|
||||
MANAGEMENT_ENDPOINTS_WEB_EXPOSURE_INCLUDE: health,info
|
||||
ports:
|
||||
- "8089:8089"
|
||||
restart: unless-stopped
|
||||
networks:
|
||||
- postgres-net
|
||||
1
gradle.properties
Normal file
1
gradle.properties
Normal file
@@ -0,0 +1 @@
|
||||
kotlin.code.style=official
|
||||
BIN
gradle/wrapper/gradle-wrapper.jar
vendored
Normal file
BIN
gradle/wrapper/gradle-wrapper.jar
vendored
Normal file
Binary file not shown.
6
gradle/wrapper/gradle-wrapper.properties
vendored
Normal file
6
gradle/wrapper/gradle-wrapper.properties
vendored
Normal file
@@ -0,0 +1,6 @@
|
||||
#Wed Oct 08 22:52:02 GET 2025
|
||||
distributionBase=GRADLE_USER_HOME
|
||||
distributionPath=wrapper/dists
|
||||
distributionUrl=https\://services.gradle.org/distributions/gradle-8.14-bin.zip
|
||||
zipStoreBase=GRADLE_USER_HOME
|
||||
zipStorePath=wrapper/dists
|
||||
234
gradlew
vendored
Executable file
234
gradlew
vendored
Executable file
@@ -0,0 +1,234 @@
|
||||
#!/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/master/subprojects/plugins/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
|
||||
|
||||
APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit
|
||||
|
||||
APP_NAME="Gradle"
|
||||
APP_BASE_NAME=${0##*/}
|
||||
|
||||
# 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"'
|
||||
|
||||
# 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
|
||||
which java >/dev/null 2>&1 || 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
|
||||
|
||||
# Increase the maximum file descriptors if we can.
|
||||
if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
|
||||
case $MAX_FD in #(
|
||||
max*)
|
||||
MAX_FD=$( ulimit -H -n ) ||
|
||||
warn "Could not query maximum file descriptor limit"
|
||||
esac
|
||||
case $MAX_FD in #(
|
||||
'' | soft) :;; #(
|
||||
*)
|
||||
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
|
||||
|
||||
# Collect all arguments for the java command;
|
||||
# * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of
|
||||
# shell script including quotes and variable substitutions, so put them in
|
||||
# double quotes to make sure that they get re-expanded; and
|
||||
# * put everything else in single quotes, so that it's not re-expanded.
|
||||
|
||||
set -- \
|
||||
"-Dorg.gradle.appname=$APP_BASE_NAME" \
|
||||
-classpath "$CLASSPATH" \
|
||||
org.gradle.wrapper.GradleWrapperMain \
|
||||
"$@"
|
||||
|
||||
# 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" "$@"
|
||||
89
gradlew.bat
vendored
Normal file
89
gradlew.bat
vendored
Normal file
@@ -0,0 +1,89 @@
|
||||
@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=.
|
||||
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%" == "0" goto execute
|
||||
|
||||
echo.
|
||||
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
|
||||
echo.
|
||||
echo Please set the JAVA_HOME variable in your environment to match the
|
||||
echo location of your Java installation.
|
||||
|
||||
goto fail
|
||||
|
||||
:findJavaFromJavaHome
|
||||
set JAVA_HOME=%JAVA_HOME:"=%
|
||||
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
|
||||
|
||||
if exist "%JAVA_EXE%" goto execute
|
||||
|
||||
echo.
|
||||
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
|
||||
echo.
|
||||
echo Please set the JAVA_HOME variable in your environment to match the
|
||||
echo location of your Java installation.
|
||||
|
||||
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%"=="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!
|
||||
if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
|
||||
exit /b 1
|
||||
|
||||
:mainEnd
|
||||
if "%OS%"=="Windows_NT" endlocal
|
||||
|
||||
:omega
|
||||
4
settings.gradle.kts
Normal file
4
settings.gradle.kts
Normal file
@@ -0,0 +1,4 @@
|
||||
plugins {
|
||||
id("org.gradle.toolchains.foojay-resolver-convention") version "0.8.0"
|
||||
}
|
||||
rootProject.name = "luminic-space"
|
||||
@@ -1,23 +1,67 @@
|
||||
package space.luminic.finance.api
|
||||
|
||||
|
||||
import org.apache.commons.codec.digest.DigestUtils.sha256
|
||||
import org.apache.commons.codec.digest.HmacUtils.hmacSha256
|
||||
import org.slf4j.LoggerFactory
|
||||
import org.springframework.beans.factory.annotation.Value
|
||||
import org.springframework.security.core.context.SecurityContextHolder
|
||||
import org.springframework.web.bind.annotation.*
|
||||
import space.luminic.finance.dtos.UserDTO
|
||||
import space.luminic.finance.dtos.UserDTO.AuthUserDTO
|
||||
import space.luminic.finance.dtos.UserDTO.RegisterUserDTO
|
||||
import space.luminic.finance.mappers.UserMapper.toDto
|
||||
import space.luminic.finance.mappers.UserMapper.toTelegramMap
|
||||
import space.luminic.finance.services.AuthService
|
||||
import java.security.MessageDigest
|
||||
import java.time.Instant
|
||||
import javax.crypto.Mac
|
||||
import javax.crypto.spec.SecretKeySpec
|
||||
|
||||
@RestController
|
||||
@RequestMapping("/auth")
|
||||
class AuthController(
|
||||
private val authService: AuthService
|
||||
private val authService: AuthService,
|
||||
@Value("\${telegram.bot.token}") private val botToken: String
|
||||
) {
|
||||
|
||||
private val logger = LoggerFactory.getLogger(javaClass)
|
||||
|
||||
fun verifyTelegramAuth(data: Map<String, String>, botToken: String): Boolean {
|
||||
val hash = data["hash"] ?: return false
|
||||
|
||||
val dataCheckString = data
|
||||
.filterKeys { it != "hash" }
|
||||
.toSortedMap()
|
||||
.map { "${it.key}=${it.value}" }
|
||||
.joinToString("\n")
|
||||
|
||||
val secretKey = sha256(botToken)
|
||||
val hmacHex = hmacSha256(secretKey, dataCheckString)
|
||||
|
||||
if (hmacHex != hash) return false
|
||||
|
||||
val authDate = data["auth_date"]?.toLongOrNull() ?: return false
|
||||
val now = Instant.now().epochSecond
|
||||
|
||||
// Опционально — запрет старых ответов (например, старше 1 часа)
|
||||
val maxAgeSeconds = 3600
|
||||
if (now - authDate > maxAgeSeconds) return false
|
||||
|
||||
return true
|
||||
}
|
||||
|
||||
private fun sha256(input: String): ByteArray =
|
||||
MessageDigest.getInstance("SHA-256").digest(input.toByteArray())
|
||||
|
||||
private fun hmacSha256(secret: ByteArray, message: String): String {
|
||||
val key = SecretKeySpec(secret, "HmacSHA256")
|
||||
val mac = Mac.getInstance("HmacSHA256")
|
||||
mac.init(key)
|
||||
val hashBytes = mac.doFinal(message.toByteArray())
|
||||
return hashBytes.joinToString("") { "%02x".format(it) }
|
||||
}
|
||||
|
||||
@GetMapping("/test")
|
||||
fun test(): String {
|
||||
val authentication = SecurityContextHolder.getContext().authentication
|
||||
@@ -36,13 +80,16 @@ class AuthController(
|
||||
return authService.register(request.username, request.password, request.firstName).toDto()
|
||||
}
|
||||
|
||||
@PostMapping("/tgLogin")
|
||||
fun tgLogin(@RequestHeader("X-Tg-Id") tgId: String): Map<String, String> {
|
||||
val token = authService.tgLogin(tgId)
|
||||
return mapOf("token" to token)
|
||||
@PostMapping("/tg-login")
|
||||
fun tgLogin(@RequestBody tgUser: UserDTO.TelegramAuthDTO): String {
|
||||
val ok = verifyTelegramAuth(tgUser.toTelegramMap(), botToken)
|
||||
if (!ok) throw IllegalArgumentException("Invalid Telegram login")
|
||||
return authService.tgAuth(tgUser)
|
||||
|
||||
}
|
||||
|
||||
|
||||
|
||||
@GetMapping("/me")
|
||||
fun getMe(): UserDTO {
|
||||
logger.info("Get Me")
|
||||
|
||||
@@ -21,7 +21,7 @@ class BearerTokenFilter(
|
||||
private val publicMatchers = listOf(
|
||||
AntPathRequestMatcher("/auth/login", "POST"),
|
||||
AntPathRequestMatcher("/auth/register", "POST"),
|
||||
AntPathRequestMatcher("/auth/tgLogin", "POST"),
|
||||
AntPathRequestMatcher("/auth/tg-login", "POST"),
|
||||
AntPathRequestMatcher("/actuator/**"),
|
||||
AntPathRequestMatcher("/static/**"),
|
||||
AntPathRequestMatcher("/wishlistexternal/**"),
|
||||
|
||||
@@ -31,7 +31,7 @@ class SecurityConfig(
|
||||
.logout { it.disable() }
|
||||
|
||||
.authorizeHttpRequests {
|
||||
it.requestMatchers(HttpMethod.POST, "/auth/login", "/auth/register", "/auth/tgLogin").permitAll()
|
||||
it.requestMatchers(HttpMethod.POST, "/auth/login", "/auth/register", "/auth/tg-login").permitAll()
|
||||
it.requestMatchers("/actuator/**", "/static/**").permitAll()
|
||||
it.requestMatchers("/wishlistexternal/**").permitAll()
|
||||
it.requestMatchers("/swagger-ui/**", "/swagger-ui.html", "/v3/api-docs/**").permitAll()
|
||||
|
||||
@@ -1,11 +1,14 @@
|
||||
package space.luminic.finance.dtos
|
||||
|
||||
import java.util.Date
|
||||
|
||||
data class UserDTO (
|
||||
var id: Int,
|
||||
val username: String,
|
||||
var firstName: String,
|
||||
var tgId: String? = null,
|
||||
var tgId: Long? = null,
|
||||
var tgUserName: String? = null,
|
||||
var photoUrl: String? = null,
|
||||
var roles: List<String>
|
||||
|
||||
) {
|
||||
@@ -22,6 +25,17 @@ data class UserDTO (
|
||||
|
||||
)
|
||||
|
||||
data class TelegramAuthDTO(
|
||||
val id: Long,
|
||||
val first_name: String?,
|
||||
val last_name: String?,
|
||||
val username: String?,
|
||||
val photo_url: String?,
|
||||
val auth_date: Long,
|
||||
val hash: String
|
||||
)
|
||||
|
||||
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
package space.luminic.finance.mappers
|
||||
|
||||
import space.luminic.finance.dtos.UserDTO
|
||||
import space.luminic.finance.dtos.UserDTO.TelegramAuthDTO
|
||||
import space.luminic.finance.models.User
|
||||
|
||||
object UserMapper {
|
||||
@@ -11,7 +12,18 @@ object UserMapper {
|
||||
firstName = this.firstName,
|
||||
tgId = this.tgId,
|
||||
tgUserName = this.tgUserName,
|
||||
photoUrl = this.photoUrl,
|
||||
roles = this.roles
|
||||
)
|
||||
|
||||
fun TelegramAuthDTO.toTelegramMap(): Map<String, String> =
|
||||
mapOf(
|
||||
"id" to id.toString(),
|
||||
"first_name" to (first_name ?: ""),
|
||||
"last_name" to (last_name ?: ""),
|
||||
"username" to (username ?: ""),
|
||||
"photo_url" to (photo_url ?: ""),
|
||||
"auth_date" to auth_date.toString(),
|
||||
"hash" to hash
|
||||
)
|
||||
}
|
||||
@@ -11,8 +11,9 @@ data class User(
|
||||
var id: Int? = null,
|
||||
val username: String,
|
||||
var firstName: String,
|
||||
var tgId: String? = null,
|
||||
var tgId: Long? = null,
|
||||
var tgUserName: String? = null,
|
||||
val photoUrl: String? = null,
|
||||
var password: String? = null,
|
||||
var isActive: Boolean = true,
|
||||
var regDate: LocalDate = LocalDate.now(),
|
||||
|
||||
@@ -9,8 +9,8 @@ interface UserRepo {
|
||||
fun findById(id: Int): User?
|
||||
fun findByUsername(username: String): User?
|
||||
fun findParticipantsBySpace(spaceId: Int): Set<User>
|
||||
fun findByTgId(tgId: String): User?
|
||||
fun save(user: User): User
|
||||
fun findByTgId(tgId: Long): User?
|
||||
fun create(user: User): User
|
||||
fun update(user: User): User
|
||||
fun deleteById(id: Long)
|
||||
}
|
||||
@@ -4,18 +4,20 @@ import org.springframework.jdbc.core.RowMapper
|
||||
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate
|
||||
import org.springframework.stereotype.Repository
|
||||
import space.luminic.finance.models.User
|
||||
|
||||
@Repository
|
||||
class UserRepoImpl(
|
||||
private val jdbcTemplate: NamedParameterJdbcTemplate
|
||||
) : UserRepo{
|
||||
) : UserRepo {
|
||||
|
||||
private fun userRowMapper() = RowMapper { rs, _ ->
|
||||
User(
|
||||
id = rs.getInt("id"),
|
||||
username = rs.getString("username"),
|
||||
firstName = rs.getString("first_name"),
|
||||
tgId = rs.getString("tg_id"),
|
||||
tgId = rs.getLong("tg_id"),
|
||||
tgUserName = rs.getString("tg_user_name"),
|
||||
photoUrl = rs.getString("photo_url"),
|
||||
password = rs.getString("password"),
|
||||
isActive = rs.getBoolean("is_active"),
|
||||
regDate = rs.getDate("reg_date").toLocalDate(),
|
||||
@@ -41,11 +43,12 @@ class UserRepoImpl(
|
||||
}
|
||||
|
||||
override fun findParticipantsBySpace(spaceId: Int): Set<User> {
|
||||
val sql = "select * from finance.users u join finance.spaces_participants sp on sp.participants_id = u.id where sp.space_id = :spaceId"
|
||||
val sql =
|
||||
"select * from finance.users u join finance.spaces_participants sp on sp.participants_id = u.id where sp.space_id = :spaceId"
|
||||
return jdbcTemplate.query(sql, mapOf("spaceId" to spaceId), userRowMapper()).toSet()
|
||||
}
|
||||
|
||||
override fun findByTgId(tgId: String): User? {
|
||||
override fun findByTgId(tgId: Long): User? {
|
||||
val sql = """
|
||||
select * from finance.users u where tg_id = :tgId
|
||||
""".trimIndent()
|
||||
@@ -53,13 +56,15 @@ class UserRepoImpl(
|
||||
return jdbcTemplate.queryForObject(sql, params, userRowMapper())
|
||||
}
|
||||
|
||||
override fun save(user: User): User {
|
||||
val sql = "insert into finance.users(username, first_name, tg_id, tg_user_name, password, is_active, reg_date) values (:username, :firstname, :tg_id, :tg_user_name, :password, :isActive, :regDate) returning ID"
|
||||
override fun create(user: User): User {
|
||||
val sql =
|
||||
"insert into finance.users(username, first_name, tg_id, tg_user_name, photo_url, password, is_active, reg_date) values (:username, :firstname, :tg_id, :tg_user_name, :photo_url :password, :isActive, :regDate) returning ID"
|
||||
val params = mapOf(
|
||||
"username" to user.username,
|
||||
"firstname" to user.firstName,
|
||||
"tg_id" to user.tgId,
|
||||
"tg_user_name" to user.tgUserName,
|
||||
"photo_url" to user.photoUrl,
|
||||
"password" to user.password,
|
||||
"isActive" to user.isActive,
|
||||
"regDate" to user.regDate,
|
||||
|
||||
@@ -6,6 +6,8 @@ import org.springframework.security.core.userdetails.UsernameNotFoundException
|
||||
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder
|
||||
import org.springframework.stereotype.Service
|
||||
import space.luminic.finance.configs.AuthException
|
||||
import space.luminic.finance.dtos.UserDTO
|
||||
import space.luminic.finance.models.NotFoundException
|
||||
import space.luminic.finance.models.Token
|
||||
import space.luminic.finance.models.User
|
||||
import space.luminic.finance.repos.UserRepo
|
||||
@@ -61,10 +63,12 @@ class AuthService(
|
||||
}
|
||||
}
|
||||
|
||||
fun tgLogin(tgId: String): String {
|
||||
val user =
|
||||
userRepo.findByTgId(tgId) ?: throw UsernameNotFoundException("Пользователь не найден")
|
||||
|
||||
fun tgAuth(tgUser: UserDTO.TelegramAuthDTO): String {
|
||||
val user: User = try {
|
||||
tgLogin(tgUser.id)
|
||||
} catch (e: NotFoundException) {
|
||||
registerTg(tgUser)
|
||||
}
|
||||
val token = jwtUtil.generateToken(user.username)
|
||||
val expireAt = Date(System.currentTimeMillis() + 1000 * 60 * 60 * 24 * 10)
|
||||
tokenService.saveToken(
|
||||
@@ -73,7 +77,22 @@ class AuthService(
|
||||
expiresAt = expireAt.toInstant()
|
||||
)
|
||||
return token
|
||||
}
|
||||
|
||||
fun registerTg(tgUser: UserDTO.TelegramAuthDTO): User {
|
||||
val user = User(
|
||||
username = tgUser.username ?: UUID.randomUUID().toString().split('-')[0],
|
||||
firstName = tgUser.first_name ?: UUID.randomUUID().toString().split('-')[0],
|
||||
tgId = tgUser.id,
|
||||
tgUserName = tgUser.username,
|
||||
photoUrl = tgUser.photo_url,
|
||||
roles = mutableListOf("USER")
|
||||
)
|
||||
return userRepo.create(user)
|
||||
}
|
||||
|
||||
fun tgLogin(tgId: Long): User {
|
||||
return userRepo.findByTgId(tgId) ?: throw NotFoundException("User with provided TG id $tgId not found")
|
||||
}
|
||||
|
||||
fun register(username: String, password: String, firstName: String): User {
|
||||
@@ -85,7 +104,7 @@ class AuthService(
|
||||
firstName = firstName,
|
||||
roles = mutableListOf("USER")
|
||||
)
|
||||
newUser = userRepo.save(newUser)
|
||||
newUser = userRepo.create(newUser)
|
||||
return newUser
|
||||
} else throw IllegalArgumentException("Пользователь уже зарегистрирован")
|
||||
}
|
||||
|
||||
@@ -24,7 +24,7 @@ class UserService(val userRepo: UserRepo) {
|
||||
}
|
||||
|
||||
fun getUserByTelegramId(telegramId: Long): User {
|
||||
return userRepo.findByTgId(telegramId.toString())?: throw NotFoundException("User with telegramId: $telegramId not found")
|
||||
return userRepo.findByTgId(telegramId)?: throw NotFoundException("User with telegramId: $telegramId not found")
|
||||
|
||||
}
|
||||
|
||||
|
||||
@@ -1,10 +1,6 @@
|
||||
spring.application.name=budger-app
|
||||
|
||||
|
||||
|
||||
spring.data.mongodb.uri=mongodb://budger-app:BA1q2w3e4r!@luminic.space:27017/budger-app-v2?authSource=admin&minPoolSize=10&maxPoolSize=100
|
||||
|
||||
|
||||
logging.level.org.springframework.web=INFO
|
||||
logging.level.org.springframework.data = INFO
|
||||
logging.level.org.springframework.data.mongodb.core.ReactiveMongoTemplate=INFO
|
||||
@@ -17,11 +13,11 @@ logging.level.org.mongodb.driver.protocol.command = INFO
|
||||
#management.endpoint.metrics.access=read_only
|
||||
|
||||
|
||||
telegram.bot.token = 6662300972:AAFXjk_h0AUCy4bORC12UcdXbYnh2QSVKAY
|
||||
telegram.bot.token = 7999296388:AAGXPE5r0yt3ZFehBoUh8FGm5FBbs9pYIks
|
||||
nlp.address=https://nlp.luminic.space
|
||||
|
||||
|
||||
|
||||
spring.datasource.url=jdbc:postgresql://213.226.71.138:5432/luminic-space-db
|
||||
spring.datasource.url=jdbc:postgresql://postgresql:5432/luminic-space-db
|
||||
spring.datasource.username=luminicspace
|
||||
spring.datasource.password=LS1q2w3e4r!
|
||||
@@ -1,6 +1,6 @@
|
||||
spring.application.name=budger-app
|
||||
|
||||
server.port=8082
|
||||
server.port=8089
|
||||
server.servlet.context-path=/api
|
||||
#spring.webflux.base-path=/api
|
||||
|
||||
|
||||
3
src/main/resources/db/migration/V22__.sql
Normal file
3
src/main/resources/db/migration/V22__.sql
Normal file
@@ -0,0 +1,3 @@
|
||||
alter table finance.users
|
||||
add column photo_url varchar null,
|
||||
alter column tg_id set data type bigint USING tg_id::bigint;;
|
||||
Reference in New Issue
Block a user