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;NpK*OZfAjAb
z`Ttl8km0{|{F`kWKWltH$^Ech;G2y`{7&N^%H;d0$cGv7Z^oJNOSiwAFaP<=em}wX
z<8AA6<}bbeZc_7S=ii6PALi)3nOXL)o&Uj%-OnQ52M&L%(%ZaWiu^(R{b!Bu2WJl<
h$Zw`p^gE5e2}ml*LW4$nU|{5+pXG<~Ugg7I{||-5t(pJ;
literal 0
HcmV?d00001
diff --git a/backend/gradle/wrapper/gradle-wrapper.properties b/backend/gradle/wrapper/gradle-wrapper.properties
new file mode 100644
index 0000000..dbc3ce4
--- /dev/null
+++ b/backend/gradle/wrapper/gradle-wrapper.properties
@@ -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
diff --git a/backend/settings.gradle.kts b/backend/settings.gradle.kts
new file mode 100644
index 0000000..7870de7
--- /dev/null
+++ b/backend/settings.gradle.kts
@@ -0,0 +1,4 @@
+plugins {
+ id("org.gradle.toolchains.foojay-resolver-convention") version "1.0.0"
+}
+rootProject.name = "backend"
diff --git a/backend/src/main/kotlin/com/github/sor2171/backend/CareerppApplication.kt b/backend/src/main/kotlin/com/github/sor2171/backend/CareerppApplication.kt
new file mode 100644
index 0000000..c85083c
--- /dev/null
+++ b/backend/src/main/kotlin/com/github/sor2171/backend/CareerppApplication.kt
@@ -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) {
+ runApplication(*args)
+}
diff --git a/backend/src/main/kotlin/com/github/sor2171/backend/config/BeanConfig.kt b/backend/src/main/kotlin/com/github/sor2171/backend/config/BeanConfig.kt
new file mode 100644
index 0000000..78a1a03
--- /dev/null
+++ b/backend/src/main/kotlin/com/github/sor2171/backend/config/BeanConfig.kt
@@ -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()
+ }
+}
\ No newline at end of file
diff --git a/backend/src/main/kotlin/com/github/sor2171/backend/config/RabbitConfig.kt b/backend/src/main/kotlin/com/github/sor2171/backend/config/RabbitConfig.kt
new file mode 100644
index 0000000..acf38bf
--- /dev/null
+++ b/backend/src/main/kotlin/com/github/sor2171/backend/config/RabbitConfig.kt
@@ -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
+ }
+}
\ No newline at end of file
diff --git a/backend/src/main/kotlin/com/github/sor2171/backend/config/SecurityConfig.kt b/backend/src/main/kotlin/com/github/sor2171/backend/config/SecurityConfig.kt
new file mode 100644
index 0000000..8596b88
--- /dev/null
+++ b/backend/src/main/kotlin/com/github/sor2171/backend/config/SecurityConfig.kt
@@ -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 writeJsonResponse(
+ exchange: ServerWebExchange,
+ status: HttpStatus,
+ body: RestBean
+): Mono {
+ 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))
+}
\ No newline at end of file
diff --git a/backend/src/main/kotlin/com/github/sor2171/backend/config/SerializationConfig.kt b/backend/src/main/kotlin/com/github/sor2171/backend/config/SerializationConfig.kt
new file mode 100644
index 0000000..04a782f
--- /dev/null
+++ b/backend/src/main/kotlin/com/github/sor2171/backend/config/SerializationConfig.kt
@@ -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
+ }
+}
\ No newline at end of file
diff --git a/backend/src/main/kotlin/com/github/sor2171/backend/controller/AuthorizeController.kt b/backend/src/main/kotlin/com/github/sor2171/backend/controller/AuthorizeController.kt
new file mode 100644
index 0000000..68f1a64
--- /dev/null
+++ b/backend/src/main/kotlin/com/github/sor2171/backend/controller/AuthorizeController.kt
@@ -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> {
+ 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> {
+ logger.info("Trying to register")
+ return service.registerEmailAccount(vo)
+ .map { messageHandler(it) }
+ }
+
+ @PostMapping("/reset")
+ fun emailResetPassword(@RequestBody @Valid vo: PasswordResetVO): Mono> {
+ logger.info("Trying to reset password")
+ return service.resetEmailAccountPassword(vo)
+ .map { messageHandler(it) }
+ }
+
+ @GetMapping("/logout")
+ fun logout(exchange: ServerWebExchange): Mono> {
+ 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> {
+ 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 {
+ return if (wrongMessage.isBlank()) {
+ RestBean.success()
+ } else {
+ RestBean.failure(400, null, wrongMessage)
+ }
+ }
+}
\ No newline at end of file
diff --git a/backend/src/main/kotlin/com/github/sor2171/backend/controller/TestController.kt b/backend/src/main/kotlin/com/github/sor2171/backend/controller/TestController.kt
new file mode 100644
index 0000000..bce579f
--- /dev/null
+++ b/backend/src/main/kotlin/com/github/sor2171/backend/controller/TestController.kt
@@ -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 = Mono.just("Hello Kotlin WebFlux!")
+}
\ No newline at end of file
diff --git a/backend/src/main/kotlin/com/github/sor2171/backend/entity/DataCopy.kt b/backend/src/main/kotlin/com/github/sor2171/backend/entity/DataCopy.kt
new file mode 100644
index 0000000..d89eb8c
--- /dev/null
+++ b/backend/src/main/kotlin/com/github/sor2171/backend/entity/DataCopy.kt
@@ -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 toAnotherObject(
+ toClass: KClass,
+ otherProperties: Map
+ ): 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,
+ 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()
+ }
+ }
+}
\ No newline at end of file
diff --git a/backend/src/main/kotlin/com/github/sor2171/backend/entity/RestBean.kt b/backend/src/main/kotlin/com/github/sor2171/backend/entity/RestBean.kt
new file mode 100644
index 0000000..e369909
--- /dev/null
+++ b/backend/src/main/kotlin/com/github/sor2171/backend/entity/RestBean.kt
@@ -0,0 +1,41 @@
+package com.github.sor2171.backend.entity
+
+import kotlinx.serialization.Serializable
+import kotlinx.serialization.json.Json
+
+@Serializable
+data class RestBean(
+ val code: Int,
+ val data: T,
+ val message: String
+) {
+ companion object {
+ fun success(data: T, message: String = "Success"): RestBean {
+ return RestBean(200, data, message)
+ }
+
+ // 针对无 data 返回的情况,统一使用 Any?
+ fun success(message: String = "Success"): RestBean {
+ return RestBean(200, null, message)
+ }
+
+ fun failure(code: Int = 401, data: T, message: String?): RestBean {
+ 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 {
+ val formatMessage = if (message.isBlank()) "" else ": $message"
+ return failure(400, null, "Logout Failed$formatMessage")
+ }
+ }
+}
+
+inline fun RestBean.toJsonString(): String {
+ return Json.encodeToString(this)
+}
\ No newline at end of file
diff --git a/backend/src/main/kotlin/com/github/sor2171/backend/entity/dto/Account.kt b/backend/src/main/kotlin/com/github/sor2171/backend/entity/dto/Account.kt
new file mode 100644
index 0000000..3ad5ef2
--- /dev/null
+++ b/backend/src/main/kotlin/com/github/sor2171/backend/entity/dto/Account.kt
@@ -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
\ No newline at end of file
diff --git a/backend/src/main/kotlin/com/github/sor2171/backend/entity/dto/EmailVerificationMsg.kt b/backend/src/main/kotlin/com/github/sor2171/backend/entity/dto/EmailVerificationMsg.kt
new file mode 100644
index 0000000..38cb443
--- /dev/null
+++ b/backend/src/main/kotlin/com/github/sor2171/backend/entity/dto/EmailVerificationMsg.kt
@@ -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
+)
\ No newline at end of file
diff --git a/backend/src/main/kotlin/com/github/sor2171/backend/entity/vo/request/EmailRegisterVO.kt b/backend/src/main/kotlin/com/github/sor2171/backend/entity/vo/request/EmailRegisterVO.kt
new file mode 100644
index 0000000..adb42c5
--- /dev/null
+++ b/backend/src/main/kotlin/com/github/sor2171/backend/entity/vo/request/EmailRegisterVO.kt
@@ -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 = "",
+)
\ No newline at end of file
diff --git a/backend/src/main/kotlin/com/github/sor2171/backend/entity/vo/request/PasswordResetVO.kt b/backend/src/main/kotlin/com/github/sor2171/backend/entity/vo/request/PasswordResetVO.kt
new file mode 100644
index 0000000..63e4527
--- /dev/null
+++ b/backend/src/main/kotlin/com/github/sor2171/backend/entity/vo/request/PasswordResetVO.kt
@@ -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 = "",
+)
\ No newline at end of file
diff --git a/backend/src/main/kotlin/com/github/sor2171/backend/entity/vo/response/AuthorizeVO.kt b/backend/src/main/kotlin/com/github/sor2171/backend/entity/vo/response/AuthorizeVO.kt
new file mode 100644
index 0000000..ba8461b
--- /dev/null
+++ b/backend/src/main/kotlin/com/github/sor2171/backend/entity/vo/response/AuthorizeVO.kt
@@ -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(),
+)
\ No newline at end of file
diff --git a/backend/src/main/kotlin/com/github/sor2171/backend/entity/vo/response/ReloginVO.kt b/backend/src/main/kotlin/com/github/sor2171/backend/entity/vo/response/ReloginVO.kt
new file mode 100644
index 0000000..afcda8e
--- /dev/null
+++ b/backend/src/main/kotlin/com/github/sor2171/backend/entity/vo/response/ReloginVO.kt
@@ -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 = "",
+)
\ No newline at end of file
diff --git a/backend/src/main/kotlin/com/github/sor2171/backend/exception/ValidationController.kt b/backend/src/main/kotlin/com/github/sor2171/backend/exception/ValidationController.kt
new file mode 100644
index 0000000..18dfa6f
--- /dev/null
+++ b/backend/src/main/kotlin/com/github/sor2171/backend/exception/ValidationController.kt
@@ -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 {
+ log.warn("Resolve [${e.javaClass.name}: ${e.message}]")
+ return RestBean.failure(
+ 400,
+ null,
+ "parameter validation error"
+ )
+ }
+}
\ No newline at end of file
diff --git a/backend/src/main/kotlin/com/github/sor2171/backend/filter/CorsFilter.kt b/backend/src/main/kotlin/com/github/sor2171/backend/filter/CorsFilter.kt
new file mode 100644
index 0000000..17ecc3d
--- /dev/null
+++ b/backend/src/main/kotlin/com/github/sor2171/backend/filter/CorsFilter.kt
@@ -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)
+ }
+}
\ No newline at end of file
diff --git a/backend/src/main/kotlin/com/github/sor2171/backend/filter/FlowLimitFilter.kt b/backend/src/main/kotlin/com/github/sor2171/backend/filter/FlowLimitFilter.kt
new file mode 100644
index 0000000..13e000a
--- /dev/null
+++ b/backend/src/main/kotlin/com/github/sor2171/backend/filter/FlowLimitFilter.kt
@@ -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 {
+ 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 {
+ 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 {
+ 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)
+ }
+ }
+ }
+ }
+ }
+}
\ No newline at end of file
diff --git a/backend/src/main/kotlin/com/github/sor2171/backend/filter/JwtAuthorizeFilter.kt b/backend/src/main/kotlin/com/github/sor2171/backend/filter/JwtAuthorizeFilter.kt
new file mode 100644
index 0000000..ddc53f5
--- /dev/null
+++ b/backend/src/main/kotlin/com/github/sor2171/backend/filter/JwtAuthorizeFilter.kt
@@ -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 {
+ 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)
+ }
+ }
+}
\ No newline at end of file
diff --git a/backend/src/main/kotlin/com/github/sor2171/backend/listener/MailQueueListener.kt b/backend/src/main/kotlin/com/github/sor2171/backend/listener/MailQueueListener.kt
new file mode 100644
index 0000000..36320f7
--- /dev/null
+++ b/backend/src/main/kotlin/com/github/sor2171/backend/listener/MailQueueListener.kt
@@ -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(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
+ }
+}
\ No newline at end of file
diff --git a/backend/src/main/kotlin/com/github/sor2171/backend/mapper/AccountMapper.kt b/backend/src/main/kotlin/com/github/sor2171/backend/mapper/AccountMapper.kt
new file mode 100644
index 0000000..d46b96b
--- /dev/null
+++ b/backend/src/main/kotlin/com/github/sor2171/backend/mapper/AccountMapper.kt
@@ -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
\ No newline at end of file
diff --git a/backend/src/main/kotlin/com/github/sor2171/backend/service/AccountService.kt b/backend/src/main/kotlin/com/github/sor2171/backend/service/AccountService.kt
new file mode 100644
index 0000000..29c9025
--- /dev/null
+++ b/backend/src/main/kotlin/com/github/sor2171/backend/service/AccountService.kt
@@ -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