From 0516a203514c104cc40ad2df1b094d7455afbd4d Mon Sep 17 00:00:00 2001 From: Raymond Yang Date: Mon, 15 May 2023 17:48:59 +0800 Subject: [PATCH] =?UTF-8?q?=E6=95=B4=E7=90=86=E5=B0=88=E6=A1=88=E7=9B=AE?= =?UTF-8?q?=E9=8C=84=E4=B8=A6=E5=8A=A0=E4=B8=8AResponseExtension?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/main/kotlin/com/ray650128/Application.kt | 3 +- src/main/kotlin/com/ray650128/JwtConfig.kt | 2 +- .../ray650128/extension/ResponseExtension.kt | 42 +++++++++++++++++ .../com/ray650128/extension/UserExtension.kt | 4 +- .../com/ray650128/{ => model}/dto/UserDto.kt | 2 +- .../ray650128/model/{ => pojo}/LoginResult.kt | 2 +- .../com/ray650128/model/{ => pojo}/User.kt | 2 +- .../kotlin/com/ray650128/plugins/Routing.kt | 47 +++++++------------ .../com/ray650128/service/UserService.kt | 2 +- 9 files changed, 68 insertions(+), 38 deletions(-) create mode 100644 src/main/kotlin/com/ray650128/extension/ResponseExtension.kt rename src/main/kotlin/com/ray650128/{ => model}/dto/UserDto.kt (90%) rename src/main/kotlin/com/ray650128/model/{ => pojo}/LoginResult.kt (79%) rename src/main/kotlin/com/ray650128/model/{ => pojo}/User.kt (90%) diff --git a/src/main/kotlin/com/ray650128/Application.kt b/src/main/kotlin/com/ray650128/Application.kt index ac2a800..fc3342a 100644 --- a/src/main/kotlin/com/ray650128/Application.kt +++ b/src/main/kotlin/com/ray650128/Application.kt @@ -1,7 +1,6 @@ package com.ray650128 -import com.ray650128.dto.UserDto -import com.ray650128.model.User +import com.ray650128.model.dto.UserDto import com.ray650128.plugins.configureRouting import com.ray650128.plugins.configureSerialization import io.ktor.server.application.* diff --git a/src/main/kotlin/com/ray650128/JwtConfig.kt b/src/main/kotlin/com/ray650128/JwtConfig.kt index 77a4318..9ecea4a 100644 --- a/src/main/kotlin/com/ray650128/JwtConfig.kt +++ b/src/main/kotlin/com/ray650128/JwtConfig.kt @@ -3,7 +3,7 @@ package com.ray650128 import com.auth0.jwt.JWT import com.auth0.jwt.JWTVerifier import com.auth0.jwt.algorithms.Algorithm -import com.ray650128.dto.UserDto +import com.ray650128.model.dto.UserDto import java.util.* object JwtConfig { diff --git a/src/main/kotlin/com/ray650128/extension/ResponseExtension.kt b/src/main/kotlin/com/ray650128/extension/ResponseExtension.kt new file mode 100644 index 0000000..9d6468d --- /dev/null +++ b/src/main/kotlin/com/ray650128/extension/ResponseExtension.kt @@ -0,0 +1,42 @@ +package com.ray650128.extension + +import com.ray650128.model.ErrorResponse +import io.ktor.http.* +import io.ktor.server.application.* +import io.ktor.server.response.* + + +suspend fun ApplicationCall.sendCreated(data: T?) { + this.respond( + status = HttpStatusCode.Created, + message = data ?: mapOf("message" to "success.") + ) +} + +suspend fun ApplicationCall.sendSuccess(data: T?) { + this.respond( + status = HttpStatusCode.OK, + message = data ?: mapOf("message" to "success.") + ) +} + +suspend fun ApplicationCall.sendUnauthorized(errorResponse: ErrorResponse) { + this.respond( + status = HttpStatusCode.Unauthorized, + message = errorResponse + ) +} + +suspend fun ApplicationCall.sendBadRequest(errorResponse: ErrorResponse) { + this.respond( + status = HttpStatusCode.BadRequest, + message = errorResponse + ) +} + +suspend fun ApplicationCall.sendNotFound(errorResponse: ErrorResponse) { + this.respond( + status = HttpStatusCode.NotFound, + message = errorResponse + ) +} diff --git a/src/main/kotlin/com/ray650128/extension/UserExtension.kt b/src/main/kotlin/com/ray650128/extension/UserExtension.kt index 4ddead1..0d50a36 100644 --- a/src/main/kotlin/com/ray650128/extension/UserExtension.kt +++ b/src/main/kotlin/com/ray650128/extension/UserExtension.kt @@ -1,7 +1,7 @@ package com.ray650128.extension -import com.ray650128.dto.UserDto -import com.ray650128.model.User +import com.ray650128.model.dto.UserDto +import com.ray650128.model.pojo.User fun User.toDto(): UserDto = UserDto( diff --git a/src/main/kotlin/com/ray650128/dto/UserDto.kt b/src/main/kotlin/com/ray650128/model/dto/UserDto.kt similarity index 90% rename from src/main/kotlin/com/ray650128/dto/UserDto.kt rename to src/main/kotlin/com/ray650128/model/dto/UserDto.kt index b15203d..ed5bb58 100644 --- a/src/main/kotlin/com/ray650128/dto/UserDto.kt +++ b/src/main/kotlin/com/ray650128/model/dto/UserDto.kt @@ -1,4 +1,4 @@ -package com.ray650128.dto +package com.ray650128.model.dto import io.ktor.server.auth.* import kotlinx.serialization.Serializable diff --git a/src/main/kotlin/com/ray650128/model/LoginResult.kt b/src/main/kotlin/com/ray650128/model/pojo/LoginResult.kt similarity index 79% rename from src/main/kotlin/com/ray650128/model/LoginResult.kt rename to src/main/kotlin/com/ray650128/model/pojo/LoginResult.kt index c78d64f..e809406 100644 --- a/src/main/kotlin/com/ray650128/model/LoginResult.kt +++ b/src/main/kotlin/com/ray650128/model/pojo/LoginResult.kt @@ -1,4 +1,4 @@ -package com.ray650128.model +package com.ray650128.model.pojo import kotlinx.serialization.Serializable diff --git a/src/main/kotlin/com/ray650128/model/User.kt b/src/main/kotlin/com/ray650128/model/pojo/User.kt similarity index 90% rename from src/main/kotlin/com/ray650128/model/User.kt rename to src/main/kotlin/com/ray650128/model/pojo/User.kt index 74c87be..650c4db 100644 --- a/src/main/kotlin/com/ray650128/model/User.kt +++ b/src/main/kotlin/com/ray650128/model/pojo/User.kt @@ -1,4 +1,4 @@ -package com.ray650128.model +package com.ray650128.model.pojo import org.bson.codecs.pojo.annotations.BsonId import org.litote.kmongo.Id diff --git a/src/main/kotlin/com/ray650128/plugins/Routing.kt b/src/main/kotlin/com/ray650128/plugins/Routing.kt index 4565709..c1edf84 100644 --- a/src/main/kotlin/com/ray650128/plugins/Routing.kt +++ b/src/main/kotlin/com/ray650128/plugins/Routing.kt @@ -1,12 +1,11 @@ package com.ray650128.plugins import com.ray650128.JwtConfig -import com.ray650128.dto.UserDto -import com.ray650128.extension.toDto -import com.ray650128.extension.toUser +import com.ray650128.extension.* +import com.ray650128.model.dto.UserDto import com.ray650128.model.ErrorResponse -import com.ray650128.model.LoginResult -import com.ray650128.model.User +import com.ray650128.model.pojo.LoginResult +import com.ray650128.model.pojo.User import com.ray650128.service.UserService import io.ktor.http.* import io.ktor.server.routing.* @@ -19,24 +18,23 @@ fun Application.configureRouting() { val service = UserService() routing { - get("/") { - call.respondText("Hello World!") - } - route("/api") { route("/v1") { post("/register") { val request = call.receive() + if (service.findByAccount(request.account) != null) { + call.sendBadRequest(ErrorResponse("User has existed.")) + return@post + } val newToken = JwtConfig.generateToken(request) val user = request.toUser().apply { token = newToken createAt = System.currentTimeMillis() } - service.create(user) - ?.let { userId -> - call.response.headers.append("My-User-Id-Header", userId.toString()) - call.respond(HttpStatusCode.Created, LoginResult(request.account, newToken)) - } ?: call.respond(HttpStatusCode.BadRequest, ErrorResponse.BAD_REQUEST_RESPONSE) + service.create(user)?.let { userId -> + call.response.headers.append("My-User-Id-Header", userId.toString()) + call.sendCreated(LoginResult(request.account, newToken)) + } ?: call.sendBadRequest(ErrorResponse.BAD_REQUEST_RESPONSE) } post("/login") { @@ -50,29 +48,20 @@ fun Application.configureRouting() { user.updatedAt = System.currentTimeMillis() service.updateById(user.id.toString(), user) } - call.respond(HttpStatusCode.OK, LoginResult(request.account, token!!)) + call.sendSuccess(LoginResult(request.account, token!!)) } else { - call.respond( - status = HttpStatusCode.Unauthorized, - message = mapOf("message" to "Account or Password wrong.") - ) + call.sendUnauthorized(ErrorResponse("Account or Password wrong.")) } } authenticate { post("/logout") { val account = call.authentication.principal()?.account ?: run { - call.respond( - status = HttpStatusCode.Unauthorized, - message = mapOf("message" to "token wrong") - ) + call.sendUnauthorized(ErrorResponse("Unauthorized")) return@post } val user = service.findByAccount(account) ?: run { - call.respond( - status = HttpStatusCode.Unauthorized, - message = mapOf("message" to "token wrong") - ) + call.sendUnauthorized(ErrorResponse("Unauthorized")) return@post } user.apply { @@ -80,7 +69,7 @@ fun Application.configureRouting() { updatedAt = System.currentTimeMillis() } service.updateById(user.id.toString(), user) - call.respond(HttpStatusCode.OK, "User has logged out") + call.sendSuccess(null) } } } @@ -94,7 +83,7 @@ fun Application.configureRouting() { val id = call.parameters["id"].toString() service.findById(id) ?.let { foundPerson -> call.respond(foundPerson.toDto()) } - ?: call.respond(HttpStatusCode.NotFound, ErrorResponse.NOT_FOUND_RESPONSE) + ?: call.sendNotFound(ErrorResponse.NOT_FOUND_RESPONSE) } get("/search") { diff --git a/src/main/kotlin/com/ray650128/service/UserService.kt b/src/main/kotlin/com/ray650128/service/UserService.kt index 5163ec0..f17bec2 100644 --- a/src/main/kotlin/com/ray650128/service/UserService.kt +++ b/src/main/kotlin/com/ray650128/service/UserService.kt @@ -1,6 +1,6 @@ package com.ray650128.service -import com.ray650128.model.User +import com.ray650128.model.pojo.User import org.bson.types.ObjectId import org.litote.kmongo.* import org.litote.kmongo.id.toId