ebanie_sneakrsi

This commit is contained in:
Your Name 2025-03-07 00:54:58 +03:00
commit 50646861e6
23 changed files with 1054 additions and 0 deletions

45
.gitignore vendored Normal file
View File

@ -0,0 +1,45 @@
.gradle
build/
!gradle/wrapper/gradle-wrapper.jar
!**/src/main/**/build/
!**/src/test/**/build/
### IntelliJ IDEA ###
.idea/modules.xml
.idea/jarRepositories.xml
.idea/compiler.xml
.idea/libraries/
*.iws
*.iml
*.ipr
out/
!**/src/main/**/out/
!**/src/test/**/out/
### Kotlin ###
.kotlin
### Eclipse ###
.apt_generated
.classpath
.factorypath
.project
.settings
.springBeans
.sts4-cache
bin/
!**/src/main/**/bin/
!**/src/test/**/bin/
### NetBeans ###
/nbproject/private/
/nbbuild/
/dist/
/nbdist/
/.nb-gradle/
### VS Code ###
.vscode/
### Mac OS ###
.DS_Store

3
.idea/.gitignore vendored Normal file
View File

@ -0,0 +1,3 @@
# Default ignored files
/shelf/
/workspace.xml

1
.idea/.name Normal file
View File

@ -0,0 +1 @@
t-test-ktor

17
.idea/gradle.xml Normal file
View File

@ -0,0 +1,17 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="GradleMigrationSettings" migrationVersion="1" />
<component name="GradleSettings">
<option name="linkedExternalProjectsSettings">
<GradleProjectSettings>
<option name="externalProjectPath" value="$PROJECT_DIR$" />
<option name="gradleHome" value="" />
<option name="modules">
<set>
<option value="$PROJECT_DIR$" />
</set>
</option>
</GradleProjectSettings>
</option>
</component>
</project>

6
.idea/kotlinc.xml Normal file
View File

@ -0,0 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="KotlinJpsPluginSettings">
<option name="version" value="2.1.10" />
</component>
</project>

7
.idea/misc.xml Normal file
View File

@ -0,0 +1,7 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ExternalStorageConfigurationManager" enabled="true" />
<component name="ProjectRootManager" version="2" languageLevel="JDK_22" default="true" project-jdk-name="corretto-22" project-jdk-type="JavaSDK">
<output url="file://$PROJECT_DIR$/out" />
</component>
</project>

6
.idea/vcs.xml Normal file
View File

@ -0,0 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="VcsDirectoryMappings">
<mapping directory="" vcs="Git" />
</component>
</project>

21
Dockerfile Normal file
View File

@ -0,0 +1,21 @@
FROM gradle:latest AS cache
RUN mkdir -p /home/gradle/cache_home
ENV GRADLE_USER_HOME=/home/gradle/cache_home
COPY build.gradle.kts gradle.properties settings.gradle.kts /home/gradle/app/
COPY gradle /home/gradle/app/gradle
WORKDIR /home/gradle/app
RUN gradle dependencies --no-daemon
FROM gradle:latest AS build
COPY --from=cache /home/gradle/cache_home /home/gradle/.gradle
COPY . /usr/src/app/
WORKDIR /usr/src/app
RUN ./gradlew build -x test
FROM amazoncorretto:22 AS runtime
EXPOSE 8080
RUN mkdir /app
COPY --from=build /usr/src/app/build/libs/*.jar /app/ktor-app.jar
ENTRYPOINT ["java", "-jar", "/app/ktor-app.jar"]

58
build.gradle.kts Normal file
View File

@ -0,0 +1,58 @@
plugins {
kotlin("jvm") version "2.1.10"
kotlin("plugin.serialization") version "1.8.0"
id("io.ktor.plugin") version "3.1.0"
}
ktor {
docker {
jreVersion.set(JavaVersion.VERSION_22)
localImageName.set("ktor-api")
imageTag.set("latest")
portMappings.set(
listOf(
io.ktor.plugin.features.DockerPortMapping(8080, 8080, io.ktor.plugin.features.DockerPortMappingProtocol.TCP)
)
)
}
application {
mainClass.set("com.example.ApplicationKt")
}
}
group = "org.example"
version = "1.0-SNAPSHOT"
repositories {
mavenCentral()
}
dependencies {
testImplementation(kotlin("test"))
implementation("io.ktor:ktor-client-core:2.3.4")
implementation("io.ktor:ktor-server-netty:2.3.4")
implementation("io.ktor:ktor-server-core:2.3.4")
implementation("io.ktor:ktor-server-content-negotiation:2.3.4")
implementation("io.ktor:ktor-serialization-kotlinx-json:2.3.4")
implementation("ch.qos.logback:logback-classic:1.4.11")
implementation("org.jetbrains.kotlinx:kotlinx-serialization-json:1.5.0")
implementation("org.jetbrains.exposed:exposed-core:0.43.0")
implementation("org.jetbrains.exposed:exposed-dao:0.43.0")
implementation("org.jetbrains.exposed:exposed-jdbc:0.43.0")
implementation("org.postgresql:postgresql:42.6.0")
implementation("org.jetbrains.kotlinx:kotlinx-coroutines-core:1.7.3")
implementation("com.sun.mail:javax.mail:1.6.2")
implementation("org.jetbrains.exposed:exposed-java-time:0.41.1")
implementation("at.favre.lib:bcrypt:0.10.2")
implementation("io.ktor:ktor-server-content-negotiation:2.3.4")
implementation("io.ktor:ktor-serialization-kotlinx-json:2.3.4")
implementation("org.jetbrains.kotlinx:kotlinx-serialization-json:1.5.1")
}
tasks.test {
useJUnitPlatform()
}
kotlin {
jvmToolchain(22)
}

44
docker-compose.yml Normal file
View File

@ -0,0 +1,44 @@
#version: "3.8"
#
#services:
# mailhog:
# image: mailhog/mailhog
# container_name: mailhog
# restart: always
# ports:
# - "1025:1025"
# - "8025:8025"
version: '3.8'
services:
db:
image: postgres:16
container_name: postgres_db
restart: always
ports:
- "5436:5432"
environment:
POSTGRES_DB: mydatabase
POSTGRES_USER: postgres
POSTGRES_PASSWORD: 123
volumes:
- postgres_data:/var/lib/postgresql/data
- ./init.sql:/docker-entrypoint-initdb.d/init.sql
ktor_api:
build: .
container_name: ktor_api
restart: always
depends_on:
- db
ports:
- "8080:8080"
environment:
DATABASE_URL: jdbc:postgresql://db:5432/mydatabase
DATABASE_USER: postgres
DATABASE_PASSWORD: 123
volumes:
postgres_data:

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 Feb 19 00:01:32 MSK 2025
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-8.10-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

28
init.sql Normal file
View File

@ -0,0 +1,28 @@
CREATE TABLE IF NOT EXISTS users (
id SERIAL PRIMARY KEY,
name VARCHAR(255) NOT NULL,
email VARCHAR(255) UNIQUE NOT NULL,
password_hash TEXT NOT NULL,
reset_token TEXT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
CREATE TABLE IF NOT EXISTS sneakers(
id SERIAL PRIMARY KEY,
name VARCHAR(255) NOT NULL,
description VARCHAR(255) NOT NULL,
cost DECIMAL(10,2) NOT NULL,
discount INTEGER NOT NULL CHECK (discount >= 0 AND discount <= 100),
photo VARCHAR(255) NOT NULL,
gender CHAR(1) NOT NULL CHECK (gender IN ('M', 'F', 'U')),
bootSize INTEGER NOT NULL
);
INSERT INTO sneakers (name, description, cost, discount, photo, gender, bootSize)
VALUES ('Adidas', 'fast', 120.50, 10, 'https://i8.amplience.net/i/jpl/jd_619310_a?qlt=92', 'M', 42);
INSERT INTO sneakers (name, description, cost, discount, photo, gender, bootSize)
VALUES ('Nike Air Max', 'Comfortable running shoes', 140, 40, 'https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcRe7ZbQ92u1JD-JgD4Kkhkju83p_uvKelP5jw&s', 'F', 39);
INSERT INTO sneakers (name, description, cost, discount, photo, gender, bootSize)
VALUES ('Puma', 'fast too', 80.12, 80, 'https://img01.ztat.net/article/spp-media-p1/c6ebc4348bd34d9fa4235a82453230fe/3c034c2c43b94d879d41d33d0eb18e14.jpg?imwidth=1800&filter=packshot', 'U', 41);

5
settings.gradle.kts Normal file
View File

@ -0,0 +1,5 @@
plugins {
id("org.gradle.toolchains.foojay-resolver-convention") version "0.8.0"
}
rootProject.name = "t-test-ktor"

View File

@ -0,0 +1,134 @@
package com.example
import com.example.*
import io.ktor.http.*
import io.ktor.server.application.*
import io.ktor.server.engine.embeddedServer
import io.ktor.server.netty.Netty
import io.ktor.server.plugins.contentnegotiation.*
import io.ktor.serialization.kotlinx.json.*
import io.ktor.server.request.*
import io.ktor.server.response.*
import io.ktor.server.routing.*
import kotlinx.serialization.KSerializer
import kotlinx.serialization.descriptors.PrimitiveKind
import kotlinx.serialization.descriptors.PrimitiveSerialDescriptor
import kotlinx.serialization.descriptors.SerialDescriptor
import kotlinx.serialization.encoding.Decoder
import kotlinx.serialization.encoding.Encoder
import kotlinx.serialization.json.Json
import kotlinx.serialization.modules.SerializersModule
import kotlinx.serialization.modules.contextual
import java.math.BigDecimal
fun main() {
embeddedServer(Netty, port = 8080, host = "0.0.0.0") {
configureSerialization()
configureRouting()
DatabaseFactory.init()
}.start(wait = true)
}
object BigDecimalSerializer : KSerializer<BigDecimal> {
override val descriptor: SerialDescriptor =
PrimitiveSerialDescriptor("BigDecimal", PrimitiveKind.STRING)
override fun serialize(encoder: Encoder, value: BigDecimal) {
encoder.encodeString(value.toPlainString())
}
override fun deserialize(decoder: Decoder): BigDecimal {
return BigDecimal(decoder.decodeString())
}
}
fun Application.configureSerialization() {
install(ContentNegotiation) {
json(Json {
serializersModule = SerializersModule {
contextual(BigDecimalSerializer) // Добавляем поддержку BigDecimal
}
})
}
}
fun Application.configureRouting() {
routing {
post("/register") {
val request = call.receive<UserRegisterRequest>()
if (AuthService.registerUser(request.name, request.email, request.password)) {
call.respond(mapOf("message" to "Регистрация успешна"))
} else {
call.respond(mapOf("error" to "Email уже зарегистрирован"))
}
}
post("/login") {
val request = call.receive<UserLoginRequest>()
if (AuthService.loginUser(request.email, request.password)) {
call.respond(mapOf("message" to "Вход успешен"))
} else {
call.respond(mapOf("error" to "Неверный email или пароль"))
}
}
post("/forgot-password") {
val request = call.receive<UserForgotPasswordRequest>()
val code = AuthService.generateResetCode(request.email)
if (code != null) {
EmailService.sendResetEmail(request.email, code)
call.respond(mapOf("message" to "Код на восстановление пароля отправлен"))
} else {
call.respond(mapOf("error" to "Email не найден"))
}
}
post("/reset-password") {
val request = call.receive<UserResetPasswordRequest>()
if (AuthService.resetPassword(request.code, request.newPassword)) {
call.respond(mapOf("message" to "Пароль успешно изменён"))
} else {
call.respond(mapOf("error" to "Неверный код"))
}
}
post("/reset-passwor") {
val request = call.receive<UserResetPasswordRequest>()
if (AuthService.resetPassword(request.code, request.newPassword)) {
call.respond(mapOf("message" to "Пароль успешно изменён"))
} else {
call.respond(mapOf("error" to "Неверный код"))
}
}
// get ("/mainWindow"){
// val sneakers = AuthService.selectSneakers()
// call.respond(mapOf("sneaker" to sneakers))
// }
// get("/mainWindow") {
// try {
// // Ваш код для обработки запроса
// call.respondText("Main Window Content")
// } catch (e: Exception) {
// call.respond(HttpStatusCode.InternalServerError, "Error: ${e.message}")
// }
// }
get("/mainWindow") {
try {
val sneakers = AuthService.selectSneakers()
if (sneakers.isNotEmpty()) {
call.respond(mapOf("sneakers" to sneakers))
} else {
call.respond(mapOf("error" to "No sneakers found"))
}
} catch (e: Exception) {
log.error("Error fetching sneakers: ${e.message}", e)
call.respond(HttpStatusCode.InternalServerError, "Error: ${e.message}")
}
}
}
}

View File

@ -0,0 +1,188 @@
//package com.example
//
//import at.favre.lib.crypto.bcrypt.BCrypt
//import org.jetbrains.exposed.sql.*
//import org.jetbrains.exposed.sql.transactions.transaction
//import java.util.UUID
//
//object AuthService {
//
// fun registerUser(name: String, email: String, password: String): Boolean {
// val hashedPassword = hashPassword(password)
// return transaction {
// if (Users.select { Users.email eq email }.empty()) {
// Users.insert {
// it[Users.name] = name
// it[Users.email] = email
// it[Users.passwordHash] = hashedPassword
// }
// true
// } else {
// false
// }
// }
// }
//
// fun loginUser(email: String, password: String): Boolean {
// val user = transaction {
// Users.select { Users.email eq email }
// .mapNotNull { it[Users.passwordHash] }
// .firstOrNull()
// }
// return user != null && checkPassword(password, user)
// }
//
// fun generateResetToken(email: String): String? {
// val token = UUID.randomUUID().toString()
// return transaction {
// val updatedRows = Users.update({ Users.email eq email }) {
// it[resetToken] = token
// }
// if (updatedRows > 0) token else null
// }
// }
//
// fun resetPassword(token: String, newPassword: String): Boolean {
// return transaction {
// val email = Users.select { Users.resetToken eq token }
// .mapNotNull { it[Users.email] }
// .firstOrNull()
//
// if (email != null) {
// val hashedPassword = hashPassword(newPassword)
// Users.update({ Users.email eq email }) {
// it[passwordHash] = hashedPassword
// it[resetToken] = null
// }
// true
// } else {
// false
// }
// }
// }
//
// private fun hashPassword(password: String): String {
// return BCrypt.withDefaults().hashToString(12, password.toCharArray())
// }
//
// private fun checkPassword(password: String, hash: String): Boolean {
// return BCrypt.verifyer().verify(password.toCharArray(), hash).verified
// }
//}
package com.example
import at.favre.lib.crypto.bcrypt.BCrypt
import org.jetbrains.exposed.sql.*
import org.jetbrains.exposed.sql.transactions.transaction
import java.net.InetAddress
import java.util.Random
object AuthService {
//USERS
fun registerUser(name: String, email: String, password: String): Boolean {
if (!isEmailValid(email)) {
return false
}
val hashedPassword = hashPassword(password)
return transaction {
if (Users.select { Users.email eq email }.empty()) {
Users.insert {
it[Users.name] = name
it[Users.email] = email
it[Users.passwordHash] = hashedPassword
}
true
} else {
false
}
}
}
fun loginUser(email: String, password: String): Boolean {
val user = transaction {
Users.select { Users.email eq email }
.mapNotNull { it[Users.passwordHash] }
.firstOrNull()
}
return user != null && checkPassword(password, user)
}
fun generateResetCode(email: String): String? {
val code = generate4DigitCode()
return transaction {
val updatedRows = Users.update({ Users.email eq email }) {
it[resetToken] = code
}
if (updatedRows > 0) code else null
}
}
fun resetPassword(code: String, newPassword: String): Boolean {
return transaction {
val email = Users.select { Users.resetToken eq code }
.mapNotNull { it[Users.email] }
.firstOrNull()
if (email != null) {
val hashedPassword = hashPassword(newPassword)
Users.update({ Users.email eq email }) {
it[passwordHash] = hashedPassword
it[resetToken] = null
}
true
} else {
false
}
}
}
private fun isEmailValid(email: String): Boolean {
return try {
val domain = email.substringAfter("@")
val addresses = InetAddress.getAllByName(domain)
addresses.isNotEmpty()
} catch (e: Exception) {
false
}
}
private fun generate4DigitCode(): String {
return (1000..9999).random().toString()
}
private fun hashPassword(password: String): String {
return BCrypt.withDefaults().hashToString(12, password.toCharArray())
}
private fun checkPassword(password: String, hash: String): Boolean {
return BCrypt.verifyer().verify(password.toCharArray(), hash).verified
}
//SNEAKERS
fun selectSneakers(): List<Sneaker> {
try {
return transaction {
Sneakers.selectAll().map {
Sneaker(
id = it[Sneakers.id],
name = it[Sneakers.name],
description = it[Sneakers.description],
cost = it[Sneakers.cost],
discount = it[Sneakers.discount],
photo = it[Sneakers.photo],
gender = it[Sneakers.gender],
bootSize = it[Sneakers.bootSize]
)
}
}
} catch (e: Exception) {
throw RuntimeException("Error selecting sneakers: ${e.message}", e)
}
}
}

View File

@ -0,0 +1,23 @@
import com.example.Users
import org.jetbrains.exposed.sql.Database
import org.jetbrains.exposed.sql.SchemaUtils
import org.jetbrains.exposed.sql.transactions.transaction
object DatabaseFactory {
fun init() {
val url = System.getenv("DATABASE_URL") ?: "jdbc:postgresql://localhost:5436/postgres"
val user = System.getenv("DATABASE_USER") ?: "postgres"
val password = System.getenv("DATABASE_PASSWORD") ?: "123"
Database.connect(
url = url,
driver = "org.postgresql.Driver",
user = user,
password = password
)
transaction {
SchemaUtils.create(Users)
}
}
}

View File

@ -0,0 +1,72 @@
package com.example
import java.util.Properties
import javax.mail.*
import javax.mail.internet.InternetAddress
import javax.mail.internet.MimeMessage
import org.jetbrains.exposed.sql.*
import org.jetbrains.exposed.sql.transactions.transaction
object EmailService {
private const val SMTP_HOST = "smtp.yandex.ru"
private const val SMTP_PORT = "465"
private const val SMTP_USER = "perfiljevkiver@yandex.ru"
private const val SMTP_PASSWORD = "nuuxizcgsssknurl"
fun sendResetEmail(to: String, code: String) {
val userName = transaction {
Users.select { Users.email eq to }
.mapNotNull { it[Users.name] }
.firstOrNull() ?: "Пользователь"
}
val props = Properties().apply {
put("mail.smtp.host", SMTP_HOST)
put("mail.smtp.port", SMTP_PORT)
put("mail.smtp.auth", "true")
put("mail.smtp.ssl.enable", "true")
}
val session = Session.getInstance(props, object : Authenticator() {
override fun getPasswordAuthentication(): PasswordAuthentication {
return PasswordAuthentication(SMTP_USER, SMTP_PASSWORD)
}
})
try {
val message = MimeMessage(session).apply {
setFrom(InternetAddress(SMTP_USER, "Support Team"))
setRecipients(Message.RecipientType.TO, InternetAddress.parse(to))
subject = "🔐 Восстановление пароля"
val htmlContent = """
<html>
<body style="font-family: Arial, sans-serif; line-height: 1.5; color: #333;">
<h2 style="color: #007bff;">Восстановление пароля</h2>
<p>Здравствуйте, <b>$userName</b>,</p>
<p>Вы запросили восстановление пароля. Введите следующий код:</p>
<p style="font-size: 24px; font-weight: bold; color: #d9534f; background: #f8d7da; padding: 10px; border-radius: 5px; text-align: center;">
$code
</p>
<p>Если вы не запрашивали восстановление пароля, просто проигнорируйте это сообщение.</p>
<hr>
<p style="font-size: 12px; color: #888;">Это автоматическое сообщение, пожалуйста, не отвечайте на него.</p>
</body>
</html>
""".trimIndent()
setContent(htmlContent, "text/html; charset=UTF-8")
}
Transport.send(message)
println("✅ Email успешно отправлен на $to через Яндекс SMTP")
} catch (e: MessagingException) {
e.printStackTrace()
println("❌ Ошибка при отправке email через Яндекс: ${e.message}")
}
}
}

View File

@ -0,0 +1,35 @@
package com.example
import com.example.Sneakers.char
import com.example.Sneakers.decimal
import com.example.Sneakers.integer
import com.example.Sneakers.varchar
import kotlinx.serialization.Contextual
import kotlinx.serialization.Serializable
import java.math.BigDecimal
import java.text.DecimalFormat
@Serializable
data class UserRegisterRequest(val name: String, val email: String, val password: String)
@Serializable
data class UserLoginRequest(val email: String, val password: String)
@Serializable
data class UserForgotPasswordRequest(val email: String)
@Serializable
data class UserResetPasswordRequest(val code: String, val newPassword: String)
@Serializable
data class Sneaker(
val id: Int,
val name: String,
val description: String,
@Contextual val cost: BigDecimal,
val discount: Int,
val photo: String,
val gender: Char,
val bootSize: Int
)

31
src/main/kotlin/Users.kt Normal file
View File

@ -0,0 +1,31 @@
package com.example
import kotlinx.serialization.Serializable
import org.jetbrains.exposed.sql.Table
import org.jetbrains.exposed.sql.javatime.timestamp
import java.math.BigDecimal
import java.time.Instant
object Users : Table("users") {
val id = integer("id").autoIncrement()
val name = varchar("name", 255)
val email = varchar("email", 255).uniqueIndex()
val passwordHash = text("password_hash")
val resetToken = text("reset_token").nullable()
val createdAt = timestamp("created_at").default(Instant.now())
override val primaryKey = PrimaryKey(id)
}
object Sneakers : Table("sneakers") {
val id = integer("id").autoIncrement()
val name = varchar("name", 255)
val description = varchar("description", 255)
val cost = decimal("cost", 10, 2)
val discount = integer("discount")
val photo = varchar("photo", 255)
val gender = char("gender")
val bootSize = integer("bootsize")
override val primaryKey = PrimaryKey(id)
}