feat: websocket support

This commit is contained in:
SOR
2026-06-25 13:24:47 +08:00
parent b3e1fd9e18
commit cc0d8da750
19 changed files with 353 additions and 230 deletions
-1
View File
@@ -30,7 +30,6 @@ dependencies {
implementation("org.springframework.boot:spring-boot-starter-validation")
implementation("org.springframework.boot:spring-boot-starter-webflux")
implementation("org.springframework:spring-messaging")
implementation("io.projectreactor.kotlin:reactor-kotlin-extensions")
implementation("org.jetbrains.kotlin:kotlin-reflect")
implementation("org.jetbrains.kotlinx:kotlinx-coroutines-reactor")
implementation("org.jetbrains.kotlinx:kotlinx-datetime:0.6.0")
@@ -4,8 +4,8 @@ import org.springframework.boot.autoconfigure.SpringBootApplication
import org.springframework.boot.runApplication
@SpringBootApplication
class CareerppApplication
class BackendApplication
fun main(args: Array<String>) {
runApplication<CareerppApplication>(*args)
runApplication<BackendApplication>(*args)
}
@@ -1,6 +1,6 @@
package com.github.sor2171.backend.config
import com.github.sor2171.backend.entity.RestBean
import com.github.sor2171.backend.entity.ApiResponse
import com.github.sor2171.backend.entity.vo.response.AuthorizeVO
import com.github.sor2171.backend.filter.JwtAuthorizeFilter
import com.github.sor2171.backend.service.AccountService
@@ -50,13 +50,15 @@ class SecurityConfig(
.authorizeExchange {
it
.pathMatchers(
"/api/auth/relogin"
"/api/v1/auth/relogin"
).authenticated()
.pathMatchers(
"/api/auth/**",
"/api/v1/auth/**",
"/ws/**",
"/error"
).permitAll()
.anyExchange().authenticated()
.anyExchange()
.authenticated()
}
.addFilterAt(loginAuthenticationFilter(), SecurityWebFiltersOrder.AUTHENTICATION)
.addFilterAt(jwtAuthorizeFilter, SecurityWebFiltersOrder.AUTHENTICATION)
@@ -65,14 +67,14 @@ class SecurityConfig(
writeJsonResponse(
exchange,
HttpStatus.UNAUTHORIZED,
RestBean.unauthenticated(ex.message)
ApiResponse.unauthenticated(ex.message)
)
}
.accessDeniedHandler { exchange, ex ->
writeJsonResponse(
exchange,
HttpStatus.FORBIDDEN,
RestBean.forbidden(ex.message)
ApiResponse.forbidden(ex.message)
)
}
}
@@ -85,7 +87,7 @@ class SecurityConfig(
fun loginAuthenticationFilter(): AuthenticationWebFilter {
val filter = AuthenticationWebFilter(reactiveAuthenticationManager())
filter.setRequiresAuthenticationMatcher(
ServerWebExchangeMatchers.pathMatchers("/api/auth/login")
ServerWebExchangeMatchers.pathMatchers("/api/v1/auth/login")
)
filter.setServerAuthenticationConverter(loginAuthenticationConverter())
filter.setAuthenticationSuccessHandler { webFilterExchange, authentication ->
@@ -102,7 +104,7 @@ class SecurityConfig(
writeJsonResponse(
webFilterExchange.exchange,
HttpStatus.OK,
RestBean.success(vo)
ApiResponse.success(vo)
)
}
}
@@ -110,7 +112,7 @@ class SecurityConfig(
writeJsonResponse(
webFilterExchange.exchange,
HttpStatus.UNAUTHORIZED,
RestBean.unauthenticated(exception.message)
ApiResponse.unauthenticated(exception.message)
)
}
return filter
@@ -134,18 +136,18 @@ class SecurityConfig(
}
}
}
}
internal inline fun <reified T> writeJsonResponse(
exchange: ServerWebExchange,
status: HttpStatus,
body: RestBean<T>
): Mono<Void> {
val response = exchange.response
response.statusCode = status
response.headers.contentType = MediaType.APPLICATION_JSON
private inline fun <reified T> writeJsonResponse(
exchange: ServerWebExchange,
status: HttpStatus,
body: ApiResponse<T>
): Mono<Void> {
val response = exchange.response
response.statusCode = status
response.headers.contentType = MediaType.APPLICATION_JSON
val jsonString = Json.encodeToJsonElement(body).toString()
val buffer = response.bufferFactory().wrap(jsonString.toByteArray())
return response.writeWith(Mono.just(buffer))
val jsonString = Json.encodeToJsonElement(body).toString()
val buffer = response.bufferFactory().wrap(jsonString.toByteArray())
return response.writeWith(Mono.just(buffer))
}
}
@@ -0,0 +1,31 @@
package com.github.sor2171.backend.config
import com.github.sor2171.backend.handler.TestHandler
import com.github.sor2171.backend.handler.v1.ExampleHandler
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
import org.springframework.web.reactive.HandlerMapping
import org.springframework.web.reactive.handler.SimpleUrlHandlerMapping
import org.springframework.web.reactive.socket.server.support.WebSocketHandlerAdapter
@Configuration
class WebSocketConfig(
private val exampleHandler: ExampleHandler,
private val testHandler: TestHandler
) {
@Bean
fun handlerMapping(): HandlerMapping {
val map = mapOf(
"/ws/v1/example" to exampleHandler,
"/ws/test" to testHandler
)
val mapping = SimpleUrlHandlerMapping()
mapping.urlMap = map
mapping.order = 1
return mapping
}
@Bean
fun handlerAdapter(): WebSocketHandlerAdapter =
WebSocketHandlerAdapter()
}
@@ -1,24 +1,29 @@
package com.github.sor2171.backend.controller
package com.github.sor2171.backend.controller.v1
import com.github.sor2171.backend.entity.RestBean
import com.github.sor2171.backend.entity.ApiResponse
import com.github.sor2171.backend.entity.vo.request.EmailRegisterVO
import com.github.sor2171.backend.entity.vo.request.PasswordResetVO
import com.github.sor2171.backend.service.AccountService
import com.github.sor2171.backend.service.v1.AuthorizationService
import jakarta.validation.Valid
import jakarta.validation.constraints.Email
import jakarta.validation.constraints.NotBlank
import jakarta.validation.constraints.Pattern
import org.slf4j.LoggerFactory
import org.springframework.validation.annotation.Validated
import org.springframework.web.bind.annotation.*
import org.springframework.web.bind.annotation.GetMapping
import org.springframework.web.bind.annotation.PostMapping
import org.springframework.web.bind.annotation.RequestBody
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.bind.annotation.RequestParam
import org.springframework.web.bind.annotation.RestController
import org.springframework.web.server.ServerWebExchange
import reactor.core.publisher.Mono
@Validated
@RestController
@RequestMapping("/api/auth")
@RequestMapping("/api/v1/auth")
class AuthorizeController(
private val service: AccountService
private val service: AuthorizationService
) {
private val logger = LoggerFactory.getLogger(this::class.java)
@@ -27,7 +32,7 @@ class AuthorizeController(
@RequestParam @NotBlank @Email email: String,
@RequestParam @Pattern(regexp = "(register|reset)") type: String,
exchange: ServerWebExchange
): Mono<RestBean<Any?>> {
): Mono<ApiResponse<Any?>> {
logger.info("Trying to ask code")
val ip = exchange.request.remoteAddress?.address?.hostAddress ?: "unknown"
return service.askEmailVerifyCode(type, email, ip)
@@ -35,45 +40,45 @@ class AuthorizeController(
}
@PostMapping("/register")
fun emailRegister(@RequestBody @Valid vo: EmailRegisterVO): Mono<RestBean<Any?>> {
fun emailRegister(@RequestBody @Valid vo: EmailRegisterVO): Mono<ApiResponse<Any?>> {
logger.info("Trying to register")
return service.registerEmailAccount(vo)
.map { messageHandler(it) }
}
@PostMapping("/reset")
fun emailResetPassword(@RequestBody @Valid vo: PasswordResetVO): Mono<RestBean<Any?>> {
fun emailResetPassword(@RequestBody @Valid vo: PasswordResetVO): Mono<ApiResponse<Any?>> {
logger.info("Trying to reset password")
return service.resetEmailAccountPassword(vo)
.map { messageHandler(it) }
}
@GetMapping("/logout")
fun logout(exchange: ServerWebExchange): Mono<RestBean<Any?>> {
fun logout(exchange: ServerWebExchange): Mono<ApiResponse<Any?>> {
logger.info("Trying to logout")
val authorization = exchange.request.headers.getFirst("Authorization")
return Mono.fromCallable { service.invalidateJwt(authorization) }
.map { success ->
if (success) RestBean.success()
else RestBean.logoutFailed()
if (success) ApiResponse.success()
else ApiResponse.logoutFailed()
}
}
@GetMapping("/relogin")
fun relogin(exchange: ServerWebExchange): Mono<RestBean<Any?>> {
fun relogin(exchange: ServerWebExchange): Mono<ApiResponse<Any?>> {
logger.info("Trying to relogin")
val authorization = exchange.request.headers.getFirst("Authorization")
return service
.jwtTokenRelogin(authorization)
?.map { RestBean.success(it) }
?.map { ApiResponse.success(it) }
?: Mono.just(messageHandler("Please login with password."))
}
private fun messageHandler(wrongMessage: String): RestBean<Any?> {
private fun messageHandler(wrongMessage: String): ApiResponse<Any?> {
return if (wrongMessage.isBlank()) {
RestBean.success()
ApiResponse.success()
} else {
RestBean.failure(400, null, wrongMessage)
ApiResponse.failure(400, null, wrongMessage)
}
}
}
@@ -4,23 +4,23 @@ import kotlinx.serialization.Serializable
import kotlinx.serialization.json.Json
@Serializable
data class RestBean<T>(
data class ApiResponse<T>(
val code: Int,
val data: T,
val message: String
) {
companion object {
fun <T> success(data: T, message: String = "Success"): RestBean<T> {
return RestBean(200, data, message)
fun <T> success(data: T, message: String = "Success"): ApiResponse<T> {
return ApiResponse(200, data, message)
}
// 针对无 data 返回的情况,统一使用 Any?
fun success(message: String = "Success"): RestBean<Any?> {
return RestBean(200, null, message)
fun success(message: String = "Success"): ApiResponse<Any?> {
return ApiResponse(200, null, message)
}
fun <T> failure(code: Int = 401, data: T, message: String?): RestBean<T> {
return RestBean(code, data, message ?: "Failure")
fun <T> failure(code: Int = 401, data: T, message: String?): ApiResponse<T> {
return ApiResponse(code, data, message ?: "Failure")
}
fun unauthenticated(message: String?) =
@@ -29,13 +29,13 @@ data class RestBean<T>(
fun forbidden(message: String?) =
failure(403, null, message)
fun logoutFailed(message: String = ""): RestBean<Any?> {
fun logoutFailed(message: String = ""): ApiResponse<Any?> {
val formatMessage = if (message.isBlank()) "" else ": $message"
return failure(400, null, "Logout Failed$formatMessage")
}
}
}
inline fun <reified T> RestBean<T>.toJsonString(): String {
inline fun <reified T> ApiResponse<T>.toJsonString(): String {
return Json.encodeToString(this)
}
@@ -1,6 +1,6 @@
package com.github.sor2171.backend.exception
import com.github.sor2171.backend.entity.RestBean
import com.github.sor2171.backend.entity.ApiResponse
import jakarta.validation.ValidationException
import org.slf4j.LoggerFactory
import org.springframework.web.bind.annotation.ExceptionHandler
@@ -12,9 +12,9 @@ class ValidationController {
private val log = LoggerFactory.getLogger(ValidationController::class.java)
@ExceptionHandler(ValidationException::class)
fun validationException(e: Exception): RestBean<out String?> {
fun validationException(e: Exception): ApiResponse<out String?> {
log.warn("Resolve [${e.javaClass.name}: ${e.message}]")
return RestBean.failure(
return ApiResponse.failure(
400,
null,
"parameter validation error"
@@ -1,6 +1,6 @@
package com.github.sor2171.backend.filter
import com.github.sor2171.backend.entity.RestBean
import com.github.sor2171.backend.entity.ApiResponse
import com.github.sor2171.backend.entity.toJsonString
import com.github.sor2171.backend.utils.Const
import org.springframework.core.annotation.Order
@@ -37,7 +37,7 @@ class FlowLimitFilter(
response.statusCode = HttpStatus.FORBIDDEN
response.headers.contentType = MediaType.APPLICATION_JSON
val buffer = response.bufferFactory()
.wrap(RestBean.forbidden("Too many requests").toJsonString().toByteArray())
.wrap(ApiResponse.forbidden("Too many requests").toJsonString().toByteArray())
return response.writeWith(Mono.just(buffer))
}
@@ -0,0 +1,20 @@
package com.github.sor2171.backend.handler
import org.springframework.stereotype.Component
import org.springframework.web.reactive.socket.WebSocketHandler
import org.springframework.web.reactive.socket.WebSocketSession
import reactor.core.publisher.Mono
@Component
class TestHandler : WebSocketHandler {
override fun handle(session: WebSocketSession): Mono<Void> {
// ws://localhost:8080/ws/test
val output = session.receive()
.map { msg ->
val userText = msg.payloadAsText
session.textMessage("Kotlin springboot4 received: $userText")
}
return session.send(output)
}
}
@@ -0,0 +1,20 @@
package com.github.sor2171.backend.handler.v1
import org.springframework.stereotype.Component
import org.springframework.web.reactive.socket.WebSocketHandler
import org.springframework.web.reactive.socket.WebSocketSession
import reactor.core.publisher.Mono
@Component
class ExampleHandler : WebSocketHandler {
override fun handle(session: WebSocketSession): Mono<Void> {
// ws://localhost:8080/ws/v1/example
val output = session.receive()
.map { msg ->
val userText = msg.payloadAsText
session.textMessage("Kotlin springboot4 received: $userText")
}
return session.send(output)
}
}
@@ -2,17 +2,14 @@ package com.github.sor2171.backend.service
import com.baomidou.mybatisplus.extension.service.IService
import com.github.sor2171.backend.entity.dto.Account
import com.github.sor2171.backend.entity.vo.request.EmailRegisterVO
import com.github.sor2171.backend.entity.vo.request.PasswordResetVO
import com.github.sor2171.backend.entity.vo.response.ReloginVO
import org.springframework.security.core.userdetails.ReactiveUserDetailsService
import reactor.core.publisher.Mono
interface AccountService : IService<Account>, ReactiveUserDetailsService {
fun findAccountByNameOrEmail(text: String): Mono<Account>
fun askEmailVerifyCode(type: String, email: String, ip: String): Mono<String>
fun registerEmailAccount(vo: EmailRegisterVO): Mono<String>
fun resetEmailAccountPassword(vo: PasswordResetVO): Mono<String>
fun invalidateJwt(headerToken: String?): Boolean
fun jwtTokenRelogin(headerToken: String?): Mono<ReloginVO>?
fun findAccountByName(username: String): Mono<Account>
fun findAccountByEmail(email: String): Mono<Account>
fun existAccountByName(username: String): Mono<Boolean>
fun existAccountByEmail(email: String): Mono<Boolean>
fun resetPasswordByEmail(email: String, encodedPassword: String): Mono<String>
}
@@ -1,41 +1,23 @@
package com.github.sor2171.backend.service.impl
import com.baomidou.mybatisplus.core.toolkit.Wrappers
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl
import com.github.sor2171.backend.entity.dto.Account
import com.github.sor2171.backend.entity.dto.EmailVerificationMsg
import com.github.sor2171.backend.entity.vo.request.EmailRegisterVO
import com.github.sor2171.backend.entity.vo.request.PasswordResetVO
import com.github.sor2171.backend.entity.vo.response.ReloginVO
import com.github.sor2171.backend.mapper.AccountMapper
import com.github.sor2171.backend.service.AccountService
import com.github.sor2171.backend.utils.Const
import com.github.sor2171.backend.utils.DateUtils.getCurrentDateTime
import com.github.sor2171.backend.utils.FlowUtils
import com.github.sor2171.backend.utils.JwtUtils
import org.springframework.amqp.core.AmqpTemplate
import org.springframework.data.redis.core.ReactiveStringRedisTemplate
import org.slf4j.LoggerFactory
import org.springframework.security.core.userdetails.User
import org.springframework.security.core.userdetails.UserDetails
import org.springframework.security.core.userdetails.UsernameNotFoundException
import org.springframework.security.crypto.password.PasswordEncoder
import org.springframework.stereotype.Service
import reactor.core.publisher.Mono
import reactor.core.scheduler.Schedulers
import java.time.Duration
@Service
class AccountServiceImpl(
private val utils: FlowUtils,
private val jwtUtils: JwtUtils,
private val amqpTemplate: AmqpTemplate,
private val stringRedisTemplate: ReactiveStringRedisTemplate,
private val encoder: PasswordEncoder
class AccountServiceImpl : ServiceImpl<AccountMapper, Account>(), AccountService {
) : ServiceImpl<AccountMapper, Account>(), AccountService {
val logger = LoggerFactory.getLogger(this::class.java)!!
override fun findByUsername(username: String): Mono<UserDetails> {
return findAccountByNameOrEmail(username)
return findAccountByName(username)
.switchIfEmpty(Mono.error(UsernameNotFoundException("Account with name $username not found")))
.map { account ->
User.withUsername(username)
@@ -45,165 +27,70 @@ class AccountServiceImpl(
}
}
override fun findAccountByNameOrEmail(text: String): Mono<Account> {
override fun findAccountByName(username: String): Mono<Account> {
return Mono.fromCallable {
this.query()
.eq("username", text).or()
.eq("email", text)
logger.info("Find account with name $username")
this.ktQuery()
.eq(Account::username, username)
.one()
}.flatMap { account ->
Mono.just(account)
}
}.switchIfEmpty(Mono.error(UsernameNotFoundException("Account with name $username not found")))
}
override fun askEmailVerifyCode(type: String, email: String, ip: String): Mono<String> {
return verifyLimit(ip).flatMap { allowed ->
if (allowed) {
val code = (100000..999999).random().toString()
val data = EmailVerificationMsg(email, type, code)
Mono.fromRunnable<Void> {
amqpTemplate.convertAndSend("mail", data)
}.then(
stringRedisTemplate.opsForValue()
.set(
Const.VERIFY_EMAIL_DATA + email,
code,
Duration.ofMinutes(3)
)
).thenReturn("").subscribeOn(Schedulers.boundedElastic())
} else {
Mono.just("Request limit exceeded. Please try again later.")
}
}
}
override fun registerEmailAccount(vo: EmailRegisterVO): Mono<String> {
val (email, code, username, password) = vo
return verifyCode(email, code).flatMap { error ->
if (!error.isBlank()) {
return@flatMap Mono.just(error)
}
existAccountByEmail(email).flatMap { emailExists ->
if (emailExists) {
return@flatMap Mono.just("account with the same email already exists.")
}
existAccountByUsername(username).flatMap { usernameExists ->
if (usernameExists) {
return@flatMap Mono.just("username already exists.")
}
val encodedPassword = encoder.encode(password)
val account = Account(
null,
username,
encodedPassword!!,
email,
"user",
getCurrentDateTime()
)
Mono.fromCallable { this.save(account) }
.flatMap { success ->
if (success) {
stringRedisTemplate.delete(Const.VERIFY_EMAIL_DATA + email)
.thenReturn("")
} else {
Mono.just("something went wrong. Please contact the administrator.")
}
}
}
}
}
}
override fun resetEmailAccountPassword(vo: PasswordResetVO): Mono<String> {
val (email, code, password) = vo
return verifyCode(email, code).flatMap { error ->
if (!error.isBlank()) {
return@flatMap Mono.just(error)
}
existAccountByEmail(email).flatMap { exists ->
if (!exists) {
return@flatMap Mono.just("account with the email does not exist.")
}
val encodedPassword = encoder.encode(password)
Mono.fromCallable {
this.update()
.eq("email", email)
.set("password", encodedPassword)
.update()
}.flatMap { success ->
if (success) {
stringRedisTemplate.delete(Const.VERIFY_EMAIL_DATA + email)
.thenReturn("")
} else {
Mono.just("something went wrong. Please contact the administrator.")
}
}
}
}
}
override fun jwtTokenRelogin(headerToken: String?): Mono<ReloginVO>? {
val user = jwtUtils.resolveJwt(headerToken?.substring("Bearer ".length))
?.let { jwtUtils.toUser(it) }
?: return null
val accountMono = findAccountByNameOrEmail(user.username)
val voMono = accountMono.map {
ReloginVO(
jwtUtils.createJwt(user, it.id!!, it.username),
jwtUtils.expiresTime().toInstant().toString()
)
}
return voMono
}
override fun invalidateJwt(headerToken: String?): Boolean {
return jwtUtils.invalidateJwt(headerToken)
}
private fun existAccountByEmail(email: String): Mono<Boolean> {
override fun findAccountByEmail(email: String): Mono<Account> {
return Mono.fromCallable {
this.baseMapper.exists(
Wrappers.query<Account>()
.eq("email", email)
)
}
logger.info("Find account with email $email")
this.ktQuery()
.eq(Account::email, email)
.one()
}.flatMap { account ->
Mono.just(account)
}.switchIfEmpty(Mono.error(UsernameNotFoundException("Account with email $email not found")))
}
private fun existAccountByUsername(username: String): Mono<Boolean> {
override fun findAccountByNameOrEmail(text: String): Mono<Account> {
return findAccountByEmail(text)
.onErrorResume { findAccountByName(text) }
}
override fun existAccountByName(username: String): Mono<Boolean> {
return Mono.fromCallable {
this.baseMapper.exists(
Wrappers.query<Account>()
.eq("username", username)
)
logger.info("Determine if name $username exists")
this.ktQuery()
.eq(Account::username, username)
.exists()
}
}
private fun verifyLimit(ip: String): Mono<Boolean> {
val key = Const.VERIFY_EMAIL_LIMIT + ip
return utils.limitOnceCheck(key, 60)
override fun existAccountByEmail(email: String): Mono<Boolean> {
return Mono.fromCallable {
logger.info("Determine if email $email exists")
this.ktQuery()
.eq(Account::email, email)
.exists()
}
}
private fun verifyCode(email: String, receivedCode: String?): Mono<String> {
return stringRedisTemplate.opsForValue()
.get(Const.VERIFY_EMAIL_DATA + email)
.flatMap { code ->
when {
receivedCode == null || code != receivedCode ->
Mono.just("verify code is wrong.")
override fun resetPasswordByEmail(email: String, encodedPassword: String): Mono<String> {
return existAccountByEmail(email).flatMap { exists ->
if (!exists) {
return@flatMap Mono.just("account with the email does not exist.")
}
else -> Mono.just("")
Mono.fromCallable {
logger.info("Reset password by email $email")
this.ktUpdate()
.eq(Account::email, email)
.set(Account::password, encodedPassword)
.update()
}.flatMap { success ->
if (success) {
Mono.just("")
} else {
Mono.just("something went wrong. Please contact the administrator.")
}
}
.switchIfEmpty(Mono.just("verify code has not been sent"))
}
}
}
@@ -0,0 +1,156 @@
package com.github.sor2171.backend.service.v1
import com.github.sor2171.backend.entity.dto.Account
import com.github.sor2171.backend.entity.dto.EmailVerificationMsg
import com.github.sor2171.backend.entity.vo.request.EmailRegisterVO
import com.github.sor2171.backend.entity.vo.request.PasswordResetVO
import com.github.sor2171.backend.entity.vo.response.ReloginVO
import com.github.sor2171.backend.service.AccountService
import com.github.sor2171.backend.utils.Const
import com.github.sor2171.backend.utils.DateUtils.getCurrentDateTime
import com.github.sor2171.backend.utils.FlowUtils
import com.github.sor2171.backend.utils.JwtUtils
import org.springframework.amqp.core.AmqpTemplate
import org.springframework.data.redis.core.ReactiveStringRedisTemplate
import org.springframework.security.crypto.password.PasswordEncoder
import org.springframework.stereotype.Service
import reactor.core.publisher.Mono
import reactor.core.scheduler.Schedulers
import java.time.Duration
@Service
class AuthorizationService(
private val accountService: AccountService,
private val utils: FlowUtils,
private val jwtUtils: JwtUtils,
private val amqpTemplate: AmqpTemplate,
private val stringRedisTemplate: ReactiveStringRedisTemplate,
private val encoder: PasswordEncoder
) {
fun askEmailVerifyCode(type: String, email: String, ip: String): Mono<String> {
return verifyLimit(ip).flatMap { allowed ->
if (allowed) {
val code = (100000..999999).random().toString()
val data = EmailVerificationMsg(email, type, code)
Mono.fromRunnable<Void> {
amqpTemplate.convertAndSend("mail", data)
}.then(
stringRedisTemplate.opsForValue()
.set(
Const.VERIFY_EMAIL_DATA + email,
code,
Duration.ofMinutes(3)
)
).thenReturn("").subscribeOn(Schedulers.boundedElastic())
} else {
Mono.just("Request limit exceeded. Please try again later.")
}
}
}
fun registerEmailAccount(vo: EmailRegisterVO): Mono<String> {
val (email, code, username, password) = vo
return verifyCode(email, code).flatMap { error ->
if (!error.isBlank()) {
return@flatMap Mono.just(error)
}
accountService
.existAccountByEmail(email)
.flatMap { emailExists ->
if (emailExists) {
return@flatMap Mono.just("account with the same email already exists.")
}
accountService
.existAccountByName(username)
.flatMap { usernameExists ->
if (usernameExists) {
return@flatMap Mono.just("username already exists.")
}
val encodedPassword = encoder.encode(password)
val account = Account(
null,
username,
encodedPassword!!,
email,
"user",
getCurrentDateTime()
)
Mono.fromCallable { accountService.save(account) }
.flatMap { success ->
if (success) {
stringRedisTemplate.delete(Const.VERIFY_EMAIL_DATA + email)
.thenReturn("")
} else {
Const.INTERNAL_ERROR_MONO
}
}
}
}
}
}
fun resetEmailAccountPassword(vo: PasswordResetVO): Mono<String> {
val (email, code, password) = vo
return verifyCode(email, code).flatMap { error ->
if (!error.isBlank()) {
return@flatMap Mono.just(error)
} else {
val encodedPassword = encoder.encode(password)
?: return@flatMap Const.INTERNAL_ERROR_MONO
return@flatMap accountService
.resetPasswordByEmail(email, encodedPassword)
.flatMap { text ->
if (text.isBlank()) {
stringRedisTemplate
.delete(Const.VERIFY_EMAIL_DATA + email)
.then(Mono.just(text))
} else Mono.just(text)
}
}
}
}
fun jwtTokenRelogin(headerToken: String?): Mono<ReloginVO>? {
val user = jwtUtils.resolveJwt(headerToken?.substring("Bearer ".length))
?.let { jwtUtils.toUser(it) }
?: return null
val accountMono = accountService.findAccountByName(user.username)
val voMono = accountMono.map {
ReloginVO(
jwtUtils.createJwt(user, it.id!!, it.username),
jwtUtils.expiresTime().toInstant().toString()
)
}
return voMono
}
fun invalidateJwt(headerToken: String?): Boolean {
return jwtUtils.invalidateJwt(headerToken)
}
private fun verifyLimit(ip: String): Mono<Boolean> {
val key = Const.VERIFY_EMAIL_LIMIT + ip
return utils.limitOnceCheck(key, 60)
}
private fun verifyCode(email: String, receivedCode: String?): Mono<String> {
return stringRedisTemplate.opsForValue()
.get(Const.VERIFY_EMAIL_DATA + email)
.flatMap { code ->
when {
receivedCode == null || code != receivedCode ->
Mono.just("verify code is wrong.")
else -> Mono.just("")
}
}
.switchIfEmpty(Mono.just("verify code has not been sent"))
}
}
@@ -1,5 +1,7 @@
package com.github.sor2171.backend.utils
import reactor.core.publisher.Mono
object Const {
const val FLOW_LIMIT_ORDER = -101
@@ -9,4 +11,6 @@ object Const {
const val FLOW_LIMIT_COUNTER = "flow:counter:"
const val FLOW_LIMIT_BLOCK = "flow:block:"
val INTERNAL_ERROR_MONO = Mono.just("something went wrong. Please contact the administrator.")
}
@@ -27,9 +27,6 @@ spring:
jwt:
#key: 123456
expire-hours: 168
ip-ban-limit: 10
ip-ban-time: 3
ip-ban-time-min: 1
datasource:
url: jdbc:mysql://localhost:3306/kotlin_springboot