整理專案目錄並加上ResponseExtension

This commit is contained in:
Raymond Yang 2023-05-15 17:48:59 +08:00
parent 1d6cca58c2
commit 0516a20351
9 changed files with 68 additions and 38 deletions

View File

@ -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.*

View File

@ -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 {

View File

@ -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 <T> ApplicationCall.sendCreated(data: T?) {
this.respond(
status = HttpStatusCode.Created,
message = data ?: mapOf("message" to "success.")
)
}
suspend fun <T : Any> 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
)
}

View File

@ -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(

View File

@ -1,4 +1,4 @@
package com.ray650128.dto
package com.ray650128.model.dto
import io.ktor.server.auth.*
import kotlinx.serialization.Serializable

View File

@ -1,4 +1,4 @@
package com.ray650128.model
package com.ray650128.model.pojo
import kotlinx.serialization.Serializable

View File

@ -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

View File

@ -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<UserDto>()
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<UserDto>()?.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") {

View File

@ -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