diff --git a/src/main/kotlin/dev/usbharu/hideout/Application.kt b/src/main/kotlin/dev/usbharu/hideout/Application.kt index 0d19054d..d711ea21 100644 --- a/src/main/kotlin/dev/usbharu/hideout/Application.kt +++ b/src/main/kotlin/dev/usbharu/hideout/Application.kt @@ -14,14 +14,13 @@ import dev.usbharu.hideout.domain.model.job.ReceiveFollowJob import dev.usbharu.hideout.plugins.* import dev.usbharu.hideout.query.FollowerQueryService import dev.usbharu.hideout.query.UserQueryService -import dev.usbharu.hideout.repository.IUserRepository import dev.usbharu.hideout.routing.register import dev.usbharu.hideout.service.activitypub.ActivityPubService import dev.usbharu.hideout.service.activitypub.ActivityPubUserService import dev.usbharu.hideout.service.api.IPostApiService import dev.usbharu.hideout.service.api.IUserApiService +import dev.usbharu.hideout.service.api.UserAuthApiService import dev.usbharu.hideout.service.auth.HttpSignatureVerifyService -import dev.usbharu.hideout.service.auth.IJwtService import dev.usbharu.hideout.service.core.IMetaService import dev.usbharu.hideout.service.core.IServerInitialiseService import dev.usbharu.hideout.service.core.IdGenerateService @@ -29,7 +28,6 @@ import dev.usbharu.hideout.service.core.TwitterSnowflakeIdGenerateService import dev.usbharu.hideout.service.job.JobQueueParentService import dev.usbharu.hideout.service.job.KJobJobQueueParentService import dev.usbharu.hideout.service.reaction.IReactionService -import dev.usbharu.hideout.service.user.IUserAuthService import dev.usbharu.hideout.service.user.IUserService import dev.usbharu.kjob.exposed.ExposedKJob import io.ktor.client.* @@ -97,6 +95,7 @@ fun Application.parent() { } } configureKoin(module, HideoutModule().module) + configureStatusPages() runBlocking { inject().value.init() } @@ -105,7 +104,7 @@ fun Application.parent() { configureStaticRouting() configureMonitoring() configureSerialization() - register(inject().value) + register(inject().value) configureSecurity( inject().value, @@ -119,11 +118,9 @@ fun Application.parent() { postService = inject().value, userApiService = inject().value, reactionService = inject().value, - userAuthService = inject().value, - userRepository = inject().value, - jwtService = inject().value, userQueryService = inject().value, - followerQueryService = inject().value + followerQueryService = inject().value, + userAuthApiService = inject().value ) } diff --git a/src/main/kotlin/dev/usbharu/hideout/exception/InvalidUsernameOrPasswordException.kt b/src/main/kotlin/dev/usbharu/hideout/exception/InvalidUsernameOrPasswordException.kt new file mode 100644 index 00000000..1aa9c789 --- /dev/null +++ b/src/main/kotlin/dev/usbharu/hideout/exception/InvalidUsernameOrPasswordException.kt @@ -0,0 +1,14 @@ +package dev.usbharu.hideout.exception + +class InvalidUsernameOrPasswordException : Exception { + constructor() : super() + constructor(message: String?) : super(message) + constructor(message: String?, cause: Throwable?) : super(message, cause) + constructor(cause: Throwable?) : super(cause) + constructor(message: String?, cause: Throwable?, enableSuppression: Boolean, writableStackTrace: Boolean) : super( + message, + cause, + enableSuppression, + writableStackTrace + ) +} diff --git a/src/main/kotlin/dev/usbharu/hideout/exception/UsernameAlreadyExistException.kt b/src/main/kotlin/dev/usbharu/hideout/exception/UsernameAlreadyExistException.kt new file mode 100644 index 00000000..c1791950 --- /dev/null +++ b/src/main/kotlin/dev/usbharu/hideout/exception/UsernameAlreadyExistException.kt @@ -0,0 +1,14 @@ +package dev.usbharu.hideout.exception + +class UsernameAlreadyExistException : Exception { + constructor() : super() + constructor(message: String?) : super(message) + constructor(message: String?, cause: Throwable?) : super(message, cause) + constructor(cause: Throwable?) : super(cause) + constructor(message: String?, cause: Throwable?, enableSuppression: Boolean, writableStackTrace: Boolean) : super( + message, + cause, + enableSuppression, + writableStackTrace + ) +} diff --git a/src/main/kotlin/dev/usbharu/hideout/plugins/Routing.kt b/src/main/kotlin/dev/usbharu/hideout/plugins/Routing.kt index ca62091c..23e59607 100644 --- a/src/main/kotlin/dev/usbharu/hideout/plugins/Routing.kt +++ b/src/main/kotlin/dev/usbharu/hideout/plugins/Routing.kt @@ -2,7 +2,6 @@ package dev.usbharu.hideout.plugins import dev.usbharu.hideout.query.FollowerQueryService import dev.usbharu.hideout.query.UserQueryService -import dev.usbharu.hideout.repository.IUserRepository import dev.usbharu.hideout.routing.activitypub.inbox import dev.usbharu.hideout.routing.activitypub.outbox import dev.usbharu.hideout.routing.activitypub.usersAP @@ -14,10 +13,9 @@ import dev.usbharu.hideout.service.activitypub.ActivityPubService import dev.usbharu.hideout.service.activitypub.ActivityPubUserService import dev.usbharu.hideout.service.api.IPostApiService import dev.usbharu.hideout.service.api.IUserApiService +import dev.usbharu.hideout.service.api.UserAuthApiService import dev.usbharu.hideout.service.auth.HttpSignatureVerifyService -import dev.usbharu.hideout.service.auth.IJwtService import dev.usbharu.hideout.service.reaction.IReactionService -import dev.usbharu.hideout.service.user.IUserAuthService import dev.usbharu.hideout.service.user.IUserService import io.ktor.server.application.* import io.ktor.server.plugins.autohead.* @@ -32,11 +30,9 @@ fun Application.configureRouting( postService: IPostApiService, userApiService: IUserApiService, reactionService: IReactionService, - userAuthService: IUserAuthService, - userRepository: IUserRepository, - jwtService: IJwtService, userQueryService: UserQueryService, - followerQueryService: FollowerQueryService + followerQueryService: FollowerQueryService, + userAuthApiService: UserAuthApiService ) { install(AutoHeadResponse) routing { @@ -47,7 +43,7 @@ fun Application.configureRouting( route("/api/internal/v1") { posts(postService, reactionService) users(userService, userApiService) - auth(userAuthService, jwtService, userQueryService) + auth(userAuthApiService) } } } diff --git a/src/main/kotlin/dev/usbharu/hideout/plugins/StatusPages.kt b/src/main/kotlin/dev/usbharu/hideout/plugins/StatusPages.kt index 67ffdb1b..92eea7af 100644 --- a/src/main/kotlin/dev/usbharu/hideout/plugins/StatusPages.kt +++ b/src/main/kotlin/dev/usbharu/hideout/plugins/StatusPages.kt @@ -1,5 +1,6 @@ package dev.usbharu.hideout.plugins +import dev.usbharu.hideout.exception.InvalidUsernameOrPasswordException import io.ktor.http.* import io.ktor.server.application.* import io.ktor.server.plugins.statuspages.* @@ -10,8 +11,12 @@ fun Application.configureStatusPages() { exception { call, cause -> call.respondText(text = "400: $cause", status = HttpStatusCode.BadRequest) } + exception { call, _ -> + call.respond(401) + } exception { call, cause -> - call.respondText(text = "500: $cause", status = HttpStatusCode.InternalServerError) + call.respondText(text = "500: ${cause.stackTraceToString()}", status = HttpStatusCode.InternalServerError) + cause.printStackTrace() } } } diff --git a/src/main/kotlin/dev/usbharu/hideout/query/UserQueryService.kt b/src/main/kotlin/dev/usbharu/hideout/query/UserQueryService.kt index eec057f4..6b7f7db6 100644 --- a/src/main/kotlin/dev/usbharu/hideout/query/UserQueryService.kt +++ b/src/main/kotlin/dev/usbharu/hideout/query/UserQueryService.kt @@ -9,4 +9,5 @@ interface UserQueryService { suspend fun findByNameAndDomain(name: String, domain: String): User suspend fun findByUrl(url: String): User suspend fun findByIds(ids: List): List + suspend fun existByNameAndDomain(name: String, domain: String): Boolean } diff --git a/src/main/kotlin/dev/usbharu/hideout/query/UserQueryServiceImpl.kt b/src/main/kotlin/dev/usbharu/hideout/query/UserQueryServiceImpl.kt index e96dea20..3e1e80fe 100644 --- a/src/main/kotlin/dev/usbharu/hideout/query/UserQueryServiceImpl.kt +++ b/src/main/kotlin/dev/usbharu/hideout/query/UserQueryServiceImpl.kt @@ -24,4 +24,8 @@ class UserQueryServiceImpl : UserQueryService { override suspend fun findByIds(ids: List): List = Users.select { Users.id inList ids }.map { it.toUser() } + + override suspend fun existByNameAndDomain(name: String, domain: String): Boolean { + return Users.select { Users.name eq name and (Users.domain eq domain) }.empty().not() + } } diff --git a/src/main/kotlin/dev/usbharu/hideout/routing/RegisterRouting.kt b/src/main/kotlin/dev/usbharu/hideout/routing/RegisterRouting.kt index ced130c3..2e01c939 100644 --- a/src/main/kotlin/dev/usbharu/hideout/routing/RegisterRouting.kt +++ b/src/main/kotlin/dev/usbharu/hideout/routing/RegisterRouting.kt @@ -1,7 +1,6 @@ package dev.usbharu.hideout.routing -import dev.usbharu.hideout.domain.model.hideout.dto.UserCreateDto -import dev.usbharu.hideout.service.user.IUserService +import dev.usbharu.hideout.service.api.IUserApiService import io.ktor.http.* import io.ktor.server.application.* import io.ktor.server.auth.* @@ -9,7 +8,7 @@ import io.ktor.server.request.* import io.ktor.server.response.* import io.ktor.server.routing.* -fun Application.register(userService: IUserService) { +fun Application.register(userApiService: IUserApiService) { routing { get("/register") { val principal = call.principal() @@ -37,10 +36,7 @@ fun Application.register(userService: IUserService) { val parameters = call.receiveParameters() val password = parameters["password"] ?: return@post call.respondRedirect("/register") val username = parameters["username"] ?: return@post call.respondRedirect("/register") - if (userService.usernameAlreadyUse(username)) { - return@post call.respondRedirect("/register") - } - userService.createLocalUser(UserCreateDto(username, username, "", password)) + userApiService.createUser(username, password) call.respondRedirect("/users/$username") } } diff --git a/src/main/kotlin/dev/usbharu/hideout/routing/activitypub/UserRouting.kt b/src/main/kotlin/dev/usbharu/hideout/routing/activitypub/UserRouting.kt index df0d6d37..f381472b 100644 --- a/src/main/kotlin/dev/usbharu/hideout/routing/activitypub/UserRouting.kt +++ b/src/main/kotlin/dev/usbharu/hideout/routing/activitypub/UserRouting.kt @@ -13,6 +13,7 @@ import io.ktor.server.application.* import io.ktor.server.request.* import io.ktor.server.response.* import io.ktor.server.routing.* +import org.jetbrains.exposed.sql.transactions.experimental.newSuspendedTransaction fun Routing.usersAP( activityPubUserService: ActivityPubUserService, @@ -32,11 +33,18 @@ fun Routing.usersAP( ) } get { - val userEntity = userQueryService.findByNameAndDomain( - call.parameters["name"] ?: throw ParameterNotExistException("Parameter(name='name') does not exist."), - Config.configData.domain - ) - call.respondText(userEntity.toString() + "\n" + followerQueryService.findFollowersById(userEntity.id)) + + + // TODO: 暫定処置なので治す + newSuspendedTransaction { + + val userEntity = userQueryService.findByNameAndDomain( + call.parameters["name"] + ?: throw ParameterNotExistException("Parameter(name='name') does not exist."), + Config.configData.domain + ) + call.respondText(userEntity.toString() + "\n" + followerQueryService.findFollowersById(userEntity.id)) + } } } } @@ -46,7 +54,7 @@ class ContentTypeRouteSelector(private vararg val contentType: ContentType) : Ro context.call.application.log.debug("Accept: ${context.call.request.accept()}") val requestContentType = context.call.request.accept() ?: return RouteSelectorEvaluation.FailedParameter return if (requestContentType.split(",") - .any { contentType.any { contentType -> contentType.match(it) } } + .any { contentType.any { contentType -> contentType.match(it) } } ) { RouteSelectorEvaluation.Constant } else { diff --git a/src/main/kotlin/dev/usbharu/hideout/routing/api/internal/v1/Auth.kt b/src/main/kotlin/dev/usbharu/hideout/routing/api/internal/v1/Auth.kt index bd0d280a..610d39b4 100644 --- a/src/main/kotlin/dev/usbharu/hideout/routing/api/internal/v1/Auth.kt +++ b/src/main/kotlin/dev/usbharu/hideout/routing/api/internal/v1/Auth.kt @@ -1,13 +1,9 @@ package dev.usbharu.hideout.routing.api.internal.v1 -import dev.usbharu.hideout.config.Config import dev.usbharu.hideout.domain.model.hideout.form.RefreshToken import dev.usbharu.hideout.domain.model.hideout.form.UserLogin import dev.usbharu.hideout.plugins.TOKEN_AUTH -import dev.usbharu.hideout.query.UserQueryService -import dev.usbharu.hideout.service.auth.IJwtService -import dev.usbharu.hideout.service.user.IUserAuthService -import io.ktor.http.* +import dev.usbharu.hideout.service.api.UserAuthApiService import io.ktor.server.application.* import io.ktor.server.auth.* import io.ktor.server.auth.jwt.* @@ -15,26 +11,15 @@ import io.ktor.server.request.* import io.ktor.server.response.* import io.ktor.server.routing.* -fun Route.auth( - userAuthService: IUserAuthService, - jwtService: IJwtService, - userQueryService: UserQueryService -) { +fun Route.auth(userAuthApiService: UserAuthApiService) { post("/login") { val loginUser = call.receive() - val check = userAuthService.verifyAccount(loginUser.username, loginUser.password) - if (check.not()) { - return@post call.respond(HttpStatusCode.Unauthorized) - } - - val user = userQueryService.findByNameAndDomain(loginUser.username, Config.configData.domain) - - return@post call.respond(jwtService.createToken(user)) + return@post call.respond(userAuthApiService.login(loginUser.username, loginUser.password)) } post("/refresh-token") { val refreshToken = call.receive() - return@post call.respond(jwtService.refreshToken(refreshToken)) + return@post call.respond(userAuthApiService.refreshToken(refreshToken)) } authenticate(TOKEN_AUTH) { get("/auth-check") { diff --git a/src/main/kotlin/dev/usbharu/hideout/service/api/IUserApiService.kt b/src/main/kotlin/dev/usbharu/hideout/service/api/IUserApiService.kt index 580d4115..7d902de3 100644 --- a/src/main/kotlin/dev/usbharu/hideout/service/api/IUserApiService.kt +++ b/src/main/kotlin/dev/usbharu/hideout/service/api/IUserApiService.kt @@ -19,4 +19,6 @@ interface IUserApiService { suspend fun findFollowersByAcct(acct: Acct): List suspend fun findFollowingsByAcct(acct: Acct): List + + suspend fun createUser(username: String, password: String): UserResponse } diff --git a/src/main/kotlin/dev/usbharu/hideout/service/api/PostApiServiceImpl.kt b/src/main/kotlin/dev/usbharu/hideout/service/api/PostApiServiceImpl.kt index e04bcd67..3a5cdb0a 100644 --- a/src/main/kotlin/dev/usbharu/hideout/service/api/PostApiServiceImpl.kt +++ b/src/main/kotlin/dev/usbharu/hideout/service/api/PostApiServiceImpl.kt @@ -20,18 +20,20 @@ class PostApiServiceImpl( private val postResponseQueryService: PostResponseQueryService ) : IPostApiService { override suspend fun createPost(postForm: FormPost, userId: Long): PostResponse { - val createdPost = postService.createLocal( - PostCreateDto( - text = postForm.text, - overview = postForm.overview, - visibility = postForm.visibility, - repostId = postForm.repostId, - repolyId = postForm.replyId, - userId = userId + return newSuspendedTransaction { + val createdPost = postService.createLocal( + PostCreateDto( + text = postForm.text, + overview = postForm.overview, + visibility = postForm.visibility, + repostId = postForm.repostId, + repolyId = postForm.replyId, + userId = userId + ) ) - ) - val creator = userRepository.findById(userId) - return PostResponse.from(createdPost, creator!!) + val creator = userRepository.findById(userId) + PostResponse.from(createdPost, creator!!) + } } @Suppress("InjectDispatcher") @@ -47,8 +49,16 @@ class PostApiServiceImpl( maxId: Long?, limit: Int?, userId: Long? - ): List = - postResponseQueryService.findAll(since?.toEpochMilli(), until?.toEpochMilli(), minId, maxId, limit, userId) + ): List = newSuspendedTransaction { + postResponseQueryService.findAll( + since?.toEpochMilli(), + until?.toEpochMilli(), + minId, + maxId, + limit, + userId + ) + } override suspend fun getByUser( nameOrId: String, diff --git a/src/main/kotlin/dev/usbharu/hideout/service/api/UserApiServiceImpl.kt b/src/main/kotlin/dev/usbharu/hideout/service/api/UserApiServiceImpl.kt index 70fc8bd3..37ac1890 100644 --- a/src/main/kotlin/dev/usbharu/hideout/service/api/UserApiServiceImpl.kt +++ b/src/main/kotlin/dev/usbharu/hideout/service/api/UserApiServiceImpl.kt @@ -2,16 +2,21 @@ package dev.usbharu.hideout.service.api import dev.usbharu.hideout.config.Config import dev.usbharu.hideout.domain.model.Acct +import dev.usbharu.hideout.domain.model.hideout.dto.UserCreateDto import dev.usbharu.hideout.domain.model.hideout.dto.UserResponse +import dev.usbharu.hideout.exception.UsernameAlreadyExistException import dev.usbharu.hideout.query.FollowerQueryService import dev.usbharu.hideout.query.UserQueryService +import dev.usbharu.hideout.service.user.IUserService +import org.jetbrains.exposed.sql.transactions.experimental.newSuspendedTransaction import org.koin.core.annotation.Single import kotlin.math.min @Single class UserApiServiceImpl( private val userQueryService: UserQueryService, - private val followerQueryService: FollowerQueryService + private val followerQueryService: FollowerQueryService, + private val userService: IUserService ) : IUserApiService { override suspend fun findAll(limit: Int?, offset: Long): List = userQueryService.findAll(min(limit ?: 100, 100), offset).map { UserResponse.from(it) } @@ -37,4 +42,13 @@ class UserApiServiceImpl( override suspend fun findFollowingsByAcct(acct: Acct): List = followerQueryService.findFollowingByNameAndDomain(acct.username, acct.domain ?: Config.configData.domain) .map { UserResponse.from(it) } + + override suspend fun createUser(username: String, password: String): UserResponse { + return newSuspendedTransaction { + if (userQueryService.existByNameAndDomain(username, Config.configData.domain)) { + throw UsernameAlreadyExistException() + } + UserResponse.from(userService.createLocalUser(UserCreateDto(username, username, "", password))) + } + } } diff --git a/src/main/kotlin/dev/usbharu/hideout/service/api/UserAuthApiService.kt b/src/main/kotlin/dev/usbharu/hideout/service/api/UserAuthApiService.kt new file mode 100644 index 00000000..0c8d35f5 --- /dev/null +++ b/src/main/kotlin/dev/usbharu/hideout/service/api/UserAuthApiService.kt @@ -0,0 +1,9 @@ +package dev.usbharu.hideout.service.api + +import dev.usbharu.hideout.domain.model.hideout.dto.JwtToken +import dev.usbharu.hideout.domain.model.hideout.form.RefreshToken + +interface UserAuthApiService { + suspend fun login(username: String, password: String): JwtToken + suspend fun refreshToken(refreshToken: RefreshToken): JwtToken +} diff --git a/src/main/kotlin/dev/usbharu/hideout/service/api/UserAuthApiServiceImpl.kt b/src/main/kotlin/dev/usbharu/hideout/service/api/UserAuthApiServiceImpl.kt new file mode 100644 index 00000000..06f87f3e --- /dev/null +++ b/src/main/kotlin/dev/usbharu/hideout/service/api/UserAuthApiServiceImpl.kt @@ -0,0 +1,34 @@ +package dev.usbharu.hideout.service.api + +import dev.usbharu.hideout.config.Config +import dev.usbharu.hideout.domain.model.hideout.dto.JwtToken +import dev.usbharu.hideout.domain.model.hideout.form.RefreshToken +import dev.usbharu.hideout.exception.InvalidUsernameOrPasswordException +import dev.usbharu.hideout.query.UserQueryService +import dev.usbharu.hideout.service.auth.IJwtService +import dev.usbharu.hideout.service.user.UserAuthService +import org.jetbrains.exposed.sql.transactions.experimental.newSuspendedTransaction +import org.koin.core.annotation.Single + +@Single +class UserAuthApiServiceImpl( + private val userAuthService: UserAuthService, + private val userQueryService: UserQueryService, + private val jwtService: IJwtService +) : UserAuthApiService { + override suspend fun login(username: String, password: String): JwtToken { + return newSuspendedTransaction { + if (userAuthService.verifyAccount(username, password).not()) { + throw InvalidUsernameOrPasswordException() + } + val user = userQueryService.findByNameAndDomain(username, Config.configData.domain) + jwtService.createToken(user) + } + } + + override suspend fun refreshToken(refreshToken: RefreshToken): JwtToken { + return newSuspendedTransaction { + jwtService.refreshToken(refreshToken) + } + } +} diff --git a/src/main/kotlin/dev/usbharu/hideout/service/auth/JwtServiceImpl.kt b/src/main/kotlin/dev/usbharu/hideout/service/auth/JwtServiceImpl.kt index 54195905..daf64a4e 100644 --- a/src/main/kotlin/dev/usbharu/hideout/service/auth/JwtServiceImpl.kt +++ b/src/main/kotlin/dev/usbharu/hideout/service/auth/JwtServiceImpl.kt @@ -13,9 +13,7 @@ import dev.usbharu.hideout.query.UserQueryService import dev.usbharu.hideout.repository.IJwtRefreshTokenRepository import dev.usbharu.hideout.service.core.IMetaService import dev.usbharu.hideout.util.RsaUtil -import kotlinx.coroutines.CoroutineScope -import kotlinx.coroutines.Dispatchers -import kotlinx.coroutines.async +import kotlinx.coroutines.runBlocking import org.koin.core.annotation.Single import java.time.Instant import java.time.temporal.ChronoUnit @@ -30,23 +28,16 @@ class JwtServiceImpl( private val refreshTokenQueryService: JwtRefreshTokenQueryService ) : IJwtService { - private val privateKey by lazy { - CoroutineScope(Dispatchers.IO).async { - RsaUtil.decodeRsaPrivateKey(metaService.getJwtMeta().privateKey) - } + private val privateKey = runBlocking { + RsaUtil.decodeRsaPrivateKey(metaService.getJwtMeta().privateKey) } - private val publicKey by lazy { - CoroutineScope(Dispatchers.IO).async { - RsaUtil.decodeRsaPublicKey(metaService.getJwtMeta().publicKey) - } + private val publicKey = runBlocking { + RsaUtil.decodeRsaPublicKey(metaService.getJwtMeta().publicKey) } - private val keyId by lazy { - CoroutineScope(Dispatchers.IO).async { - metaService.getJwtMeta().kid - } - } + private val keyId = runBlocking { metaService.getJwtMeta().kid } + @Suppress("MagicNumber") override suspend fun createToken(user: User): JwtToken { @@ -54,10 +45,10 @@ class JwtServiceImpl( val token = JWT.create() .withAudience("${Config.configData.url}/users/${user.name}") .withIssuer(Config.configData.url) - .withKeyId(keyId.await().toString()) + .withKeyId(keyId.toString()) .withClaim("uid", user.id) .withExpiresAt(now.plus(30, ChronoUnit.MINUTES)) - .sign(Algorithm.RSA256(publicKey.await(), privateKey.await())) + .sign(Algorithm.RSA256(publicKey, privateKey)) val jwtRefreshToken = JwtRefreshToken( id = refreshTokenRepository.generateId(), diff --git a/src/main/kotlin/dev/usbharu/hideout/service/core/MetaServiceImpl.kt b/src/main/kotlin/dev/usbharu/hideout/service/core/MetaServiceImpl.kt index 9e922312..ebd15efa 100644 --- a/src/main/kotlin/dev/usbharu/hideout/service/core/MetaServiceImpl.kt +++ b/src/main/kotlin/dev/usbharu/hideout/service/core/MetaServiceImpl.kt @@ -4,13 +4,15 @@ import dev.usbharu.hideout.domain.model.hideout.entity.Jwt import dev.usbharu.hideout.domain.model.hideout.entity.Meta import dev.usbharu.hideout.exception.NotInitException import dev.usbharu.hideout.repository.IMetaRepository +import org.jetbrains.exposed.sql.transactions.experimental.newSuspendedTransaction import org.koin.core.annotation.Single @Single class MetaServiceImpl(private val metaRepository: IMetaRepository) : IMetaService { - override suspend fun getMeta(): Meta = metaRepository.get() ?: throw NotInitException("Meta is null") + override suspend fun getMeta(): Meta = + newSuspendedTransaction { metaRepository.get() ?: throw NotInitException("Meta is null") } - override suspend fun updateMeta(meta: Meta) { + override suspend fun updateMeta(meta: Meta) = newSuspendedTransaction { metaRepository.save(meta) } diff --git a/src/main/kotlin/dev/usbharu/hideout/service/core/ServerInitialiseServiceImpl.kt b/src/main/kotlin/dev/usbharu/hideout/service/core/ServerInitialiseServiceImpl.kt index ea9b5099..6e9db865 100644 --- a/src/main/kotlin/dev/usbharu/hideout/service/core/ServerInitialiseServiceImpl.kt +++ b/src/main/kotlin/dev/usbharu/hideout/service/core/ServerInitialiseServiceImpl.kt @@ -4,6 +4,7 @@ import dev.usbharu.hideout.domain.model.hideout.entity.Jwt import dev.usbharu.hideout.domain.model.hideout.entity.Meta import dev.usbharu.hideout.repository.IMetaRepository import dev.usbharu.hideout.util.ServerUtil +import org.jetbrains.exposed.sql.transactions.experimental.newSuspendedTransaction import org.koin.core.annotation.Single import org.slf4j.Logger import org.slf4j.LoggerFactory @@ -16,18 +17,20 @@ class ServerInitialiseServiceImpl(private val metaRepository: IMetaRepository) : val logger: Logger = LoggerFactory.getLogger(ServerInitialiseServiceImpl::class.java) override suspend fun init() { - val savedMeta = metaRepository.get() - val implementationVersion = ServerUtil.getImplementationVersion() - if (wasInitialised(savedMeta).not()) { - logger.info("Start Initialise") - initialise(implementationVersion) - logger.info("Finish Initialise") - return - } + newSuspendedTransaction { + val savedMeta = metaRepository.get() + val implementationVersion = ServerUtil.getImplementationVersion() + if (wasInitialised(savedMeta).not()) { + logger.info("Start Initialise") + initialise(implementationVersion) + logger.info("Finish Initialise") + return@newSuspendedTransaction + } - if (isVersionChanged(requireNotNull(savedMeta))) { - logger.info("Version changed!! (${savedMeta.version} -> $implementationVersion)") - updateVersion(savedMeta, implementationVersion) + if (isVersionChanged(requireNotNull(savedMeta))) { + logger.info("Version changed!! (${savedMeta.version} -> $implementationVersion)") + updateVersion(savedMeta, implementationVersion) + } } }