19 Commits

Author SHA1 Message Date
xds
90f1a3ce08 build 2025-10-31 17:38:48 +03:00
xds
f1b3fb34bd build 2025-10-31 17:33:49 +03:00
xds
5d8bfa236d build 2025-10-31 17:24:29 +03:00
xds
a0024def2e tg login 2025-10-31 17:13:10 +03:00
xds
d2458633db tg login 2025-10-31 17:11:40 +03:00
xds
5b9d2366db init 2025-10-31 16:26:24 +03:00
xds
a30eb52f3f init 2025-10-31 16:16:36 +03:00
xds
175c86d787 init 2025-10-31 16:14:56 +03:00
xds
3541528e77 init 2025-10-31 16:12:01 +03:00
xds
62fe88abdf init 2025-10-31 16:10:59 +03:00
xds
61bfdf273a init 2025-10-31 16:10:30 +03:00
xds
4a17b4f528 init 2025-10-31 16:09:31 +03:00
xds
50607a8c42 init 2025-10-31 15:53:26 +03:00
xds
3bb8c33094 init 2025-10-31 15:50:56 +03:00
xds
1bc5932793 init 2025-10-31 15:48:55 +03:00
xds
8d1b0f2a3c init 2025-10-31 15:46:49 +03:00
xds
224fe18639 init 2025-10-31 15:40:45 +03:00
xds
d32062a485 init 2025-10-31 15:40:10 +03:00
0b54384258 Merge pull request 'init' (#1) from sql into main
Reviewed-on: #1
2025-10-31 15:38:34 +03:00
22 changed files with 495 additions and 56 deletions

View File

@@ -1,31 +1,20 @@
# ---------- build stage ---------- FROM eclipse-temurin:17-jre AS runtime
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
WORKDIR /app WORKDIR /app
# Create non-root user with a higher UID/GID to avoid conflicts # (Опционально) установить curl для healthcheck
RUN groupadd --system --gid 1001 app && \ USER root
useradd --system --gid app --uid 1001 --shell /bin/bash --create-home app 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 RUN mkdir -p /app/static && chown -R app:app /app
USER 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" ENV JAVA_TOOL_OPTIONS="-XX:+UseContainerSupport -XX:MaxRAMPercentage=75.0"
EXPOSE 8080 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"]

Binary file not shown.

19
docker-compose.yml Normal file
View 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
View File

@@ -0,0 +1 @@
kotlin.code.style=official

BIN
gradle/wrapper/gradle-wrapper.jar vendored Normal file

Binary file not shown.

View 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
View 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
View 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
View File

@@ -0,0 +1,4 @@
plugins {
id("org.gradle.toolchains.foojay-resolver-convention") version "0.8.0"
}
rootProject.name = "luminic-space"

View File

@@ -1,23 +1,67 @@
package space.luminic.finance.api 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.slf4j.LoggerFactory
import org.springframework.beans.factory.annotation.Value
import org.springframework.security.core.context.SecurityContextHolder import org.springframework.security.core.context.SecurityContextHolder
import org.springframework.web.bind.annotation.* import org.springframework.web.bind.annotation.*
import space.luminic.finance.dtos.UserDTO import space.luminic.finance.dtos.UserDTO
import space.luminic.finance.dtos.UserDTO.AuthUserDTO import space.luminic.finance.dtos.UserDTO.AuthUserDTO
import space.luminic.finance.dtos.UserDTO.RegisterUserDTO import space.luminic.finance.dtos.UserDTO.RegisterUserDTO
import space.luminic.finance.mappers.UserMapper.toDto import space.luminic.finance.mappers.UserMapper.toDto
import space.luminic.finance.mappers.UserMapper.toTelegramMap
import space.luminic.finance.services.AuthService import space.luminic.finance.services.AuthService
import java.security.MessageDigest
import java.time.Instant
import javax.crypto.Mac
import javax.crypto.spec.SecretKeySpec
@RestController @RestController
@RequestMapping("/auth") @RequestMapping("/auth")
class AuthController( class AuthController(
private val authService: AuthService private val authService: AuthService,
@Value("\${telegram.bot.token}") private val botToken: String
) { ) {
private val logger = LoggerFactory.getLogger(javaClass) 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") @GetMapping("/test")
fun test(): String { fun test(): String {
val authentication = SecurityContextHolder.getContext().authentication val authentication = SecurityContextHolder.getContext().authentication
@@ -26,23 +70,26 @@ class AuthController(
} }
@PostMapping("/login") @PostMapping("/login")
fun login(@RequestBody request: AuthUserDTO): Map<String, String> { fun login(@RequestBody request: AuthUserDTO): Map<String, String> {
val token = authService.login(request.username.lowercase(), request.password) val token = authService.login(request.username.lowercase(), request.password)
return mapOf("token" to token) return mapOf("token" to token)
} }
@PostMapping("/register") @PostMapping("/register")
fun register(@RequestBody request: RegisterUserDTO): UserDTO { fun register(@RequestBody request: RegisterUserDTO): UserDTO {
return authService.register(request.username, request.password, request.firstName).toDto() return authService.register(request.username, request.password, request.firstName).toDto()
} }
@PostMapping("/tgLogin") @PostMapping("/tg-login")
fun tgLogin(@RequestHeader("X-Tg-Id") tgId: String): Map<String, String> { fun tgLogin(@RequestBody tgUser: UserDTO.TelegramAuthDTO): String {
val token = authService.tgLogin(tgId) val ok = verifyTelegramAuth(tgUser.toTelegramMap(), botToken)
return mapOf("token" to token) if (!ok) throw IllegalArgumentException("Invalid Telegram login")
return authService.tgAuth(tgUser)
} }
@GetMapping("/me") @GetMapping("/me")
fun getMe(): UserDTO { fun getMe(): UserDTO {
logger.info("Get Me") logger.info("Get Me")

View File

@@ -21,7 +21,7 @@ class BearerTokenFilter(
private val publicMatchers = listOf( private val publicMatchers = listOf(
AntPathRequestMatcher("/auth/login", "POST"), AntPathRequestMatcher("/auth/login", "POST"),
AntPathRequestMatcher("/auth/register", "POST"), AntPathRequestMatcher("/auth/register", "POST"),
AntPathRequestMatcher("/auth/tgLogin", "POST"), AntPathRequestMatcher("/auth/tg-login", "POST"),
AntPathRequestMatcher("/actuator/**"), AntPathRequestMatcher("/actuator/**"),
AntPathRequestMatcher("/static/**"), AntPathRequestMatcher("/static/**"),
AntPathRequestMatcher("/wishlistexternal/**"), AntPathRequestMatcher("/wishlistexternal/**"),

View File

@@ -31,7 +31,7 @@ class SecurityConfig(
.logout { it.disable() } .logout { it.disable() }
.authorizeHttpRequests { .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("/actuator/**", "/static/**").permitAll()
it.requestMatchers("/wishlistexternal/**").permitAll() it.requestMatchers("/wishlistexternal/**").permitAll()
it.requestMatchers("/swagger-ui/**", "/swagger-ui.html", "/v3/api-docs/**").permitAll() it.requestMatchers("/swagger-ui/**", "/swagger-ui.html", "/v3/api-docs/**").permitAll()

View File

@@ -1,11 +1,14 @@
package space.luminic.finance.dtos package space.luminic.finance.dtos
import java.util.Date
data class UserDTO ( data class UserDTO (
var id: Int, var id: Int,
val username: String, val username: String,
var firstName: String, var firstName: String,
var tgId: String? = null, var tgId: Long? = null,
var tgUserName: String? = null, var tgUserName: String? = null,
var photoUrl: String? = null,
var roles: List<String> 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
)
} }

View File

@@ -1,6 +1,7 @@
package space.luminic.finance.mappers package space.luminic.finance.mappers
import space.luminic.finance.dtos.UserDTO import space.luminic.finance.dtos.UserDTO
import space.luminic.finance.dtos.UserDTO.TelegramAuthDTO
import space.luminic.finance.models.User import space.luminic.finance.models.User
object UserMapper { object UserMapper {
@@ -11,7 +12,18 @@ object UserMapper {
firstName = this.firstName, firstName = this.firstName,
tgId = this.tgId, tgId = this.tgId,
tgUserName = this.tgUserName, tgUserName = this.tgUserName,
photoUrl = this.photoUrl,
roles = this.roles 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
)
} }

View File

@@ -11,8 +11,9 @@ data class User(
var id: Int? = null, var id: Int? = null,
val username: String, val username: String,
var firstName: String, var firstName: String,
var tgId: String? = null, var tgId: Long? = null,
var tgUserName: String? = null, var tgUserName: String? = null,
val photoUrl: String? = null,
var password: String? = null, var password: String? = null,
var isActive: Boolean = true, var isActive: Boolean = true,
var regDate: LocalDate = LocalDate.now(), var regDate: LocalDate = LocalDate.now(),

View File

@@ -9,8 +9,8 @@ interface UserRepo {
fun findById(id: Int): User? fun findById(id: Int): User?
fun findByUsername(username: String): User? fun findByUsername(username: String): User?
fun findParticipantsBySpace(spaceId: Int): Set<User> fun findParticipantsBySpace(spaceId: Int): Set<User>
fun findByTgId(tgId: String): User? fun findByTgId(tgId: Long): User?
fun save(user: User): User fun create(user: User): User
fun update(user: User): User fun update(user: User): User
fun deleteById(id: Long) fun deleteById(id: Long)
} }

View File

@@ -4,18 +4,20 @@ import org.springframework.jdbc.core.RowMapper
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate
import org.springframework.stereotype.Repository import org.springframework.stereotype.Repository
import space.luminic.finance.models.User import space.luminic.finance.models.User
@Repository @Repository
class UserRepoImpl( class UserRepoImpl(
private val jdbcTemplate: NamedParameterJdbcTemplate private val jdbcTemplate: NamedParameterJdbcTemplate
) : UserRepo{ ) : UserRepo {
private fun userRowMapper() = RowMapper { rs, _ -> private fun userRowMapper() = RowMapper { rs, _ ->
User( User(
id = rs.getInt("id"), id = rs.getInt("id"),
username = rs.getString("username"), username = rs.getString("username"),
firstName = rs.getString("first_name"), firstName = rs.getString("first_name"),
tgId = rs.getString("tg_id"), tgId = rs.getLong("tg_id"),
tgUserName = rs.getString("tg_user_name"), tgUserName = rs.getString("tg_user_name"),
photoUrl = rs.getString("photo_url"),
password = rs.getString("password"), password = rs.getString("password"),
isActive = rs.getBoolean("is_active"), isActive = rs.getBoolean("is_active"),
regDate = rs.getDate("reg_date").toLocalDate(), regDate = rs.getDate("reg_date").toLocalDate(),
@@ -41,11 +43,12 @@ class UserRepoImpl(
} }
override fun findParticipantsBySpace(spaceId: Int): Set<User> { 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() return jdbcTemplate.query(sql, mapOf("spaceId" to spaceId), userRowMapper()).toSet()
} }
override fun findByTgId(tgId: String): User? { override fun findByTgId(tgId: Long): User? {
val sql = """ val sql = """
select * from finance.users u where tg_id = :tgId select * from finance.users u where tg_id = :tgId
""".trimIndent() """.trimIndent()
@@ -53,13 +56,15 @@ class UserRepoImpl(
return jdbcTemplate.queryForObject(sql, params, userRowMapper()) return jdbcTemplate.queryForObject(sql, params, userRowMapper())
} }
override fun save(user: User): User { override fun create(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" 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( val params = mapOf(
"username" to user.username, "username" to user.username,
"firstname" to user.firstName, "firstname" to user.firstName,
"tg_id" to user.tgId, "tg_id" to user.tgId,
"tg_user_name" to user.tgUserName, "tg_user_name" to user.tgUserName,
"photo_url" to user.photoUrl,
"password" to user.password, "password" to user.password,
"isActive" to user.isActive, "isActive" to user.isActive,
"regDate" to user.regDate, "regDate" to user.regDate,

View File

@@ -6,6 +6,8 @@ import org.springframework.security.core.userdetails.UsernameNotFoundException
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder
import org.springframework.stereotype.Service import org.springframework.stereotype.Service
import space.luminic.finance.configs.AuthException 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.Token
import space.luminic.finance.models.User import space.luminic.finance.models.User
import space.luminic.finance.repos.UserRepo import space.luminic.finance.repos.UserRepo
@@ -44,7 +46,7 @@ class AuthService(
return username.toInt() return username.toInt()
} }
fun login(username: String, password: String): String { fun login(username: String, password: String): String {
val user = userRepo.findByUsername(username) val user = userRepo.findByUsername(username)
?: throw UsernameNotFoundException("Пользователь не найден") ?: throw UsernameNotFoundException("Пользователь не найден")
return if (passwordEncoder.matches(password, user.password)) { return if (passwordEncoder.matches(password, user.password)) {
@@ -61,10 +63,12 @@ class AuthService(
} }
} }
fun tgLogin(tgId: String): String { fun tgAuth(tgUser: UserDTO.TelegramAuthDTO): String {
val user = val user: User = try {
userRepo.findByTgId(tgId) ?: throw UsernameNotFoundException("Пользователь не найден") tgLogin(tgUser.id)
} catch (e: NotFoundException) {
registerTg(tgUser)
}
val token = jwtUtil.generateToken(user.username) val token = jwtUtil.generateToken(user.username)
val expireAt = Date(System.currentTimeMillis() + 1000 * 60 * 60 * 24 * 10) val expireAt = Date(System.currentTimeMillis() + 1000 * 60 * 60 * 24 * 10)
tokenService.saveToken( tokenService.saveToken(
@@ -73,7 +77,22 @@ class AuthService(
expiresAt = expireAt.toInstant() expiresAt = expireAt.toInstant()
) )
return token 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 { fun register(username: String, password: String, firstName: String): User {
@@ -85,14 +104,14 @@ class AuthService(
firstName = firstName, firstName = firstName,
roles = mutableListOf("USER") roles = mutableListOf("USER")
) )
newUser = userRepo.save(newUser) newUser = userRepo.create(newUser)
return newUser return newUser
} else throw IllegalArgumentException("Пользователь уже зарегистрирован") } else throw IllegalArgumentException("Пользователь уже зарегистрирован")
} }
@Cacheable(cacheNames = ["tokens"], key = "#token") @Cacheable(cacheNames = ["tokens"], key = "#token")
fun isTokenValid(token: String): User { fun isTokenValid(token: String): User {
val tokenDetails = tokenService.getToken(token) val tokenDetails = tokenService.getToken(token)
when { when {
tokenDetails.status == Token.TokenStatus.ACTIVE && tokenDetails.expiresAt.isAfter(Instant.now()) -> { tokenDetails.status == Token.TokenStatus.ACTIVE && tokenDetails.expiresAt.isAfter(Instant.now()) -> {

View File

@@ -24,7 +24,7 @@ class UserService(val userRepo: UserRepo) {
} }
fun getUserByTelegramId(telegramId: Long): User { 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")
} }

View File

@@ -1,10 +1,6 @@
spring.application.name=budger-app 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 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.web=INFO
logging.level.org.springframework.data = INFO logging.level.org.springframework.data = INFO
logging.level.org.springframework.data.mongodb.core.ReactiveMongoTemplate=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 #management.endpoint.metrics.access=read_only
telegram.bot.token = 6662300972:AAFXjk_h0AUCy4bORC12UcdXbYnh2QSVKAY telegram.bot.token = 7999296388:AAGXPE5r0yt3ZFehBoUh8FGm5FBbs9pYIks
nlp.address=https://nlp.luminic.space 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.username=luminicspace
spring.datasource.password=LS1q2w3e4r! spring.datasource.password=LS1q2w3e4r!

View File

@@ -1,6 +1,6 @@
spring.application.name=budger-app spring.application.name=budger-app
server.port=8082 server.port=8089
server.servlet.context-path=/api server.servlet.context-path=/api
#spring.webflux.base-path=/api #spring.webflux.base-path=/api

View 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;;