Add users validation
This commit is contained in:
@@ -4,6 +4,8 @@ import be.vandewalleh.entities.User
|
||||
import be.vandewalleh.extensions.respondStatus
|
||||
import be.vandewalleh.extensions.userId
|
||||
import be.vandewalleh.services.UserService
|
||||
import be.vandewalleh.validation.receiveValidated
|
||||
import be.vandewalleh.validation.user.registerValidator
|
||||
import io.ktor.application.*
|
||||
import io.ktor.auth.*
|
||||
import io.ktor.http.*
|
||||
@@ -18,14 +20,9 @@ import java.time.LocalDateTime
|
||||
fun Routing.user(kodein: Kodein) {
|
||||
val userService by kodein.instance<UserService>()
|
||||
|
||||
post("/user/test") {
|
||||
val user = call.receive<User>()
|
||||
call.respond(user)
|
||||
}
|
||||
|
||||
route("/user") {
|
||||
post {
|
||||
val user = call.receive<User>()
|
||||
val user = call.receiveValidated(registerValidator)
|
||||
|
||||
if (userService.userExists(user.username, user.email))
|
||||
return@post call.respondStatus(HttpStatusCode.Conflict)
|
||||
@@ -39,7 +36,7 @@ fun Routing.user(kodein: Kodein) {
|
||||
|
||||
authenticate {
|
||||
put {
|
||||
val user = call.receive<User>()
|
||||
val user = call.receiveValidated(registerValidator)
|
||||
|
||||
if (userService.userExists(user.username, user.email))
|
||||
return@put call.respond(HttpStatusCode.Conflict)
|
||||
|
||||
@@ -0,0 +1,14 @@
|
||||
package be.vandewalleh.validation
|
||||
|
||||
import am.ik.yavi.core.Validator
|
||||
import am.ik.yavi.core.ViolationDetail
|
||||
import io.ktor.application.*
|
||||
import io.ktor.request.*
|
||||
|
||||
suspend inline fun <reified T : Any> ApplicationCall.receiveValidated(validator: Validator<T>): T {
|
||||
val value: T = receive()
|
||||
validator.validate(value).throwIfInvalid { ValidationException(it.details()) }
|
||||
return value
|
||||
}
|
||||
|
||||
data class ValidationException(val details: List<ViolationDetail>) : RuntimeException()
|
||||
@@ -0,0 +1,18 @@
|
||||
package be.vandewalleh.validation.user
|
||||
|
||||
import am.ik.yavi.builder.ValidatorBuilder
|
||||
import am.ik.yavi.builder.konstraint
|
||||
import am.ik.yavi.core.Validator
|
||||
import be.vandewalleh.entities.User
|
||||
|
||||
val registerValidator: Validator<User> = ValidatorBuilder.of<User>()
|
||||
.konstraint(User::username) {
|
||||
notNull().lessThanOrEqual(50).greaterThanOrEqual(3)
|
||||
}
|
||||
.konstraint(User::email) {
|
||||
notNull().notEmpty().lessThanOrEqual(255).email()
|
||||
}
|
||||
.konstraint(User::password) {
|
||||
notNull().greaterThanOrEqual(6)
|
||||
}
|
||||
.build()
|
||||
Reference in New Issue
Block a user