This commit is contained in:
SOR
2026-04-04 08:32:57 +08:00
commit b3e1fd9e18
76 changed files with 6650 additions and 0 deletions
+3
View File
@@ -0,0 +1,3 @@
/gradlew text eol=lf
*.bat text eol=crlf
*.jar binary
+41
View File
@@ -0,0 +1,41 @@
HELP.md
.gradle
build/
!gradle/wrapper/gradle-wrapper.jar
!**/src/main/**/build/
!**/src/test/**/build/
src/main/resources/application.yaml
### STS ###
.apt_generated
.classpath
.factorypath
.project
.settings
.springBeans
.sts4-cache
bin/
!**/src/main/**/bin/
!**/src/test/**/bin/
### IntelliJ IDEA ###
.idea
*.iws
*.iml
*.ipr
out/
!**/src/main/**/out/
!**/src/test/**/out/
### NetBeans ###
/nbproject/private/
/nbbuild/
/dist/
/nbdist/
/.nb-gradle/
### VS Code ###
.vscode/
### Kotlin ###
.kotlin
+125
View File
@@ -0,0 +1,125 @@
## localhost:8080/api
所有返回的json对象总有如下格式
```
{
"code": int,
"message": string,
"data": T
}
```
接下来将省略`/api`并只给出`T`的类声明
当`"code"`不是`200`时,`"data"`必定为`null`
部分`/api/test`的返回值不遵循上述格式
## /auth
### POST /login
Authorization: 无
key: username, password
data:
```
{
"username": string,
"role": string,
"token": sting,
"expire": time
}
```
### GET /logout
Authorization: Bearer $Token
key: 无
data:
```
null
```
### GET /ask-code?email=******&type=register
Authorization: 无
key: 无
data:
```
null
```
### GET /ask-code?email=******&type=reset
Authorization: 无
key: 无
data:
```
null
```
### POST /register
Authorization: 无
key: 无
data:email, code, username, password
```
null
```
### POST /reset
Authorization: 无
key: email, code, password
data:
```
null
```
### GET /relogin
Authorization: Bearer $Token
key: 无
data:
```
{
"token": sting,
"expire": time
}
```
## /test
### GET /hello
Authorization: Bearer $Token
key: 无
回复:
```
Hello Kotlin WebFlux!
```
+61
View File
@@ -0,0 +1,61 @@
plugins {
kotlin("jvm") version "2.3.20"
kotlin("plugin.spring") version "2.3.20"
kotlin("plugin.serialization") version "2.3.20"
id("org.springframework.boot") version "4.0.4"
id("io.spring.dependency-management") version "1.1.7"
}
group = "com.github.sor2171"
version = "1.0.0"
java {
toolchain {
languageVersion = JavaLanguageVersion.of(25)
}
}
repositories {
mavenCentral()
}
dependencies {
implementation("com.auth0:java-jwt:4.4.0")
implementation("com.baomidou:mybatis-plus-spring-boot4-starter:3.5.15")
implementation("org.springframework.boot:spring-boot-starter-amqp")
implementation("org.springframework.boot:spring-boot-starter-data-redis-reactive")
implementation("org.springframework.boot:spring-boot-starter-json")
implementation("org.springframework.boot:spring-boot-starter-mail")
implementation("org.springframework.boot:spring-boot-starter-security")
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")
implementation("org.jetbrains.kotlinx:kotlinx-serialization-json:1.7.1")
implementation("io.projectreactor.kotlin:reactor-kotlin-extensions")
implementation("tools.jackson.module:jackson-module-kotlin")
runtimeOnly("com.mysql:mysql-connector-j")
testImplementation("org.springframework.boot:spring-boot-starter-test")
testImplementation("org.jetbrains.kotlin:kotlin-test-junit5")
testImplementation("org.jetbrains.kotlinx:kotlinx-coroutines-test")
testRuntimeOnly("org.junit.platform:junit-platform-launcher")
}
kotlin {
compilerOptions {
freeCompilerArgs.addAll("-Xjsr305=strict", "-Xannotation-default-target=param-property")
jvmToolchain(25)
}
}
tasks.withType<org.springframework.boot.gradle.tasks.run.BootRun> {
jvmArgs("--enable-native-access=ALL-UNNAMED")
}
tasks.withType<Test> {
useJUnitPlatform()
jvmArgs("--enable-native-access=ALL-UNNAMED")
}
Binary file not shown.
+7
View File
@@ -0,0 +1,7 @@
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-9.4.0-bin.zip
networkTimeout=10000
validateDistributionUrl=true
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
+4
View File
@@ -0,0 +1,4 @@
plugins {
id("org.gradle.toolchains.foojay-resolver-convention") version "1.0.0"
}
rootProject.name = "backend"
@@ -0,0 +1,11 @@
package com.github.sor2171.backend
import org.springframework.boot.autoconfigure.SpringBootApplication
import org.springframework.boot.runApplication
@SpringBootApplication
class CareerppApplication
fun main(args: Array<String>) {
runApplication<CareerppApplication>(*args)
}
@@ -0,0 +1,15 @@
package com.github.sor2171.backend.config
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder
import org.springframework.security.crypto.password.PasswordEncoder
@Configuration
class BeanConfig {
@Bean
fun passwordEncoder(): PasswordEncoder {
return BCryptPasswordEncoder()
}
}
@@ -0,0 +1,60 @@
package com.github.sor2171.backend.config
import kotlinx.serialization.json.Json
import kotlinx.serialization.serializer
import org.springframework.amqp.core.Message
import org.springframework.amqp.core.MessageProperties
import org.springframework.amqp.rabbit.config.SimpleRabbitListenerContainerFactory
import org.springframework.amqp.rabbit.connection.ConnectionFactory
import org.springframework.amqp.rabbit.core.RabbitTemplate
import org.springframework.amqp.support.converter.AbstractMessageConverter
import org.springframework.amqp.support.converter.MessageConverter
import org.springframework.beans.factory.annotation.Qualifier
import org.springframework.boot.amqp.autoconfigure.SimpleRabbitListenerContainerFactoryConfigurer
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
@Configuration
class RabbitConfig {
@Bean
fun messageConverter(@Qualifier("kotlinxSerializationJson") json: Json): MessageConverter =
object : AbstractMessageConverter() {
override fun createMessage(obj: Any, messageProperties: MessageProperties): Message {
val serializer = json.serializersModule.serializer(obj::class.java)
val jsonString = json.encodeToString(serializer, obj)
val bytes = jsonString.toByteArray(Charsets.UTF_8)
messageProperties.contentType = MessageProperties.CONTENT_TYPE_JSON
messageProperties.contentLength = bytes.size.toLong()
return Message(bytes, messageProperties)
}
override fun fromMessage(message: Message): Any {
val content = String(message.body, Charsets.UTF_8)
return content
}
}
@Bean
fun rabbitTemplate(
connectionFactory: ConnectionFactory,
messageConverter: MessageConverter
): RabbitTemplate {
val rabbitTemplate = RabbitTemplate(connectionFactory)
rabbitTemplate.messageConverter = messageConverter
return rabbitTemplate
}
@Bean
fun rabbitListenerContainerFactory(
configurer: SimpleRabbitListenerContainerFactoryConfigurer,
connectionFactory: ConnectionFactory,
messageConverter: MessageConverter
): SimpleRabbitListenerContainerFactory {
val factory = SimpleRabbitListenerContainerFactory()
configurer.configure(factory, connectionFactory)
factory.setMessageConverter(messageConverter)
return factory
}
}
@@ -0,0 +1,151 @@
package com.github.sor2171.backend.config
import com.github.sor2171.backend.entity.RestBean
import com.github.sor2171.backend.entity.vo.response.AuthorizeVO
import com.github.sor2171.backend.filter.JwtAuthorizeFilter
import com.github.sor2171.backend.service.AccountService
import com.github.sor2171.backend.utils.DateUtils
import com.github.sor2171.backend.utils.JwtUtils
import kotlinx.serialization.json.Json
import kotlinx.serialization.json.encodeToJsonElement
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
import org.springframework.http.HttpStatus
import org.springframework.http.MediaType
import org.springframework.security.authentication.ReactiveAuthenticationManager
import org.springframework.security.authentication.UserDetailsRepositoryReactiveAuthenticationManager
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken
import org.springframework.security.config.annotation.web.reactive.EnableWebFluxSecurity
import org.springframework.security.config.web.server.SecurityWebFiltersOrder
import org.springframework.security.config.web.server.ServerHttpSecurity
import org.springframework.security.core.userdetails.User
import org.springframework.security.crypto.password.PasswordEncoder
import org.springframework.security.web.server.SecurityWebFilterChain
import org.springframework.security.web.server.authentication.AuthenticationWebFilter
import org.springframework.security.web.server.authentication.ServerAuthenticationConverter
import org.springframework.security.web.server.context.NoOpServerSecurityContextRepository
import org.springframework.security.web.server.util.matcher.ServerWebExchangeMatchers
import org.springframework.web.server.ServerWebExchange
import reactor.core.publisher.Mono
@Configuration
@EnableWebFluxSecurity
class SecurityConfig(
private val jwtUtils: JwtUtils,
private val service: AccountService,
private val jwtAuthorizeFilter: JwtAuthorizeFilter,
private val passwordEncoder: PasswordEncoder
) {
@Bean
fun reactiveAuthenticationManager(): ReactiveAuthenticationManager {
val manager = UserDetailsRepositoryReactiveAuthenticationManager(service)
manager.setPasswordEncoder(passwordEncoder)
return manager
}
@Bean
fun securityWebFilterChain(http: ServerHttpSecurity): SecurityWebFilterChain {
return http
.authorizeExchange {
it
.pathMatchers(
"/api/auth/relogin"
).authenticated()
.pathMatchers(
"/api/auth/**",
"/error"
).permitAll()
.anyExchange().authenticated()
}
.addFilterAt(loginAuthenticationFilter(), SecurityWebFiltersOrder.AUTHENTICATION)
.addFilterAt(jwtAuthorizeFilter, SecurityWebFiltersOrder.AUTHENTICATION)
.exceptionHandling {
it.authenticationEntryPoint { exchange, ex ->
writeJsonResponse(
exchange,
HttpStatus.UNAUTHORIZED,
RestBean.unauthenticated(ex.message)
)
}
.accessDeniedHandler { exchange, ex ->
writeJsonResponse(
exchange,
HttpStatus.FORBIDDEN,
RestBean.forbidden(ex.message)
)
}
}
.csrf { it.disable() }
.securityContextRepository(NoOpServerSecurityContextRepository.getInstance())
.build()
}
@Bean
fun loginAuthenticationFilter(): AuthenticationWebFilter {
val filter = AuthenticationWebFilter(reactiveAuthenticationManager())
filter.setRequiresAuthenticationMatcher(
ServerWebExchangeMatchers.pathMatchers("/api/auth/login")
)
filter.setServerAuthenticationConverter(loginAuthenticationConverter())
filter.setAuthenticationSuccessHandler { webFilterExchange, authentication ->
val user = authentication.principal as User
service.findAccountByNameOrEmail(user.username)
.flatMap { account ->
val vo = account.toAnotherObject(
AuthorizeVO::class,
mapOf(
"token" to jwtUtils.createJwt(user, account.id!!, account.username),
"expire" to DateUtils.dateToLocalDateTime(jwtUtils.expiresTime())
)
)
writeJsonResponse(
webFilterExchange.exchange,
HttpStatus.OK,
RestBean.success(vo)
)
}
}
filter.setAuthenticationFailureHandler { webFilterExchange, exception ->
writeJsonResponse(
webFilterExchange.exchange,
HttpStatus.UNAUTHORIZED,
RestBean.unauthenticated(exception.message)
)
}
return filter
}
private fun loginAuthenticationConverter(): ServerAuthenticationConverter {
return ServerAuthenticationConverter { exchange ->
exchange.formData.flatMap { formData ->
val username = formData.getFirst("username")
val password = formData.getFirst("password")
if (username != null && password != null) {
Mono.just(
UsernamePasswordAuthenticationToken(
username,
password
)
)
} else {
Mono.empty()
}
}
}
}
}
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
val jsonString = Json.encodeToJsonElement(body).toString()
val buffer = response.bufferFactory().wrap(jsonString.toByteArray())
return response.writeWith(Mono.just(buffer))
}
@@ -0,0 +1,17 @@
package com.github.sor2171.backend.config
import kotlinx.serialization.json.Json
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
@Configuration
class SerializationConfig {
@Bean
fun kotlinxSerializationJson(): Json = Json {
ignoreUnknownKeys = true
isLenient = true
encodeDefaults = false
prettyPrint = true
}
}
@@ -0,0 +1,79 @@
package com.github.sor2171.backend.controller
import com.github.sor2171.backend.entity.RestBean
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 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.server.ServerWebExchange
import reactor.core.publisher.Mono
@Validated
@RestController
@RequestMapping("/api/auth")
class AuthorizeController(
private val service: AccountService
) {
private val logger = LoggerFactory.getLogger(this::class.java)
@GetMapping("/ask-code")
fun askVerifyCode(
@RequestParam @NotBlank @Email email: String,
@RequestParam @Pattern(regexp = "(register|reset)") type: String,
exchange: ServerWebExchange
): Mono<RestBean<Any?>> {
logger.info("Trying to ask code")
val ip = exchange.request.remoteAddress?.address?.hostAddress ?: "unknown"
return service.askEmailVerifyCode(type, email, ip)
.map { messageHandler(it) }
}
@PostMapping("/register")
fun emailRegister(@RequestBody @Valid vo: EmailRegisterVO): Mono<RestBean<Any?>> {
logger.info("Trying to register")
return service.registerEmailAccount(vo)
.map { messageHandler(it) }
}
@PostMapping("/reset")
fun emailResetPassword(@RequestBody @Valid vo: PasswordResetVO): Mono<RestBean<Any?>> {
logger.info("Trying to reset password")
return service.resetEmailAccountPassword(vo)
.map { messageHandler(it) }
}
@GetMapping("/logout")
fun logout(exchange: ServerWebExchange): Mono<RestBean<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()
}
}
@GetMapping("/relogin")
fun relogin(exchange: ServerWebExchange): Mono<RestBean<Any?>> {
logger.info("Trying to relogin")
val authorization = exchange.request.headers.getFirst("Authorization")
return service
.jwtTokenRelogin(authorization)
?.map { RestBean.success(it) }
?: Mono.just(messageHandler("Please login with password."))
}
private fun messageHandler(wrongMessage: String): RestBean<Any?> {
return if (wrongMessage.isBlank()) {
RestBean.success()
} else {
RestBean.failure(400, null, wrongMessage)
}
}
}
@@ -0,0 +1,14 @@
package com.github.sor2171.backend.controller
import org.springframework.web.bind.annotation.GetMapping
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.bind.annotation.RestController
import reactor.core.publisher.Mono
@RestController
@RequestMapping("/api/test")
class TestController {
@GetMapping("/hello")
fun test(): Mono<String> = Mono.just("Hello Kotlin WebFlux!")
}
@@ -0,0 +1,56 @@
package com.github.sor2171.backend.entity
import kotlin.reflect.KClass
import kotlin.reflect.KProperty
import kotlin.reflect.full.createInstance
import kotlin.reflect.full.declaredMemberProperties
import kotlin.reflect.full.memberProperties
import kotlin.reflect.jvm.javaField
interface DataCopy {
fun <T : Any> toAnotherObject(
toClass: KClass<T>,
otherProperties: Map<String, Any?>
): T {
try {
val voProperties = toClass.declaredMemberProperties
val vo = toClass.createInstance()
for (voProperty in voProperties)
copyFieldData(voProperty, otherProperties, vo)
return vo
} catch (e: ReflectiveOperationException) {
throw RuntimeException(
"${toClass.simpleName} has no fields.",
e
)
}
}
private fun copyFieldData(
toProperty: KProperty<*>,
otherProperties: Map<String, Any?>,
another: Any
) {
try {
val thisProperty = this::class.memberProperties
.firstOrNull { it.name == toProperty.name }
val value =
if (thisProperty != null) {
thisProperty.getter.call(this)
} else if (otherProperties.containsKey(toProperty.name))
otherProperties[toProperty.name]
else
throw RuntimeException(
"Property ${toProperty.name} not found."
)
val field = toProperty.javaField!!
field.isAccessible = true
field.set(another, value)
} catch (e: Exception) {
e.printStackTrace()
}
}
}
@@ -0,0 +1,41 @@
package com.github.sor2171.backend.entity
import kotlinx.serialization.Serializable
import kotlinx.serialization.json.Json
@Serializable
data class RestBean<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)
}
// 针对无 data 返回的情况,统一使用 Any?
fun success(message: String = "Success"): RestBean<Any?> {
return RestBean(200, null, message)
}
fun <T> failure(code: Int = 401, data: T, message: String?): RestBean<T> {
return RestBean(code, data, message ?: "Failure")
}
fun unauthenticated(message: String?) =
failure(401, null, message)
fun forbidden(message: String?) =
failure(403, null, message)
fun logoutFailed(message: String = ""): RestBean<Any?> {
val formatMessage = if (message.isBlank()) "" else ": $message"
return failure(400, null, "Logout Failed$formatMessage")
}
}
}
inline fun <reified T> RestBean<T>.toJsonString(): String {
return Json.encodeToString(this)
}
@@ -0,0 +1,20 @@
package com.github.sor2171.backend.entity.dto
import com.baomidou.mybatisplus.annotation.IdType
import com.baomidou.mybatisplus.annotation.TableId
import com.baomidou.mybatisplus.annotation.TableName
import com.github.sor2171.backend.entity.DataCopy
import kotlinx.datetime.LocalDateTime
import kotlinx.serialization.Serializable
@Serializable
@TableName("account")
data class Account(
@TableId(type = IdType.AUTO)
val id: Int? = null,
val username: String = "",
val password: String = "",
val email: String = "",
val role: String = "",
val registerTime: LocalDateTime? = null
) : DataCopy
@@ -0,0 +1,10 @@
package com.github.sor2171.backend.entity.dto
import kotlinx.serialization.Serializable
@Serializable
data class EmailVerificationMsg(
val email: String,
val type: String,
val code: String
)
@@ -0,0 +1,19 @@
package com.github.sor2171.backend.entity.vo.request
import jakarta.validation.constraints.Email
import jakarta.validation.constraints.Pattern
import kotlinx.serialization.Serializable
import org.hibernate.validator.constraints.Length
@Serializable
data class EmailRegisterVO(
@param:Email
val email: String = "",
@param:Length(min = 6, max = 6)
val code: String? = null,
@param:Pattern(regexp = "^[a-zA-Z0-9\\u4e00-\\u9fa5]+$")
@param:Length(min = 4, max = 16)
val username: String = "",
@param:Length(min = 6, max = 20)
val password: String = "",
)
@@ -0,0 +1,15 @@
package com.github.sor2171.backend.entity.vo.request
import jakarta.validation.constraints.Email
import kotlinx.serialization.Serializable
import org.hibernate.validator.constraints.Length
@Serializable
data class PasswordResetVO(
@param:Email
val email: String = "",
@param:Length(min = 6, max = 6)
val code: String? = null,
@param:Length(min = 6, max = 20)
val password: String = "",
)
@@ -0,0 +1,13 @@
package com.github.sor2171.backend.entity.vo.response
import com.github.sor2171.backend.utils.DateUtils.getCurrentDateTime
import kotlinx.datetime.LocalDateTime
import kotlinx.serialization.Serializable
@Serializable
data class AuthorizeVO(
val username: String = "",
val role: String = "",
val token: String = "",
val expire: LocalDateTime = getCurrentDateTime(),
)
@@ -0,0 +1,9 @@
package com.github.sor2171.backend.entity.vo.response
import kotlinx.serialization.Serializable
@Serializable
data class ReloginVO(
val token: String = "",
val expire: String = "",
)
@@ -0,0 +1,23 @@
package com.github.sor2171.backend.exception
import com.github.sor2171.backend.entity.RestBean
import jakarta.validation.ValidationException
import org.slf4j.LoggerFactory
import org.springframework.web.bind.annotation.ExceptionHandler
import org.springframework.web.bind.annotation.RestControllerAdvice
@RestControllerAdvice
class ValidationController {
private val log = LoggerFactory.getLogger(ValidationController::class.java)
@ExceptionHandler(ValidationException::class)
fun validationException(e: Exception): RestBean<out String?> {
log.warn("Resolve [${e.javaClass.name}: ${e.message}]")
return RestBean.failure(
400,
null,
"parameter validation error"
)
}
}
@@ -0,0 +1,38 @@
package com.github.sor2171.backend.filter
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
import org.springframework.http.HttpHeaders
import org.springframework.http.HttpMethod
import org.springframework.web.cors.CorsConfiguration
import org.springframework.web.cors.reactive.CorsWebFilter
import org.springframework.web.cors.reactive.UrlBasedCorsConfigurationSource
@Configuration
class CorsFilter {
@Bean
fun corsWebFilter(): CorsWebFilter {
val config = CorsConfiguration().apply {
allowedOriginPatterns = listOf("*")
allowedMethods = listOf(
HttpMethod.GET.name(),
HttpMethod.POST.name(),
HttpMethod.PUT.name(),
HttpMethod.DELETE.name(),
HttpMethod.OPTIONS.name()
)
allowedHeaders = listOf(
HttpHeaders.AUTHORIZATION,
HttpHeaders.CONTENT_TYPE
)
allowCredentials = true
}
val source = UrlBasedCorsConfigurationSource().apply {
registerCorsConfiguration("/**", config)
}
return CorsWebFilter(source)
}
}
@@ -0,0 +1,72 @@
package com.github.sor2171.backend.filter
import com.github.sor2171.backend.entity.RestBean
import com.github.sor2171.backend.entity.toJsonString
import com.github.sor2171.backend.utils.Const
import org.springframework.core.annotation.Order
import org.springframework.data.redis.core.ReactiveStringRedisTemplate
import org.springframework.http.HttpStatus
import org.springframework.http.MediaType
import org.springframework.stereotype.Component
import org.springframework.web.server.ServerWebExchange
import org.springframework.web.server.WebFilter
import org.springframework.web.server.WebFilterChain
import reactor.core.publisher.Mono
import java.time.Duration
@Component
@Order(Const.FLOW_LIMIT_ORDER)
class FlowLimitFilter(
private val template: ReactiveStringRedisTemplate
) : WebFilter {
override fun filter(exchange: ServerWebExchange, chain: WebFilterChain): Mono<Void> {
val address = exchange.request.remoteAddress?.address?.hostAddress ?: "unknown"
return tryCount(address).flatMap { allowed ->
if (allowed) {
chain.filter(exchange)
} else {
writeBlockMessage(exchange)
}
}
}
private fun writeBlockMessage(exchange: ServerWebExchange): Mono<Void> {
val response = exchange.response
response.statusCode = HttpStatus.FORBIDDEN
response.headers.contentType = MediaType.APPLICATION_JSON
val buffer = response.bufferFactory()
.wrap(RestBean.forbidden("Too many requests").toJsonString().toByteArray())
return response.writeWith(Mono.just(buffer))
}
private fun tryCount(ip: String): Mono<Boolean> {
val blockKey = Const.FLOW_LIMIT_BLOCK + ip
val counterKey = Const.FLOW_LIMIT_COUNTER + ip
return template.hasKey(blockKey).flatMap { isBlocked ->
if (isBlocked) {
Mono.just(false)
} else {
template.hasKey(counterKey).flatMap { hasCounter ->
if (hasCounter) {
template.opsForValue().increment(counterKey).flatMap { count ->
if (count > 10) {
template.opsForValue()
.set(blockKey, "1", Duration.ofMinutes(1))
.thenReturn(false)
} else {
Mono.just(true)
}
}
} else {
template.opsForValue()
.set(counterKey, "1", Duration.ofSeconds(3))
.thenReturn(true)
}
}
}
}
}
}
@@ -0,0 +1,37 @@
package com.github.sor2171.backend.filter
import com.github.sor2171.backend.utils.JwtUtils
import org.springframework.http.HttpHeaders
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken
import org.springframework.security.core.context.ReactiveSecurityContextHolder
import org.springframework.stereotype.Component
import org.springframework.web.server.ServerWebExchange
import org.springframework.web.server.WebFilter
import org.springframework.web.server.WebFilterChain
import reactor.core.publisher.Mono
@Component
class JwtAuthorizeFilter(
private val utils: JwtUtils
) : WebFilter {
override fun filter(exchange: ServerWebExchange, chain: WebFilterChain): Mono<Void> {
val authorization = exchange.request.headers.getFirst(HttpHeaders.AUTHORIZATION)
val jwt = utils.resolveJwt(authorization)
return if (jwt != null) {
val user = utils.toUser(jwt)
val authentication = UsernamePasswordAuthenticationToken(
user,
null,
user.authorities
)
exchange.attributes["id"] = utils.toId(jwt)
chain.filter(exchange)
.contextWrite(ReactiveSecurityContextHolder.withAuthentication(authentication))
} else {
chain.filter(exchange)
}
}
}
@@ -0,0 +1,59 @@
package com.github.sor2171.backend.listener
import com.github.sor2171.backend.entity.dto.EmailVerificationMsg
import kotlinx.serialization.json.Json
import org.slf4j.LoggerFactory
import org.springframework.amqp.rabbit.annotation.RabbitHandler
import org.springframework.amqp.rabbit.annotation.RabbitListener
import org.springframework.beans.factory.annotation.Value
import org.springframework.mail.MailSender
import org.springframework.mail.SimpleMailMessage
import org.springframework.stereotype.Component
@Component
@RabbitListener(queues = ["mail"])
class MailQueueListener(
@param:Value($$"${spring.mail.username}")
private val username: String,
private val json: Json,
private val sender: MailSender
) {
private val logger = LoggerFactory.getLogger(this::class.java)
@RabbitHandler
fun senderMailMessage(content: String) {
val data = json.decodeFromString<EmailVerificationMsg>(content)
val (email, type, code) = data
val message = when (type) {
"register" -> createMailMessage(
"Welcome to Our Service",
"Thank you for registering! Your verification code is: $code"
+ "\nThis code is valid for 3 minutes.",
email
)
"reset" -> createMailMessage(
"Password Reset Request",
"You requested a password reset. Your verification code is: $code"
+ "\nThis code is valid for 3 minutes.",
email
)
else -> return
}
sender.send(message)
logger.info("Email sent to $email.")
}
fun createMailMessage(title: String, content: String, to: String): SimpleMailMessage {
val message = SimpleMailMessage()
message.subject = title
message.text = content
message.from = username
message.setTo(to)
return message
}
}
@@ -0,0 +1,8 @@
package com.github.sor2171.backend.mapper
import com.baomidou.mybatisplus.core.mapper.BaseMapper
import com.github.sor2171.backend.entity.dto.Account
import org.apache.ibatis.annotations.Mapper
@Mapper
interface AccountMapper : BaseMapper<Account>
@@ -0,0 +1,18 @@
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>?
}
@@ -0,0 +1,209 @@
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.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
) : ServiceImpl<AccountMapper, Account>(), AccountService {
override fun findByUsername(username: String): Mono<UserDetails> {
return findAccountByNameOrEmail(username)
.switchIfEmpty(Mono.error(UsernameNotFoundException("Account with name $username not found")))
.map { account ->
User.withUsername(username)
.password(account.password)
.roles(account.role)
.build()
}
}
override fun findAccountByNameOrEmail(text: String): Mono<Account> {
return Mono.fromCallable {
this.query()
.eq("username", text).or()
.eq("email", text)
.one()
}.flatMap { account ->
Mono.just(account)
}
}
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> {
return Mono.fromCallable {
this.baseMapper.exists(
Wrappers.query<Account>()
.eq("email", email)
)
}
}
private fun existAccountByUsername(username: String): Mono<Boolean> {
return Mono.fromCallable {
this.baseMapper.exists(
Wrappers.query<Account>()
.eq("username", username)
)
}
}
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"))
}
}
@@ -0,0 +1,12 @@
package com.github.sor2171.backend.utils
object Const {
const val FLOW_LIMIT_ORDER = -101
const val JWT_BLACK_LIST = "jwt:blacklist:"
const val VERIFY_EMAIL_LIMIT = "verify:email:limit:"
const val VERIFY_EMAIL_DATA = "verify:email:data:"
const val FLOW_LIMIT_COUNTER = "flow:counter:"
const val FLOW_LIMIT_BLOCK = "flow:block:"
}
@@ -0,0 +1,17 @@
package com.github.sor2171.backend.utils
import kotlinx.datetime.*
import kotlinx.datetime.TimeZone
import java.util.*
object DateUtils {
fun getCurrentDateTime() =
Clock.System.now().toLocalDateTime(TimeZone.currentSystemDefault())
fun dateToLocalDateTime(date: Date): LocalDateTime {
return date
.toInstant()
.toKotlinInstant()
.toLocalDateTime(TimeZone.currentSystemDefault())
}
}
@@ -0,0 +1,26 @@
package com.github.sor2171.backend.utils
import jakarta.annotation.Resource
import org.springframework.data.redis.core.ReactiveStringRedisTemplate
import org.springframework.stereotype.Component
import reactor.core.publisher.Mono
import java.time.Duration
@Component
class FlowUtils(
@Resource
val template: ReactiveStringRedisTemplate
) {
fun limitOnceCheck(key: String, blockTime: Int): Mono<Boolean> {
return template.hasKey(key).flatMap { exists ->
if (exists) {
Mono.just(false)
} else {
template.opsForValue()
.set(key, "", Duration.ofSeconds(blockTime.toLong()))
.thenReturn(true)
}
}
}
}
@@ -0,0 +1,107 @@
package com.github.sor2171.backend.utils
import com.auth0.jwt.JWT
import com.auth0.jwt.JWTVerifier
import com.auth0.jwt.algorithms.Algorithm
import com.auth0.jwt.interfaces.DecodedJWT
import org.springframework.beans.factory.annotation.Value
import org.springframework.data.redis.core.StringRedisTemplate
import org.springframework.security.core.userdetails.User
import org.springframework.security.core.userdetails.UserDetails
import org.springframework.stereotype.Component
import java.util.*
import java.util.concurrent.TimeUnit
@Component
class JwtUtils(
@param:Value($$"${spring.security.jwt.key}")
private val key: String,
@param:Value($$"${spring.security.jwt.expire-hours}")
private val expireHours: Int,
private val template: StringRedisTemplate,
private val algorithm: Algorithm = Algorithm.HMAC256(key),
private val jwtVerifier: JWTVerifier = JWT.require(algorithm).build()
) {
fun invalidateJwt(headerToken: String?): Boolean {
val token = this.convertToToken(headerToken) ?: return false
try {
val jwt = jwtVerifier.verify(token)
val id = jwt.id
return deleteToken(id, jwt.expiresAt)
} catch (e: Exception) {
println(e.message)
return false
}
}
private fun deleteToken(uuid: String, time: Date): Boolean {
val now = Date()
val expire = (time.time - now.time).coerceAtLeast(0)
template.opsForValue().set(
Const.JWT_BLACK_LIST + uuid,
"deleted",
expire,
TimeUnit.MILLISECONDS
)
return true
}
private fun isInvalidToken(uuid: String): Boolean =
template.hasKey(Const.JWT_BLACK_LIST + uuid) ?: false
fun resolveJwt(headerToken: String?): DecodedJWT? {
val token = convertToToken(headerToken) ?: return null
try {
val decodedJWT = jwtVerifier.verify(token)
if (this.isInvalidToken(decodedJWT.id)) return null
val expiresAt = decodedJWT.expiresAt
return if (Date().after(expiresAt)) null
else decodedJWT
} catch (e: Exception) {
println(e.message)
return null
}
}
fun createJwt(
details: UserDetails,
id: Int,
username: String
): String {
return JWT.create()
.withJWTId(UUID.randomUUID().toString())
.withClaim("id", id)
.withClaim("username", username)
.withClaim(
"authorities",
details.authorities.map { it.authority }.toList()
)
.withExpiresAt(expiresTime())
.withIssuedAt(Date())
.sign(algorithm)
}
fun toUser(jwt: DecodedJWT): UserDetails {
val claims = jwt.claims
return User
.withUsername(claims["username"]!!.asString())
.password("********")
.authorities(*(claims["authorities"]!!.asArray(String::class.java)))
.build()
}
fun toId(jwt: DecodedJWT) = jwt.claims["id"]?.asInt() ?: -1
fun expiresTime(): Date {
val cal = Calendar.getInstance()
cal.add(Calendar.HOUR, expireHours)
return cal.time
}
fun convertToToken(headerToken: String?): String? =
headerToken?.replace("Bearer ", "")
}
@@ -0,0 +1,38 @@
spring:
webflux:
base-path: /
mail:
#host: smtp.example.com
#username: 123456@example.com
#password: password
#port: 123456
protocol: smtp
properties:
mail.smtp.auth: true
mail.smtp.ssl.enable: true
mail.smtp.timeout: 5000
rabbitmq:
host: localhost
port: 5672
virtual-host: /
#username: admin
#password: 123456
application:
name: backend
security:
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
#username: root
#password: 123456
driver-class-name: com.mysql.cj.jdbc.Driver
@@ -0,0 +1,57 @@
-- MySQL dump 10.13 Distrib 8.0.43, for Linux (x86_64)
--
-- Host: 127.0.0.1 Database: kotlin_springboot
-- ------------------------------------------------------
-- Server version 8.0.43-0ubuntu0.24.04.2
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!50503 SET NAMES utf8mb4 */;
/*!40103 SET @OLD_TIME_ZONE=@@TIME_ZONE */;
/*!40103 SET TIME_ZONE='+00:00' */;
/*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */;
/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */;
/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */;
/*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */;
--
-- Table structure for table `account`
--
DROP TABLE IF EXISTS `account`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!50503 SET character_set_client = utf8mb4 */;
CREATE TABLE `account` (
`id` int NOT NULL AUTO_INCREMENT,
`username` varchar(255) DEFAULT NULL,
`password` varchar(255) DEFAULT NULL,
`email` varchar(255) DEFAULT NULL,
`role` varchar(255) DEFAULT NULL,
`register_time` datetime DEFAULT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `unique_email` (`email`),
UNIQUE KEY `unique_name` (`username`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Dumping data for table `account`
--
LOCK TABLES `account` WRITE;
/*!40000 ALTER TABLE `account` DISABLE KEYS */;
INSERT INTO `account` VALUES (1,'test','$2a$10$Xqe2W.5zs/I8FAs3cK331e6tyuo4XWTHNhW1oV6bOHUzwMZ2kAPTa','1234567890@gmail.com','user','2025-11-06 15:56:37');
/*!40000 ALTER TABLE `account` ENABLE KEYS */;
UNLOCK TABLES;
/*!40103 SET TIME_ZONE=@OLD_TIME_ZONE */;
/*!40101 SET SQL_MODE=@OLD_SQL_MODE */;
/*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */;
/*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
/*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */;
-- Dump completed on 2025-11-24 17:53:21
@@ -0,0 +1,15 @@
package com.github.sor2171.backend
import org.junit.jupiter.api.Test
import org.springframework.boot.test.context.SpringBootTest
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder
@SpringBootTest
class BackendApplicationTests {
@Test
fun contextLoads() {
println(BCryptPasswordEncoder().encode("123456"))
}
}