This commit is contained in:
xds
2025-10-31 15:31:55 +03:00
parent 040da34ff7
commit 7972ea0fdf
117 changed files with 3691 additions and 2013 deletions

View File

@@ -1,10 +1,7 @@
package space.luminic.finance.services
import kotlinx.coroutines.reactive.awaitFirstOrNull
import kotlinx.coroutines.reactor.awaitSingle
import kotlinx.coroutines.reactor.awaitSingleOrNull
import org.springframework.cache.annotation.Cacheable
import org.springframework.security.core.context.ReactiveSecurityContextHolder
import org.springframework.security.core.context.SecurityContextHolder
import org.springframework.security.core.userdetails.UsernameNotFoundException
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder
import org.springframework.stereotype.Service
@@ -13,14 +10,13 @@ import space.luminic.finance.models.Token
import space.luminic.finance.models.User
import space.luminic.finance.repos.UserRepo
import space.luminic.finance.utils.JWTUtil
import java.time.LocalDateTime
import java.time.ZoneId
import java.time.Instant
import java.util.*
@Service
class AuthService(
private val userRepository: UserRepo,
private val userRepo: UserRepo,
private val tokenService: TokenService,
private val jwtUtil: JWTUtil,
private val userService: UserService,
@@ -28,18 +24,28 @@ class AuthService(
) {
private val passwordEncoder = BCryptPasswordEncoder()
suspend fun getSecurityUser(): User {
val securityContextHolder = ReactiveSecurityContextHolder.getContext().awaitSingleOrNull()
fun getSecurityUser(): User {
val securityContextHolder = SecurityContextHolder.getContext()
?: throw AuthException("Authentication failed")
val authentication = securityContextHolder.authentication
val username = authentication.name
// Получаем пользователя по имени
return userService.getByUsername(username)
return userService.getById(username.toInt())
}
suspend fun login(username: String, password: String): String {
val user = userRepository.findByUsername(username).awaitFirstOrNull()
fun getSecurityUserId(): Int {
val securityContextHolder = SecurityContextHolder.getContext()
?: throw AuthException("Authentication failed")
val authentication = securityContextHolder.authentication
val username = authentication.name
// Получаем пользователя по имени
return username.toInt()
}
fun login(username: String, password: String): String {
val user = userRepo.findByUsername(username)
?: throw UsernameNotFoundException("Пользователь не найден")
return if (passwordEncoder.matches(password, user.password)) {
val token = jwtUtil.generateToken(user.username)
@@ -47,10 +53,7 @@ class AuthService(
tokenService.saveToken(
token = token,
username = username,
expiresAt = LocalDateTime.ofInstant(
expireAt.toInstant(),
ZoneId.systemDefault()
)
expiresAt = expireAt.toInstant()
)
token
} else {
@@ -58,26 +61,23 @@ class AuthService(
}
}
suspend fun tgLogin(tgId: String): String {
fun tgLogin(tgId: String): String {
val user =
userRepository.findByTgId(tgId).awaitSingleOrNull() ?: throw UsernameNotFoundException("Пользователь не найден")
userRepo.findByTgId(tgId) ?: throw UsernameNotFoundException("Пользователь не найден")
val token = jwtUtil.generateToken(user.username)
val expireAt = Date(System.currentTimeMillis() + 1000 * 60 * 60 * 24 * 10)
tokenService.saveToken(
token = token,
username = user.username,
expiresAt = LocalDateTime.ofInstant(
expireAt.toInstant(),
ZoneId.systemDefault()
)
expiresAt = expireAt.toInstant()
)
return token
}
suspend fun register(username: String, password: String, firstName: String): User {
val user = userRepository.findByUsername(username).awaitSingleOrNull()
fun register(username: String, password: String, firstName: String): User {
val user = userRepo.findByUsername(username)
if (user == null) {
var newUser = User(
username = username,
@@ -85,18 +85,18 @@ class AuthService(
firstName = firstName,
roles = mutableListOf("USER")
)
newUser = userRepository.save(newUser).awaitSingle()
newUser = userRepo.save(newUser)
return newUser
} else throw IllegalArgumentException("Пользователь уже зарегистрирован")
}
@Cacheable(cacheNames = ["tokens"], key = "#token")
suspend fun isTokenValid(token: String): User {
val tokenDetails = tokenService.getToken(token).awaitFirstOrNull() ?: throw AuthException("Токен не валиден")
fun isTokenValid(token: String): User {
val tokenDetails = tokenService.getToken(token)
when {
tokenDetails.status == Token.TokenStatus.ACTIVE && tokenDetails.expiresAt.isAfter(LocalDateTime.now()) -> {
return userService.getByUsername(tokenDetails.username)
tokenDetails.status == Token.TokenStatus.ACTIVE && tokenDetails.expiresAt.isAfter(Instant.now()) -> {
return tokenDetails.user
}
else -> {