package space.luminic.finance.api import kotlinx.coroutines.reactive.awaitSingle import org.slf4j.LoggerFactory import org.springframework.security.core.context.ReactiveSecurityContextHolder 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 import space.luminic.finance.mappers.UserMapper.toDto import space.luminic.finance.services.AuthService import space.luminic.finance.services.UserService import kotlin.jvm.javaClass import kotlin.to @RestController @RequestMapping("/auth") class AuthController( private val userService: UserService, private val authService: AuthService ) { private val logger = LoggerFactory.getLogger(javaClass) @GetMapping("/test") fun test(): String { val authentication = SecurityContextHolder.getContext().authentication logger.info("SecurityContext in controller: $authentication") return "Hello, ${authentication.name}" } @PostMapping("/login") suspend fun login(@RequestBody request: AuthUserDTO): Map { val token = authService.login(request.username, request.password) return mapOf("token" to token) } @PostMapping("/register") suspend fun register(@RequestBody request: RegisterUserDTO): UserDTO { return authService.register(request.username, request.password, request.firstName).toDto() } @PostMapping("/tgLogin") suspend fun tgLogin(@RequestHeader("X-Tg-Id") tgId: String): Map { val token = authService.tgLogin(tgId) return mapOf("token" to token) } @GetMapping("/me") suspend fun getMe(): UserDTO { val securityContext = ReactiveSecurityContextHolder.getContext().awaitSingle() return userService.getByUsername(securityContext.authentication.name).toDto() } }