Skip to content

Commit

Permalink
refactor: remove JsonSchemaAop
Browse files Browse the repository at this point in the history
  • Loading branch information
Handiwork committed Apr 19, 2024
1 parent 0109cea commit d2e01e4
Show file tree
Hide file tree
Showing 12 changed files with 93 additions and 124 deletions.

This file was deleted.

86 changes: 0 additions & 86 deletions src/main/kotlin/plus/maa/backend/common/aop/JsonSchemaAop.kt

This file was deleted.

Original file line number Diff line number Diff line change
@@ -1,17 +1,17 @@
package plus.maa.backend.config.accesslimit

import com.fasterxml.jackson.databind.ObjectMapper
import org.springframework.context.annotation.Configuration
import org.springframework.data.redis.core.StringRedisTemplate
import org.springframework.web.servlet.config.annotation.InterceptorRegistry
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer
import plus.maa.backend.service.DataTransferService

@Configuration
class AccessLimitConfig(
private val stringRedisTemplate: StringRedisTemplate,
private val objectMapper: ObjectMapper,
private val dataTransferService: DataTransferService,
) : WebMvcConfigurer {
override fun addInterceptors(registry: InterceptorRegistry) {
registry.addInterceptor(AccessLimitInterceptor(stringRedisTemplate, objectMapper))
registry.addInterceptor(AccessLimitInterceptor(stringRedisTemplate, dataTransferService))
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
package plus.maa.backend.config.validation

import jakarta.validation.Constraint
import jakarta.validation.Payload
import kotlin.reflect.KClass

@MustBeDocumented
@Constraint(validatedBy = [JsonSchemaMatchValidator::class])
@Target(AnnotationTarget.FIELD)
@Retention(AnnotationRetention.RUNTIME)
annotation class JsonSchemaMatch(
val message: String = "Not Satisfying Json Schema",
val schema: String,
val groups: Array<KClass<*>> = [],
val payload: Array<KClass<out Payload>> = [],
)
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
package plus.maa.backend.config.validation

import jakarta.validation.ConstraintValidator
import jakarta.validation.ConstraintValidatorContext
import org.everit.json.schema.Schema
import org.everit.json.schema.loader.SchemaLoader
import org.json.JSONObject
import org.json.JSONTokener
import org.springframework.core.io.ClassPathResource

class JsonSchemaMatchValidator : ConstraintValidator<JsonSchemaMatch, String> {
private lateinit var schema: String
override fun initialize(constraintAnnotation: JsonSchemaMatch) {
super.initialize(constraintAnnotation)
schema = constraintAnnotation.schema
}

override fun isValid(text: String?, ctx: ConstraintValidatorContext): Boolean {
try {
if (text == null) return true
val validator = validators[schema] ?: return false
validator.validate(text.let(::JSONObject))
return true
} catch (e: Exception) {
ctx.disableDefaultConstraintViolation()
ctx.buildConstraintViolationWithTemplate(e.message).addConstraintViolation()
return false
}
}

companion object {
const val COPILOT_SCHEMA_JSON = "static/templates/maa-copilot-schema.json"
val validators = mapOf(
loadSchema(COPILOT_SCHEMA_JSON),
)

@Suppress("SameParameterValue")
private fun loadSchema(path: String): Pair<String, Schema> {
val schema = ClassPathResource(path).inputStream.let(::JSONTokener).let(::JSONObject).let(SchemaLoader::load)
return path to schema
}
}
}
19 changes: 19 additions & 0 deletions src/main/kotlin/plus/maa/backend/config/validation/RatingType.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
package plus.maa.backend.config.validation

import jakarta.validation.Constraint
import jakarta.validation.Payload
import jakarta.validation.ReportAsSingleViolation
import jakarta.validation.constraints.Pattern
import kotlin.reflect.KClass

@MustBeDocumented
@Target(AnnotationTarget.FIELD)
@Retention(AnnotationRetention.RUNTIME)
@Constraint(validatedBy = [])
@ReportAsSingleViolation
@Pattern(regexp = "Like|Dislike|None")
annotation class RatingType(
val message: String = "The rating must be one of Like, Dislike, None",
val groups: Array<KClass<*>> = [],
val payload: Array<KClass<out Payload>> = [],
)
Original file line number Diff line number Diff line change
Expand Up @@ -4,15 +4,13 @@ import io.swagger.v3.oas.annotations.Operation
import io.swagger.v3.oas.annotations.responses.ApiResponse
import io.swagger.v3.oas.annotations.tags.Tag
import jakarta.validation.Valid
import jakarta.validation.constraints.NotBlank
import org.springdoc.core.annotations.ParameterObject
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 plus.maa.backend.common.annotation.JsonSchema
import plus.maa.backend.common.annotation.SensitiveWordDetection
import plus.maa.backend.config.doc.RequireJwt
import plus.maa.backend.config.security.AuthenticationHelper
Expand Down Expand Up @@ -62,7 +60,6 @@ class CommentsAreaController(
return success("评论已删除")
}

@JsonSchema
@Operation(summary = "为评论点赞")
@ApiResponse(description = "点赞结果")
@RequireJwt
Expand All @@ -84,7 +81,7 @@ class CommentsAreaController(
@Operation(summary = "设置通知接收状态")
@RequireJwt
@GetMapping("/status")
fun modifyStatus(@RequestParam id: @NotBlank String, @RequestParam status: Boolean): MaaResult<String> {
fun modifyStatus(@RequestParam id: String, @RequestParam status: Boolean): MaaResult<String> {
commentsAreaService.notificationStatus(authHelper.requireUserId(), id, status)
return success("success")
}
Expand Down
10 changes: 3 additions & 7 deletions src/main/kotlin/plus/maa/backend/controller/CopilotController.kt
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,6 @@ 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 plus.maa.backend.common.annotation.JsonSchema
import plus.maa.backend.common.annotation.SensitiveWordDetection
import plus.maa.backend.config.doc.RequireJwt
import plus.maa.backend.config.security.AuthenticationHelper
Expand Down Expand Up @@ -45,12 +44,11 @@ class CopilotController(
@Operation(summary = "上传作业")
@ApiResponse(description = "上传作业结果")
@RequireJwt
@JsonSchema
@SensitiveWordDetection(
"#request.content != null ? #objectMapper.readTree(#request.content).get('doc')?.toString() : null",
)
@PostMapping("/upload")
fun uploadCopilot(@RequestBody request: CopilotCUDRequest): MaaResult<Long> =
fun uploadCopilot(@RequestBody @Valid request: CopilotCUDRequest): MaaResult<Long> =
success(copilotService.upload(helper.requireUserId(), request.content))

@Operation(summary = "删除作业")
Expand Down Expand Up @@ -83,21 +81,19 @@ class CopilotController(
@Operation(summary = "更新作业")
@ApiResponse(description = "更新结果")
@RequireJwt
@JsonSchema
@SensitiveWordDetection(
"#copilotCUDRequest.content != null ? #objectMapper.readTree(#copilotCUDRequest.content).get('doc')?.toString() : null",
)
@PostMapping("/update")
fun updateCopilot(@RequestBody copilotCUDRequest: CopilotCUDRequest): MaaResult<Unit> {
fun updateCopilot(@RequestBody @Valid copilotCUDRequest: CopilotCUDRequest): MaaResult<Unit> {
copilotService.update(helper.requireUserId(), copilotCUDRequest)
return success()
}

@Operation(summary = "为作业评分")
@ApiResponse(description = "评分结果")
@JsonSchema
@PostMapping("/rating")
fun ratesCopilotOperation(@RequestBody copilotRatingReq: CopilotRatingReq): MaaResult<String> {
fun ratesCopilotOperation(@RequestBody @Valid copilotRatingReq: CopilotRatingReq): MaaResult<String> {
copilotService.rates(helper.obtainUserIdOrIpAddress(), copilotRatingReq)
return success("评分成功")
}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package plus.maa.backend.controller.request.comments

import jakarta.validation.constraints.NotBlank
import plus.maa.backend.config.validation.RatingType

/**
* @author LoMu
Expand All @@ -10,5 +11,6 @@ data class CommentsRatingDTO(
@field:NotBlank(message = "评分id不可为空")
val commentId: String,
@field:NotBlank(message = "评分不能为空")
@field:RatingType
val rating: String,
)
Original file line number Diff line number Diff line change
@@ -1,6 +1,10 @@
package plus.maa.backend.controller.request.copilot

import plus.maa.backend.config.validation.JsonSchemaMatch
import plus.maa.backend.config.validation.JsonSchemaMatchValidator

data class CopilotCUDRequest(
@JsonSchemaMatch(schema = JsonSchemaMatchValidator.COPILOT_SCHEMA_JSON)
val content: String? = null,
val id: Long? = null,
)
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package plus.maa.backend.controller.request.copilot

import jakarta.validation.constraints.NotBlank
import plus.maa.backend.config.validation.RatingType

/**
* @author LoMu
Expand All @@ -10,5 +11,6 @@ data class CopilotRatingReq(
@NotBlank(message = "评分作业id不能为空")
val id: Long,
@NotBlank(message = "评分不能为空")
@RatingType
val rating: String,
)
15 changes: 0 additions & 15 deletions src/main/resources/static/templates/maa-rating-schema.json

This file was deleted.

0 comments on commit d2e01e4

Please sign in to comment.