mirror of
https://github.com/SOR2171/Springboot4-Vue3_Demo.git
synced 2026-10-23 19:41:12 +08:00
feat: websocket support
This commit is contained in:
Generated
+1
@@ -1,5 +1,6 @@
|
|||||||
<?xml version="1.0" encoding="UTF-8"?>
|
<?xml version="1.0" encoding="UTF-8"?>
|
||||||
<project version="4">
|
<project version="4">
|
||||||
|
<component name="GradleMigrationSettings" migrationVersion="1" />
|
||||||
<component name="GradleSettings">
|
<component name="GradleSettings">
|
||||||
<option name="linkedExternalProjectsSettings">
|
<option name="linkedExternalProjectsSettings">
|
||||||
<GradleProjectSettings>
|
<GradleProjectSettings>
|
||||||
|
|||||||
Generated
+3
@@ -1,6 +1,9 @@
|
|||||||
<?xml version="1.0" encoding="UTF-8"?>
|
<?xml version="1.0" encoding="UTF-8"?>
|
||||||
<project version="4">
|
<project version="4">
|
||||||
<component name="ExternalStorageConfigurationManager" enabled="true" />
|
<component name="ExternalStorageConfigurationManager" enabled="true" />
|
||||||
|
<component name="FrameworkDetectionExcludesConfiguration">
|
||||||
|
<file type="web" url="file://$PROJECT_DIR$/backend" />
|
||||||
|
</component>
|
||||||
<component name="ProjectRootManager" version="2">
|
<component name="ProjectRootManager" version="2">
|
||||||
<output url="file://$PROJECT_DIR$/out" />
|
<output url="file://$PROJECT_DIR$/out" />
|
||||||
</component>
|
</component>
|
||||||
|
|||||||
Generated
+1
@@ -2,5 +2,6 @@
|
|||||||
<project version="4">
|
<project version="4">
|
||||||
<component name="VcsDirectoryMappings">
|
<component name="VcsDirectoryMappings">
|
||||||
<mapping directory="" vcs="Git" />
|
<mapping directory="" vcs="Git" />
|
||||||
|
<mapping directory="$PROJECT_DIR$/ItStudio-CareerPlanningPlatform" vcs="Git" />
|
||||||
</component>
|
</component>
|
||||||
</project>
|
</project>
|
||||||
@@ -30,7 +30,6 @@ dependencies {
|
|||||||
implementation("org.springframework.boot:spring-boot-starter-validation")
|
implementation("org.springframework.boot:spring-boot-starter-validation")
|
||||||
implementation("org.springframework.boot:spring-boot-starter-webflux")
|
implementation("org.springframework.boot:spring-boot-starter-webflux")
|
||||||
implementation("org.springframework:spring-messaging")
|
implementation("org.springframework:spring-messaging")
|
||||||
implementation("io.projectreactor.kotlin:reactor-kotlin-extensions")
|
|
||||||
implementation("org.jetbrains.kotlin:kotlin-reflect")
|
implementation("org.jetbrains.kotlin:kotlin-reflect")
|
||||||
implementation("org.jetbrains.kotlinx:kotlinx-coroutines-reactor")
|
implementation("org.jetbrains.kotlinx:kotlinx-coroutines-reactor")
|
||||||
implementation("org.jetbrains.kotlinx:kotlinx-datetime:0.6.0")
|
implementation("org.jetbrains.kotlinx:kotlinx-datetime:0.6.0")
|
||||||
|
|||||||
+2
-2
@@ -4,8 +4,8 @@ import org.springframework.boot.autoconfigure.SpringBootApplication
|
|||||||
import org.springframework.boot.runApplication
|
import org.springframework.boot.runApplication
|
||||||
|
|
||||||
@SpringBootApplication
|
@SpringBootApplication
|
||||||
class CareerppApplication
|
class BackendApplication
|
||||||
|
|
||||||
fun main(args: Array<String>) {
|
fun main(args: Array<String>) {
|
||||||
runApplication<CareerppApplication>(*args)
|
runApplication<BackendApplication>(*args)
|
||||||
}
|
}
|
||||||
@@ -1,6 +1,6 @@
|
|||||||
package com.github.sor2171.backend.config
|
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.entity.vo.response.AuthorizeVO
|
||||||
import com.github.sor2171.backend.filter.JwtAuthorizeFilter
|
import com.github.sor2171.backend.filter.JwtAuthorizeFilter
|
||||||
import com.github.sor2171.backend.service.AccountService
|
import com.github.sor2171.backend.service.AccountService
|
||||||
@@ -50,13 +50,15 @@ class SecurityConfig(
|
|||||||
.authorizeExchange {
|
.authorizeExchange {
|
||||||
it
|
it
|
||||||
.pathMatchers(
|
.pathMatchers(
|
||||||
"/api/auth/relogin"
|
"/api/v1/auth/relogin"
|
||||||
).authenticated()
|
).authenticated()
|
||||||
.pathMatchers(
|
.pathMatchers(
|
||||||
"/api/auth/**",
|
"/api/v1/auth/**",
|
||||||
|
"/ws/**",
|
||||||
"/error"
|
"/error"
|
||||||
).permitAll()
|
).permitAll()
|
||||||
.anyExchange().authenticated()
|
.anyExchange()
|
||||||
|
.authenticated()
|
||||||
}
|
}
|
||||||
.addFilterAt(loginAuthenticationFilter(), SecurityWebFiltersOrder.AUTHENTICATION)
|
.addFilterAt(loginAuthenticationFilter(), SecurityWebFiltersOrder.AUTHENTICATION)
|
||||||
.addFilterAt(jwtAuthorizeFilter, SecurityWebFiltersOrder.AUTHENTICATION)
|
.addFilterAt(jwtAuthorizeFilter, SecurityWebFiltersOrder.AUTHENTICATION)
|
||||||
@@ -65,14 +67,14 @@ class SecurityConfig(
|
|||||||
writeJsonResponse(
|
writeJsonResponse(
|
||||||
exchange,
|
exchange,
|
||||||
HttpStatus.UNAUTHORIZED,
|
HttpStatus.UNAUTHORIZED,
|
||||||
RestBean.unauthenticated(ex.message)
|
ApiResponse.unauthenticated(ex.message)
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
.accessDeniedHandler { exchange, ex ->
|
.accessDeniedHandler { exchange, ex ->
|
||||||
writeJsonResponse(
|
writeJsonResponse(
|
||||||
exchange,
|
exchange,
|
||||||
HttpStatus.FORBIDDEN,
|
HttpStatus.FORBIDDEN,
|
||||||
RestBean.forbidden(ex.message)
|
ApiResponse.forbidden(ex.message)
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -85,7 +87,7 @@ class SecurityConfig(
|
|||||||
fun loginAuthenticationFilter(): AuthenticationWebFilter {
|
fun loginAuthenticationFilter(): AuthenticationWebFilter {
|
||||||
val filter = AuthenticationWebFilter(reactiveAuthenticationManager())
|
val filter = AuthenticationWebFilter(reactiveAuthenticationManager())
|
||||||
filter.setRequiresAuthenticationMatcher(
|
filter.setRequiresAuthenticationMatcher(
|
||||||
ServerWebExchangeMatchers.pathMatchers("/api/auth/login")
|
ServerWebExchangeMatchers.pathMatchers("/api/v1/auth/login")
|
||||||
)
|
)
|
||||||
filter.setServerAuthenticationConverter(loginAuthenticationConverter())
|
filter.setServerAuthenticationConverter(loginAuthenticationConverter())
|
||||||
filter.setAuthenticationSuccessHandler { webFilterExchange, authentication ->
|
filter.setAuthenticationSuccessHandler { webFilterExchange, authentication ->
|
||||||
@@ -102,7 +104,7 @@ class SecurityConfig(
|
|||||||
writeJsonResponse(
|
writeJsonResponse(
|
||||||
webFilterExchange.exchange,
|
webFilterExchange.exchange,
|
||||||
HttpStatus.OK,
|
HttpStatus.OK,
|
||||||
RestBean.success(vo)
|
ApiResponse.success(vo)
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -110,7 +112,7 @@ class SecurityConfig(
|
|||||||
writeJsonResponse(
|
writeJsonResponse(
|
||||||
webFilterExchange.exchange,
|
webFilterExchange.exchange,
|
||||||
HttpStatus.UNAUTHORIZED,
|
HttpStatus.UNAUTHORIZED,
|
||||||
RestBean.unauthenticated(exception.message)
|
ApiResponse.unauthenticated(exception.message)
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
return filter
|
return filter
|
||||||
@@ -134,18 +136,18 @@ class SecurityConfig(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
|
||||||
internal inline fun <reified T> writeJsonResponse(
|
private inline fun <reified T> writeJsonResponse(
|
||||||
exchange: ServerWebExchange,
|
exchange: ServerWebExchange,
|
||||||
status: HttpStatus,
|
status: HttpStatus,
|
||||||
body: RestBean<T>
|
body: ApiResponse<T>
|
||||||
): Mono<Void> {
|
): Mono<Void> {
|
||||||
val response = exchange.response
|
val response = exchange.response
|
||||||
response.statusCode = status
|
response.statusCode = status
|
||||||
response.headers.contentType = MediaType.APPLICATION_JSON
|
response.headers.contentType = MediaType.APPLICATION_JSON
|
||||||
|
|
||||||
val jsonString = Json.encodeToJsonElement(body).toString()
|
val jsonString = Json.encodeToJsonElement(body).toString()
|
||||||
val buffer = response.bufferFactory().wrap(jsonString.toByteArray())
|
val buffer = response.bufferFactory().wrap(jsonString.toByteArray())
|
||||||
return response.writeWith(Mono.just(buffer))
|
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()
|
||||||
|
}
|
||||||
+22
-17
@@ -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.EmailRegisterVO
|
||||||
import com.github.sor2171.backend.entity.vo.request.PasswordResetVO
|
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.Valid
|
||||||
import jakarta.validation.constraints.Email
|
import jakarta.validation.constraints.Email
|
||||||
import jakarta.validation.constraints.NotBlank
|
import jakarta.validation.constraints.NotBlank
|
||||||
import jakarta.validation.constraints.Pattern
|
import jakarta.validation.constraints.Pattern
|
||||||
import org.slf4j.LoggerFactory
|
import org.slf4j.LoggerFactory
|
||||||
import org.springframework.validation.annotation.Validated
|
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 org.springframework.web.server.ServerWebExchange
|
||||||
import reactor.core.publisher.Mono
|
import reactor.core.publisher.Mono
|
||||||
|
|
||||||
@Validated
|
@Validated
|
||||||
@RestController
|
@RestController
|
||||||
@RequestMapping("/api/auth")
|
@RequestMapping("/api/v1/auth")
|
||||||
class AuthorizeController(
|
class AuthorizeController(
|
||||||
private val service: AccountService
|
private val service: AuthorizationService
|
||||||
) {
|
) {
|
||||||
private val logger = LoggerFactory.getLogger(this::class.java)
|
private val logger = LoggerFactory.getLogger(this::class.java)
|
||||||
|
|
||||||
@@ -27,7 +32,7 @@ class AuthorizeController(
|
|||||||
@RequestParam @NotBlank @Email email: String,
|
@RequestParam @NotBlank @Email email: String,
|
||||||
@RequestParam @Pattern(regexp = "(register|reset)") type: String,
|
@RequestParam @Pattern(regexp = "(register|reset)") type: String,
|
||||||
exchange: ServerWebExchange
|
exchange: ServerWebExchange
|
||||||
): Mono<RestBean<Any?>> {
|
): Mono<ApiResponse<Any?>> {
|
||||||
logger.info("Trying to ask code")
|
logger.info("Trying to ask code")
|
||||||
val ip = exchange.request.remoteAddress?.address?.hostAddress ?: "unknown"
|
val ip = exchange.request.remoteAddress?.address?.hostAddress ?: "unknown"
|
||||||
return service.askEmailVerifyCode(type, email, ip)
|
return service.askEmailVerifyCode(type, email, ip)
|
||||||
@@ -35,45 +40,45 @@ class AuthorizeController(
|
|||||||
}
|
}
|
||||||
|
|
||||||
@PostMapping("/register")
|
@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")
|
logger.info("Trying to register")
|
||||||
return service.registerEmailAccount(vo)
|
return service.registerEmailAccount(vo)
|
||||||
.map { messageHandler(it) }
|
.map { messageHandler(it) }
|
||||||
}
|
}
|
||||||
|
|
||||||
@PostMapping("/reset")
|
@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")
|
logger.info("Trying to reset password")
|
||||||
return service.resetEmailAccountPassword(vo)
|
return service.resetEmailAccountPassword(vo)
|
||||||
.map { messageHandler(it) }
|
.map { messageHandler(it) }
|
||||||
}
|
}
|
||||||
|
|
||||||
@GetMapping("/logout")
|
@GetMapping("/logout")
|
||||||
fun logout(exchange: ServerWebExchange): Mono<RestBean<Any?>> {
|
fun logout(exchange: ServerWebExchange): Mono<ApiResponse<Any?>> {
|
||||||
logger.info("Trying to logout")
|
logger.info("Trying to logout")
|
||||||
val authorization = exchange.request.headers.getFirst("Authorization")
|
val authorization = exchange.request.headers.getFirst("Authorization")
|
||||||
return Mono.fromCallable { service.invalidateJwt(authorization) }
|
return Mono.fromCallable { service.invalidateJwt(authorization) }
|
||||||
.map { success ->
|
.map { success ->
|
||||||
if (success) RestBean.success()
|
if (success) ApiResponse.success()
|
||||||
else RestBean.logoutFailed()
|
else ApiResponse.logoutFailed()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@GetMapping("/relogin")
|
@GetMapping("/relogin")
|
||||||
fun relogin(exchange: ServerWebExchange): Mono<RestBean<Any?>> {
|
fun relogin(exchange: ServerWebExchange): Mono<ApiResponse<Any?>> {
|
||||||
logger.info("Trying to relogin")
|
logger.info("Trying to relogin")
|
||||||
val authorization = exchange.request.headers.getFirst("Authorization")
|
val authorization = exchange.request.headers.getFirst("Authorization")
|
||||||
return service
|
return service
|
||||||
.jwtTokenRelogin(authorization)
|
.jwtTokenRelogin(authorization)
|
||||||
?.map { RestBean.success(it) }
|
?.map { ApiResponse.success(it) }
|
||||||
?: Mono.just(messageHandler("Please login with password."))
|
?: 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()) {
|
return if (wrongMessage.isBlank()) {
|
||||||
RestBean.success()
|
ApiResponse.success()
|
||||||
} else {
|
} else {
|
||||||
RestBean.failure(400, null, wrongMessage)
|
ApiResponse.failure(400, null, wrongMessage)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
+9
-9
@@ -4,23 +4,23 @@ import kotlinx.serialization.Serializable
|
|||||||
import kotlinx.serialization.json.Json
|
import kotlinx.serialization.json.Json
|
||||||
|
|
||||||
@Serializable
|
@Serializable
|
||||||
data class RestBean<T>(
|
data class ApiResponse<T>(
|
||||||
val code: Int,
|
val code: Int,
|
||||||
val data: T,
|
val data: T,
|
||||||
val message: String
|
val message: String
|
||||||
) {
|
) {
|
||||||
companion object {
|
companion object {
|
||||||
fun <T> success(data: T, message: String = "Success"): RestBean<T> {
|
fun <T> success(data: T, message: String = "Success"): ApiResponse<T> {
|
||||||
return RestBean(200, data, message)
|
return ApiResponse(200, data, message)
|
||||||
}
|
}
|
||||||
|
|
||||||
// 针对无 data 返回的情况,统一使用 Any?
|
// 针对无 data 返回的情况,统一使用 Any?
|
||||||
fun success(message: String = "Success"): RestBean<Any?> {
|
fun success(message: String = "Success"): ApiResponse<Any?> {
|
||||||
return RestBean(200, null, message)
|
return ApiResponse(200, null, message)
|
||||||
}
|
}
|
||||||
|
|
||||||
fun <T> failure(code: Int = 401, data: T, message: String?): RestBean<T> {
|
fun <T> failure(code: Int = 401, data: T, message: String?): ApiResponse<T> {
|
||||||
return RestBean(code, data, message ?: "Failure")
|
return ApiResponse(code, data, message ?: "Failure")
|
||||||
}
|
}
|
||||||
|
|
||||||
fun unauthenticated(message: String?) =
|
fun unauthenticated(message: String?) =
|
||||||
@@ -29,13 +29,13 @@ data class RestBean<T>(
|
|||||||
fun forbidden(message: String?) =
|
fun forbidden(message: String?) =
|
||||||
failure(403, null, message)
|
failure(403, null, message)
|
||||||
|
|
||||||
fun logoutFailed(message: String = ""): RestBean<Any?> {
|
fun logoutFailed(message: String = ""): ApiResponse<Any?> {
|
||||||
val formatMessage = if (message.isBlank()) "" else ": $message"
|
val formatMessage = if (message.isBlank()) "" else ": $message"
|
||||||
return failure(400, null, "Logout Failed$formatMessage")
|
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)
|
return Json.encodeToString(this)
|
||||||
}
|
}
|
||||||
+3
-3
@@ -1,6 +1,6 @@
|
|||||||
package com.github.sor2171.backend.exception
|
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 jakarta.validation.ValidationException
|
||||||
import org.slf4j.LoggerFactory
|
import org.slf4j.LoggerFactory
|
||||||
import org.springframework.web.bind.annotation.ExceptionHandler
|
import org.springframework.web.bind.annotation.ExceptionHandler
|
||||||
@@ -12,9 +12,9 @@ class ValidationController {
|
|||||||
private val log = LoggerFactory.getLogger(ValidationController::class.java)
|
private val log = LoggerFactory.getLogger(ValidationController::class.java)
|
||||||
|
|
||||||
@ExceptionHandler(ValidationException::class)
|
@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}]")
|
log.warn("Resolve [${e.javaClass.name}: ${e.message}]")
|
||||||
return RestBean.failure(
|
return ApiResponse.failure(
|
||||||
400,
|
400,
|
||||||
null,
|
null,
|
||||||
"parameter validation error"
|
"parameter validation error"
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
package com.github.sor2171.backend.filter
|
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.entity.toJsonString
|
||||||
import com.github.sor2171.backend.utils.Const
|
import com.github.sor2171.backend.utils.Const
|
||||||
import org.springframework.core.annotation.Order
|
import org.springframework.core.annotation.Order
|
||||||
@@ -37,7 +37,7 @@ class FlowLimitFilter(
|
|||||||
response.statusCode = HttpStatus.FORBIDDEN
|
response.statusCode = HttpStatus.FORBIDDEN
|
||||||
response.headers.contentType = MediaType.APPLICATION_JSON
|
response.headers.contentType = MediaType.APPLICATION_JSON
|
||||||
val buffer = response.bufferFactory()
|
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))
|
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.baomidou.mybatisplus.extension.service.IService
|
||||||
import com.github.sor2171.backend.entity.dto.Account
|
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 org.springframework.security.core.userdetails.ReactiveUserDetailsService
|
||||||
import reactor.core.publisher.Mono
|
import reactor.core.publisher.Mono
|
||||||
|
|
||||||
interface AccountService : IService<Account>, ReactiveUserDetailsService {
|
interface AccountService : IService<Account>, ReactiveUserDetailsService {
|
||||||
fun findAccountByNameOrEmail(text: String): Mono<Account>
|
fun findAccountByNameOrEmail(text: String): Mono<Account>
|
||||||
fun askEmailVerifyCode(type: String, email: String, ip: String): Mono<String>
|
fun findAccountByName(username: String): Mono<Account>
|
||||||
fun registerEmailAccount(vo: EmailRegisterVO): Mono<String>
|
fun findAccountByEmail(email: String): Mono<Account>
|
||||||
fun resetEmailAccountPassword(vo: PasswordResetVO): Mono<String>
|
fun existAccountByName(username: String): Mono<Boolean>
|
||||||
fun invalidateJwt(headerToken: String?): Boolean
|
fun existAccountByEmail(email: String): Mono<Boolean>
|
||||||
fun jwtTokenRelogin(headerToken: String?): Mono<ReloginVO>?
|
fun resetPasswordByEmail(email: String, encodedPassword: String): Mono<String>
|
||||||
}
|
}
|
||||||
+51
-164
@@ -1,41 +1,23 @@
|
|||||||
package com.github.sor2171.backend.service.impl
|
package com.github.sor2171.backend.service.impl
|
||||||
|
|
||||||
import com.baomidou.mybatisplus.core.toolkit.Wrappers
|
|
||||||
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl
|
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl
|
||||||
import com.github.sor2171.backend.entity.dto.Account
|
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.mapper.AccountMapper
|
||||||
import com.github.sor2171.backend.service.AccountService
|
import com.github.sor2171.backend.service.AccountService
|
||||||
import com.github.sor2171.backend.utils.Const
|
import org.slf4j.LoggerFactory
|
||||||
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.core.userdetails.User
|
import org.springframework.security.core.userdetails.User
|
||||||
import org.springframework.security.core.userdetails.UserDetails
|
import org.springframework.security.core.userdetails.UserDetails
|
||||||
import org.springframework.security.core.userdetails.UsernameNotFoundException
|
import org.springframework.security.core.userdetails.UsernameNotFoundException
|
||||||
import org.springframework.security.crypto.password.PasswordEncoder
|
|
||||||
import org.springframework.stereotype.Service
|
import org.springframework.stereotype.Service
|
||||||
import reactor.core.publisher.Mono
|
import reactor.core.publisher.Mono
|
||||||
import reactor.core.scheduler.Schedulers
|
|
||||||
import java.time.Duration
|
|
||||||
|
|
||||||
@Service
|
@Service
|
||||||
class AccountServiceImpl(
|
class AccountServiceImpl : ServiceImpl<AccountMapper, Account>(), AccountService {
|
||||||
private val utils: FlowUtils,
|
|
||||||
private val jwtUtils: JwtUtils,
|
|
||||||
private val amqpTemplate: AmqpTemplate,
|
|
||||||
private val stringRedisTemplate: ReactiveStringRedisTemplate,
|
|
||||||
private val encoder: PasswordEncoder
|
|
||||||
|
|
||||||
) : ServiceImpl<AccountMapper, Account>(), AccountService {
|
val logger = LoggerFactory.getLogger(this::class.java)!!
|
||||||
|
|
||||||
override fun findByUsername(username: String): Mono<UserDetails> {
|
override fun findByUsername(username: String): Mono<UserDetails> {
|
||||||
return findAccountByNameOrEmail(username)
|
return findAccountByName(username)
|
||||||
.switchIfEmpty(Mono.error(UsernameNotFoundException("Account with name $username not found")))
|
.switchIfEmpty(Mono.error(UsernameNotFoundException("Account with name $username not found")))
|
||||||
.map { account ->
|
.map { account ->
|
||||||
User.withUsername(username)
|
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 {
|
return Mono.fromCallable {
|
||||||
this.query()
|
logger.info("Find account with name $username")
|
||||||
.eq("username", text).or()
|
this.ktQuery()
|
||||||
.eq("email", text)
|
.eq(Account::username, username)
|
||||||
.one()
|
.one()
|
||||||
}.flatMap { account ->
|
}.flatMap { account ->
|
||||||
Mono.just(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> {
|
override fun findAccountByEmail(email: String): Mono<Account> {
|
||||||
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> {
|
|
||||||
return Mono.fromCallable {
|
return Mono.fromCallable {
|
||||||
this.baseMapper.exists(
|
logger.info("Find account with email $email")
|
||||||
Wrappers.query<Account>()
|
this.ktQuery()
|
||||||
.eq("email", email)
|
.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 {
|
return Mono.fromCallable {
|
||||||
this.baseMapper.exists(
|
logger.info("Determine if name $username exists")
|
||||||
Wrappers.query<Account>()
|
this.ktQuery()
|
||||||
.eq("username", username)
|
.eq(Account::username, username)
|
||||||
)
|
.exists()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun verifyLimit(ip: String): Mono<Boolean> {
|
override fun existAccountByEmail(email: String): Mono<Boolean> {
|
||||||
val key = Const.VERIFY_EMAIL_LIMIT + ip
|
return Mono.fromCallable {
|
||||||
return utils.limitOnceCheck(key, 60)
|
logger.info("Determine if email $email exists")
|
||||||
|
this.ktQuery()
|
||||||
|
.eq(Account::email, email)
|
||||||
|
.exists()
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun verifyCode(email: String, receivedCode: String?): Mono<String> {
|
override fun resetPasswordByEmail(email: String, encodedPassword: String): Mono<String> {
|
||||||
return stringRedisTemplate.opsForValue()
|
return existAccountByEmail(email).flatMap { exists ->
|
||||||
.get(Const.VERIFY_EMAIL_DATA + email)
|
if (!exists) {
|
||||||
.flatMap { code ->
|
return@flatMap Mono.just("account with the email does not exist.")
|
||||||
when {
|
}
|
||||||
receivedCode == null || code != receivedCode ->
|
|
||||||
Mono.just("verify code is wrong.")
|
|
||||||
|
|
||||||
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"))
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
+156
@@ -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
|
package com.github.sor2171.backend.utils
|
||||||
|
|
||||||
|
import reactor.core.publisher.Mono
|
||||||
|
|
||||||
object Const {
|
object Const {
|
||||||
const val FLOW_LIMIT_ORDER = -101
|
const val FLOW_LIMIT_ORDER = -101
|
||||||
|
|
||||||
@@ -9,4 +11,6 @@ object Const {
|
|||||||
|
|
||||||
const val FLOW_LIMIT_COUNTER = "flow:counter:"
|
const val FLOW_LIMIT_COUNTER = "flow:counter:"
|
||||||
const val FLOW_LIMIT_BLOCK = "flow:block:"
|
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:
|
jwt:
|
||||||
#key: 123456
|
#key: 123456
|
||||||
expire-hours: 168
|
expire-hours: 168
|
||||||
ip-ban-limit: 10
|
|
||||||
ip-ban-time: 3
|
|
||||||
ip-ban-time-min: 1
|
|
||||||
|
|
||||||
datasource:
|
datasource:
|
||||||
url: jdbc:mysql://localhost:3306/kotlin_springboot
|
url: jdbc:mysql://localhost:3306/kotlin_springboot
|
||||||
|
|||||||
Reference in New Issue
Block a user