style: スタイルを調整

This commit is contained in:
usbharu 2023-09-25 17:27:42 +09:00
parent 3c310952b5
commit 09442d2bdf
29 changed files with 120 additions and 168 deletions

View File

@ -2,6 +2,7 @@ build:
maxIssues: 20 maxIssues: 20
weights: weights:
Indentation: 0 Indentation: 0
MagicNumber: 0
style: style:
ClassOrdering: ClassOrdering:

View File

@ -30,17 +30,19 @@ class JobQueueWorkerRunner(
) : ApplicationRunner { ) : ApplicationRunner {
override fun run(args: ApplicationArguments?) { override fun run(args: ApplicationArguments?) {
LOGGER.info("Init job queue worker.") LOGGER.info("Init job queue worker.")
jobQueueWorkerService.init(jobs.map { jobQueueWorkerService.init(
it to { jobs.map {
execute { it to {
LOGGER.debug("excute job ${it.name}") execute {
apService.processActivity( LOGGER.debug("excute job ${it.name}")
job = this, apService.processActivity(
hideoutJob = it job = this,
) hideoutJob = it
)
}
} }
} }
}) )
} }
companion object { companion object {

View File

@ -8,6 +8,7 @@ import org.springframework.boot.runApplication
@ConfigurationPropertiesScan @ConfigurationPropertiesScan
class SpringApplication class SpringApplication
@Suppress("SpreadOperator")
fun main(args: Array<String>) { fun main(args: Array<String>) {
runApplication<SpringApplication>(*args) runApplication<SpringApplication>(*args)
} }

View File

@ -32,7 +32,9 @@ class HttpClientConfig {
applicationConfig: ApplicationConfig applicationConfig: ApplicationConfig
): KtorKeyMap { ): KtorKeyMap {
return KtorKeyMap( return KtorKeyMap(
userQueryService, transaction, applicationConfig userQueryService,
transaction,
applicationConfig
) )
} }
} }

View File

@ -55,7 +55,6 @@ class SecurityConfig {
return http.build() return http.build()
} }
@Bean @Bean
@Order(2) @Order(2)
fun defaultSecurityFilterChain(http: HttpSecurity, introspector: HandlerMappingIntrospector): SecurityFilterChain { fun defaultSecurityFilterChain(http: HttpSecurity, introspector: HandlerMappingIntrospector): SecurityFilterChain {
@ -99,9 +98,7 @@ class SecurityConfig {
} }
@Bean @Bean
fun passwordEncoder(): PasswordEncoder { fun passwordEncoder(): PasswordEncoder = BCryptPasswordEncoder()
return BCryptPasswordEncoder()
}
@Bean @Bean
fun genJwkSource(): JWKSource<SecurityContext> { fun genJwkSource(): JWKSource<SecurityContext> {
@ -131,9 +128,8 @@ class SecurityConfig {
} }
@Bean @Bean
fun jwtDecoder(jwkSource: JWKSource<SecurityContext>): JwtDecoder { fun jwtDecoder(jwkSource: JWKSource<SecurityContext>): JwtDecoder =
return OAuth2AuthorizationServerConfiguration.jwtDecoder(jwkSource) OAuth2AuthorizationServerConfiguration.jwtDecoder(jwkSource)
}
@Bean @Bean
fun authorizationServerSettings(): AuthorizationServerSettings { fun authorizationServerSettings(): AuthorizationServerSettings {

View File

@ -12,7 +12,6 @@ import javax.sql.DataSource
@EnableTransactionManagement @EnableTransactionManagement
class SpringTransactionConfig(val datasource: DataSource) : TransactionManagementConfigurer { class SpringTransactionConfig(val datasource: DataSource) : TransactionManagementConfigurer {
@Bean @Bean
override fun annotationDrivenTransactionManager(): PlatformTransactionManager { override fun annotationDrivenTransactionManager(): PlatformTransactionManager =
return SpringTransactionManager(datasource) SpringTransactionManager(datasource)
}
} }

View File

@ -12,10 +12,11 @@ interface InboxController {
@RequestMapping( @RequestMapping(
"/inbox", "/inbox",
"/users/{username}/inbox", "/users/{username}/inbox",
produces = ["application/activity+json", "application/ld+json; profile=\"https://www.w3.org/ns/activitystreams\""], produces = [
"application/activity+json",
"application/ld+json; profile=\"https://www.w3.org/ns/activitystreams\""
],
method = [RequestMethod.GET, RequestMethod.POST] method = [RequestMethod.GET, RequestMethod.POST]
) )
fun inbox(@RequestBody string: String): ResponseEntity<Unit> { fun inbox(@RequestBody string: String): ResponseEntity<Unit> = ResponseEntity(HttpStatus.ACCEPTED)
return ResponseEntity(HttpStatus.ACCEPTED)
}
} }

View File

@ -10,7 +10,5 @@ import org.springframework.web.bind.annotation.RestController
@RestController @RestController
interface OutboxController { interface OutboxController {
@RequestMapping("/outbox", "/users/{username}/outbox", method = [RequestMethod.POST, RequestMethod.GET]) @RequestMapping("/outbox", "/users/{username}/outbox", method = [RequestMethod.POST, RequestMethod.GET])
fun outbox(@RequestBody string: String): ResponseEntity<Unit> { fun outbox(@RequestBody string: String): ResponseEntity<Unit> = ResponseEntity(HttpStatus.ACCEPTED)
return ResponseEntity(HttpStatus.ACCEPTED)
}
} }

View File

@ -7,7 +7,5 @@ import org.springframework.web.bind.annotation.RestController
@RestController @RestController
class OutboxControllerImpl : OutboxController { class OutboxControllerImpl : OutboxController {
override fun outbox(@RequestBody string: String): ResponseEntity<Unit> { override fun outbox(@RequestBody string: String): ResponseEntity<Unit> = ResponseEntity(HttpStatus.NOT_IMPLEMENTED)
return ResponseEntity(HttpStatus.NOT_IMPLEMENTED)
}
} }

View File

@ -29,14 +29,8 @@ class HostMetaController(private val applicationConfig: ApplicationConfig) {
}""" }"""
@GetMapping("/.well-known/host-meta", produces = ["application/xml"]) @GetMapping("/.well-known/host-meta", produces = ["application/xml"])
fun hostmeta(): ResponseEntity<String> { fun hostmeta(): ResponseEntity<String> = ResponseEntity(xml, HttpStatus.OK)
return ResponseEntity(xml, HttpStatus.OK)
}
@GetMapping("/.well-known/host-meta.json", produces = ["application/json"]) @GetMapping("/.well-known/host-meta.json", produces = ["application/json"])
fun hostmetJson(): ResponseEntity<String> { fun hostmetJson(): ResponseEntity<String> = ResponseEntity(json, HttpStatus.OK)
return ResponseEntity(json, HttpStatus.OK)
}
} }

View File

@ -20,11 +20,13 @@ class NodeinfoController(private val applicationConfig: ApplicationConfig) {
"${applicationConfig.url}/nodeinfo/2.0" "${applicationConfig.url}/nodeinfo/2.0"
) )
) )
), HttpStatus.OK ),
HttpStatus.OK
) )
} }
@GetMapping("/nodeinfo/2.0") @GetMapping("/nodeinfo/2.0")
@Suppress("FunctionNaming")
fun nodeinfo2_0(): ResponseEntity<Nodeinfo2_0> { fun nodeinfo2_0(): ResponseEntity<Nodeinfo2_0> {
return ResponseEntity( return ResponseEntity(
Nodeinfo2_0( Nodeinfo2_0(

View File

@ -42,10 +42,12 @@ class UserDetailsImpl(
) )
@JsonIgnoreProperties(ignoreUnknown = true) @JsonIgnoreProperties(ignoreUnknown = true)
@JsonSubTypes @JsonSubTypes
@Suppress("UnnecessaryAbstractClass")
abstract class UserDetailsMixin abstract class UserDetailsMixin
class UserDetailsDeserializer : JsonDeserializer<UserDetailsImpl>() { class UserDetailsDeserializer : JsonDeserializer<UserDetailsImpl>() {
val SIMPLE_GRANTED_AUTHORITY_SET = object : TypeReference<Set<SimpleGrantedAuthority>>() {}
private val SIMPLE_GRANTED_AUTHORITY_SET = object : TypeReference<Set<SimpleGrantedAuthority>>() {}
override fun deserialize(p: JsonParser, ctxt: DeserializationContext): UserDetailsImpl { override fun deserialize(p: JsonParser, ctxt: DeserializationContext): UserDetailsImpl {
val mapper = p.codec as ObjectMapper val mapper = p.codec as ObjectMapper
val jsonNode: JsonNode = mapper.readTree(p) val jsonNode: JsonNode = mapper.readTree(p)
@ -57,14 +59,14 @@ class UserDetailsDeserializer : JsonDeserializer<UserDetailsImpl>() {
val password = jsonNode.readText("password") val password = jsonNode.readText("password")
return UserDetailsImpl( return UserDetailsImpl(
jsonNode["id"].longValue(), id = jsonNode["id"].longValue(),
jsonNode.readText("username"), username = jsonNode.readText("username"),
password, password = password,
true, enabled = true,
true, accountNonExpired = true,
true, credentialsNonExpired = true,
true, accountNonLocked = true,
authorities.toMutableList(), authorities = authorities.toMutableList(),
) )
} }

View File

@ -1,6 +1,5 @@
package dev.usbharu.hideout.domain.model.wellknown package dev.usbharu.hideout.domain.model.wellknown
data class Nodeinfo( data class Nodeinfo(
val links: List<Links> val links: List<Links>
) { ) {

View File

@ -1,5 +1,6 @@
package dev.usbharu.hideout.domain.model.wellknown package dev.usbharu.hideout.domain.model.wellknown
@Suppress("ClassNaming")
data class Nodeinfo2_0( data class Nodeinfo2_0(
val version: String, val version: String,
val software: Software, val software: Software,

View File

@ -48,9 +48,9 @@ class RegisteredClientRepositoryImpl(private val database: Database) : Registere
it[clientSecretExpiresAt] = registeredClient.clientSecretExpiresAt it[clientSecretExpiresAt] = registeredClient.clientSecretExpiresAt
it[clientName] = registeredClient.clientName it[clientName] = registeredClient.clientName
it[clientAuthenticationMethods] = it[clientAuthenticationMethods] =
registeredClient.clientAuthenticationMethods.map { it.value }.joinToString(",") registeredClient.clientAuthenticationMethods.map { method -> method.value }.joinToString(",")
it[authorizationGrantTypes] = it[authorizationGrantTypes] =
registeredClient.authorizationGrantTypes.map { it.value }.joinToString(",") registeredClient.authorizationGrantTypes.map { type -> type.value }.joinToString(",")
it[redirectUris] = registeredClient.redirectUris.joinToString(",") it[redirectUris] = registeredClient.redirectUris.joinToString(",")
it[postLogoutRedirectUris] = registeredClient.postLogoutRedirectUris.joinToString(",") it[postLogoutRedirectUris] = registeredClient.postLogoutRedirectUris.joinToString(",")
it[scopes] = registeredClient.scopes.joinToString(",") it[scopes] = registeredClient.scopes.joinToString(",")
@ -100,20 +100,7 @@ class RegisteredClientRepositoryImpl(private val database: Database) : Registere
private fun <T, U> jsonToMap(json: String): Map<T, U> = objectMapper.readValue(json) private fun <T, U> jsonToMap(json: String): Map<T, U> = objectMapper.readValue(json)
companion object { @Suppress("CyclomaticComplexMethod")
val objectMapper: ObjectMapper = ObjectMapper()
val LOGGER = LoggerFactory.getLogger(RegisteredClientRepositoryImpl::class.java)
init {
val classLoader = ExposedOAuth2AuthorizationService::class.java.classLoader
val modules = SecurityJackson2Modules.getModules(classLoader)
this.objectMapper.registerModules(JavaTimeModule())
this.objectMapper.registerModules(modules)
this.objectMapper.registerModules(OAuth2AuthorizationServerJackson2Module())
}
}
fun ResultRow.toRegisteredClient(): SpringRegisteredClient { fun ResultRow.toRegisteredClient(): SpringRegisteredClient {
fun resolveClientAuthenticationMethods(string: String): ClientAuthenticationMethod { fun resolveClientAuthenticationMethods(string: String): ClientAuthenticationMethod {
return when (string) { return when (string) {
@ -175,6 +162,20 @@ class RegisteredClientRepositoryImpl(private val database: Database) : Registere
return builder.build() return builder.build()
} }
companion object {
val objectMapper: ObjectMapper = ObjectMapper()
val LOGGER = LoggerFactory.getLogger(RegisteredClientRepositoryImpl::class.java)
init {
val classLoader = ExposedOAuth2AuthorizationService::class.java.classLoader
val modules = SecurityJackson2Modules.getModules(classLoader)
this.objectMapper.registerModules(JavaTimeModule())
this.objectMapper.registerModules(modules)
this.objectMapper.registerModules(OAuth2AuthorizationServerJackson2Module())
}
}
} }
// org/springframework/security/oauth2/server/authorization/client/oauth2-registered-client-schema.sql // org/springframework/security/oauth2/server/authorization/client/oauth2-registered-client-schema.sql

View File

@ -83,7 +83,8 @@ class APReactionServiceImpl(
`object` = postUrl, `object` = postUrl,
id = "${Config.configData.url}/like/note/$id", id = "${Config.configData.url}/like/note/$id",
content = content content = content
), objectMapper ),
objectMapper
) )
} }
@ -100,7 +101,8 @@ class APReactionServiceImpl(
`object` = like, `object` = like,
id = "${Config.configData.url}/undo/note/${like.id}", id = "${Config.configData.url}/undo/note/${like.id}",
published = Instant.now() published = Instant.now()
), objectMapper ),
objectMapper
) )
} }
} }

View File

@ -18,7 +18,6 @@ import kjob.core.job.JobProps
import org.springframework.beans.factory.annotation.Qualifier import org.springframework.beans.factory.annotation.Qualifier
import org.springframework.stereotype.Service import org.springframework.stereotype.Service
interface APReceiveFollowService { interface APReceiveFollowService {
suspend fun receiveFollow(follow: Follow): ActivityPubResponse suspend fun receiveFollow(follow: Follow): ActivityPubResponse
suspend fun receiveFollowJob(props: JobProps<ReceiveFollowJob>) suspend fun receiveFollowJob(props: JobProps<ReceiveFollowJob>)
@ -58,7 +57,8 @@ class APReceiveFollowServiceImpl(
name = "Follow", name = "Follow",
`object` = follow, `object` = follow,
actor = targetActor actor = targetActor
), objectMapper ),
objectMapper
) )
val targetEntity = userQueryService.findByUrl(targetActor) val targetEntity = userQueryService.findByUrl(targetActor)

View File

@ -18,10 +18,10 @@ class AccountApiServiceImpl(private val accountService: AccountService, private
AccountApiService { AccountApiService {
override suspend fun verifyCredentials(userid: Long): CredentialAccount = transaction.transaction { override suspend fun verifyCredentials(userid: Long): CredentialAccount = transaction.transaction {
val account = accountService.findById(userid) val account = accountService.findById(userid)
of(account) from(account)
} }
private fun of(account: Account): CredentialAccount { private fun from(account: Account): CredentialAccount {
return CredentialAccount( return CredentialAccount(
id = account.id, id = account.id,
username = account.username, username = account.username,

View File

@ -55,7 +55,5 @@ class AppApiServiceImpl(
} }
} }
private fun parseScope(string: String): Set<String> { private fun parseScope(string: String): Set<String> = string.split(" ").toSet()
return string.split(" ").toSet()
}
} }

View File

@ -11,13 +11,15 @@ interface InstanceApiService {
@Service @Service
class InstanceApiServiceImpl(private val applicationConfig: ApplicationConfig) : InstanceApiService { class InstanceApiServiceImpl(private val applicationConfig: ApplicationConfig) : InstanceApiService {
@Suppress("LongMethod")
override suspend fun v1Instance(): V1Instance { override suspend fun v1Instance(): V1Instance {
val url = applicationConfig.url val url = applicationConfig.url
return V1Instance( return V1Instance(
uri = url.host, uri = url.host,
title = "Hideout Server", title = "Hideout Server",
shortDescription = "Hideout test server", shortDescription = "Hideout test server",
description = "This server is operated for testing of Hideout. We are not responsible for any events that occur when associating with this server", description = "This server is operated for testing of Hideout." +
" We are not responsible for any events that occur when associating with this server",
email = "i@usbharu.dev", email = "i@usbharu.dev",
version = "0.0.1", version = "0.0.1",
urls = V1InstanceUrls("wss://${url.host}"), urls = V1InstanceUrls("wss://${url.host}"),
@ -35,7 +37,7 @@ class InstanceApiServiceImpl(private val applicationConfig: ApplicationConfig) :
23 23
), ),
mediaAttachments = V1InstanceConfigurationMediaAttachments( mediaAttachments = V1InstanceConfigurationMediaAttachments(
listOf(), emptyList(),
0, 0,
0, 0,
0, 0,

View File

@ -26,6 +26,7 @@ class StatsesApiServiceImpl(
private val userQueryService: UserQueryService private val userQueryService: UserQueryService
) : ) :
StatusesApiService { StatusesApiService {
@Suppress("LongMethod")
override suspend fun postStatus(statusesRequest: StatusesRequest, user: UserDetailsImpl): Status { override suspend fun postStatus(statusesRequest: StatusesRequest, user: UserDetailsImpl): Status {
val visibility = when (statusesRequest.visibility) { val visibility = when (statusesRequest.visibility) {
StatusesRequest.Visibility.public -> Visibility.PUBLIC StatusesRequest.Visibility.public -> Visibility.PUBLIC
@ -37,12 +38,12 @@ class StatsesApiServiceImpl(
val post = postService.createLocal( val post = postService.createLocal(
PostCreateDto( PostCreateDto(
statusesRequest.status.orEmpty(), text = statusesRequest.status.orEmpty(),
statusesRequest.spoilerText, overview = statusesRequest.spoilerText,
visibility, visibility = visibility,
null, repostId = null,
statusesRequest.inReplyToId?.toLongOrNull(), repolyId = statusesRequest.inReplyToId?.toLongOrNull(),
user.id userId = user.id
) )
) )
val account = accountService.findById(user.id) val account = accountService.findById(user.id)
@ -58,7 +59,7 @@ class StatsesApiServiceImpl(
val replyUser = if (post.replyId != null) { val replyUser = if (post.replyId != null) {
try { try {
userQueryService.findById(postQueryService.findById(post.replyId).userId).id userQueryService.findById(postQueryService.findById(post.replyId).userId).id
} catch (e: FailedToGetResourcesException) { } catch (ignore: FailedToGetResourcesException) {
null null
} }
} else { } else {
@ -82,7 +83,7 @@ class StatsesApiServiceImpl(
favouritesCount = 0, favouritesCount = 0,
repliesCount = 0, repliesCount = 0,
url = post.url, url = post.url,
post.replyId?.toString(), inReplyToId = post.replyId?.toString(),
inReplyToAccountId = replyUser?.toString(), inReplyToAccountId = replyUser?.toString(),
reblog = null, reblog = null,
language = null, language = null,

View File

@ -40,6 +40,7 @@ class ExposedOAuth2AuthorizationService(
} }
} }
@Suppress("LongMethod", "CyclomaticComplexMethod")
override fun save(authorization: OAuth2Authorization?): Unit = runBlocking { override fun save(authorization: OAuth2Authorization?): Unit = runBlocking {
requireNotNull(authorization) requireNotNull(authorization)
transaction.transaction { transaction.transaction {
@ -56,7 +57,8 @@ class ExposedOAuth2AuthorizationService(
it[registeredClientId] = authorization.registeredClientId it[registeredClientId] = authorization.registeredClientId
it[principalName] = authorization.principalName it[principalName] = authorization.principalName
it[authorizationGrantType] = authorization.authorizationGrantType.value it[authorizationGrantType] = authorization.authorizationGrantType.value
it[authorizedScopes] = authorization.authorizedScopes.joinToString(",").takeIf { it.isNotEmpty() } it[authorizedScopes] =
authorization.authorizedScopes.joinToString(",").takeIf { s -> s.isNotEmpty() }
it[attributes] = mapToJson(authorization.attributes) it[attributes] = mapToJson(authorization.attributes)
it[state] = authorization.getAttribute(OAuth2ParameterNames.STATE) it[state] = authorization.getAttribute(OAuth2ParameterNames.STATE)
it[authorizationCodeValue] = authorizationCodeToken?.token?.tokenValue it[authorizationCodeValue] = authorizationCodeToken?.token?.tokenValue
@ -99,7 +101,8 @@ class ExposedOAuth2AuthorizationService(
it[registeredClientId] = authorization.registeredClientId it[registeredClientId] = authorization.registeredClientId
it[principalName] = authorization.principalName it[principalName] = authorization.principalName
it[authorizationGrantType] = authorization.authorizationGrantType.value it[authorizationGrantType] = authorization.authorizationGrantType.value
it[authorizedScopes] = authorization.authorizedScopes.joinToString(",").takeIf { it.isNotEmpty() } it[authorizedScopes] =
authorization.authorizedScopes.joinToString(",").takeIf { s -> s.isNotEmpty() }
it[attributes] = mapToJson(authorization.attributes) it[attributes] = mapToJson(authorization.attributes)
it[state] = authorization.getAttribute(OAuth2ParameterNames.STATE) it[state] = authorization.getAttribute(OAuth2ParameterNames.STATE)
it[authorizationCodeValue] = authorizationCodeToken?.token?.tokenValue it[authorizationCodeValue] = authorizationCodeToken?.token?.tokenValue
@ -111,8 +114,9 @@ class ExposedOAuth2AuthorizationService(
it[accessTokenIssuedAt] = accessToken?.token?.issuedAt it[accessTokenIssuedAt] = accessToken?.token?.issuedAt
it[accessTokenExpiresAt] = accessToken?.token?.expiresAt it[accessTokenExpiresAt] = accessToken?.token?.expiresAt
it[accessTokenMetadata] = accessToken?.metadata?.let { it1 -> mapToJson(it1) } it[accessTokenMetadata] = accessToken?.metadata?.let { it1 -> mapToJson(it1) }
it[accessTokenType] = accessToken?.token?.tokenType?.value it[accessTokenType] = accessToken?.run { token.tokenType.value }
it[accessTokenScopes] = accessToken?.token?.scopes?.joinToString(",")?.takeIf { it.isNotEmpty() } it[accessTokenScopes] =
accessToken?.run { token.scopes.joinToString(",").takeIf { s -> s.isNotEmpty() } }
it[refreshTokenValue] = refreshToken?.token?.tokenValue it[refreshTokenValue] = refreshToken?.token?.tokenValue
it[refreshTokenIssuedAt] = refreshToken?.token?.issuedAt it[refreshTokenIssuedAt] = refreshToken?.token?.issuedAt
it[refreshTokenExpiresAt] = refreshToken?.token?.expiresAt it[refreshTokenExpiresAt] = refreshToken?.token?.expiresAt
@ -203,6 +207,7 @@ class ExposedOAuth2AuthorizationService(
} }
} }
@Suppress("LongMethod", "CyclomaticComplexMethod")
fun ResultRow.toAuthorization(): OAuth2Authorization { fun ResultRow.toAuthorization(): OAuth2Authorization {
val registeredClientId = this[Authorization.registeredClientId] val registeredClientId = this[Authorization.registeredClientId]

View File

@ -24,14 +24,14 @@ class UserDetailsServiceImpl(
transaction.transaction { transaction.transaction {
val findById = userQueryService.findByNameAndDomain(username, applicationConfig.url.host) val findById = userQueryService.findByNameAndDomain(username, applicationConfig.url.host)
UserDetailsImpl( UserDetailsImpl(
findById.id, id = findById.id,
findById.name, username = findById.name,
findById.password, password = findById.password,
true, enabled = true,
true, accountNonExpired = true,
true, credentialsNonExpired = true,
true, accountNonLocked = true,
mutableListOf() authorities = mutableListOf()
) )
} }
} }

View File

@ -1,12 +1,14 @@
package dev.usbharu.hideout.service.job package dev.usbharu.hideout.service.job
import dev.usbharu.hideout.domain.model.job.HideoutJob
import kjob.core.dsl.KJobFunctions import kjob.core.dsl.KJobFunctions
import org.springframework.stereotype.Service import org.springframework.stereotype.Service
import dev.usbharu.hideout.domain.model.job.HideoutJob as HJ
import kjob.core.dsl.JobContextWithProps as JCWP import kjob.core.dsl.JobContextWithProps as JCWP
import kjob.core.dsl.JobRegisterContext as JRC import kjob.core.dsl.JobRegisterContext as JRC
@Service @Service
interface JobQueueWorkerService { interface JobQueueWorkerService {
fun init(defines: List<Pair<HideoutJob, JRC<HideoutJob, JCWP<HideoutJob>>.(HideoutJob) -> KJobFunctions<HideoutJob, JCWP<HideoutJob>>>>) fun init(
defines: List<Pair<HJ, JRC<HJ, JCWP<HJ>>.(HJ) -> KJobFunctions<HJ, JCWP<HJ>>>>
)
} }

View File

@ -1,13 +1,13 @@
package dev.usbharu.hideout.service.job package dev.usbharu.hideout.service.job
import dev.usbharu.hideout.domain.model.job.HideoutJob
import dev.usbharu.kjob.exposed.ExposedKJob import dev.usbharu.kjob.exposed.ExposedKJob
import kjob.core.dsl.JobContextWithProps
import kjob.core.dsl.JobRegisterContext import kjob.core.dsl.JobRegisterContext
import kjob.core.dsl.KJobFunctions import kjob.core.dsl.KJobFunctions
import kjob.core.kjob import kjob.core.kjob
import org.jetbrains.exposed.sql.Database import org.jetbrains.exposed.sql.Database
import org.springframework.stereotype.Service import org.springframework.stereotype.Service
import dev.usbharu.hideout.domain.model.job.HideoutJob as HJ
import kjob.core.dsl.JobContextWithProps as JCWP
@Service @Service
class KJobJobQueueWorkerService(private val database: Database) : JobQueueWorkerService { class KJobJobQueueWorkerService(private val database: Database) : JobQueueWorkerService {
@ -21,7 +21,9 @@ class KJobJobQueueWorkerService(private val database: Database) : JobQueueWorker
}.start() }.start()
} }
override fun init(defines: List<Pair<HideoutJob, JobRegisterContext<HideoutJob, JobContextWithProps<HideoutJob>>.(HideoutJob) -> KJobFunctions<HideoutJob, JobContextWithProps<HideoutJob>>>>) { override fun init(
defines: List<Pair<HJ, JobRegisterContext<HJ, JCWP<HJ>>.(HJ) -> KJobFunctions<HJ, JCWP<HJ>>>>
) {
defines.forEach { job -> defines.forEach { job ->
kjob.register(job.first, job.second) kjob.register(job.first, job.second)
} }

View File

@ -25,15 +25,15 @@ class AccountServiceImpl(private val userQueryService: UserQueryService) : Accou
header = findById.url + "/header.jpg", header = findById.url + "/header.jpg",
headerStatic = findById.url + "/header.jpg", headerStatic = findById.url + "/header.jpg",
locked = false, locked = false,
emptyList(), fields = emptyList(),
emptyList(), emojis = emptyList(),
false, bot = false,
false, group = false,
false, discoverable = false,
findById.createdAt.toString(), createdAt = findById.createdAt.toString(),
findById.createdAt.toString(), lastStatusAt = findById.createdAt.toString(),
0, statusesCount = 0,
0, followersCount = 0,
) )
} }
} }

View File

@ -12,9 +12,7 @@ class UserAuthServiceImpl(
val userQueryService: UserQueryService val userQueryService: UserQueryService
) : UserAuthService { ) : UserAuthService {
override fun hash(password: String): String { override fun hash(password: String): String = BCryptPasswordEncoder().encode(password)
return BCryptPasswordEncoder().encode(password)
}
override suspend fun usernameAlreadyUse(username: String): Boolean { override suspend fun usernameAlreadyUse(username: String): Boolean {
userQueryService.findByName(username) userQueryService.findByName(username)

View File

@ -1,16 +0,0 @@
package dev.usbharu.hideout.util
import com.fasterxml.jackson.databind.ObjectMapper
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule
import com.fasterxml.jackson.module.kotlin.jacksonObjectMapper
import com.fasterxml.jackson.module.kotlin.readValue
object JsonUtil {
val objectMapper = jacksonObjectMapper().registerModule(JavaTimeModule())
fun mapToJson(map: Map<*, *>, objectMapper: ObjectMapper = this.objectMapper): String =
objectMapper.writeValueAsString(map)
fun <K, V> jsonToMap(json: String, objectMapper: ObjectMapper = this.objectMapper): Map<K, V> =
objectMapper.readValue(json)
}

View File

@ -1,39 +0,0 @@
package dev.usbharu.hideout.util
import java.math.BigInteger
import java.security.KeyFactory
import java.security.interfaces.RSAPublicKey
import java.security.spec.X509EncodedKeySpec
import java.util.*
object JsonWebKeyUtil {
fun publicKeyToJwk(publicKey: String, kid: String): String {
val x509EncodedKeySpec = X509EncodedKeySpec(Base64.getDecoder().decode(publicKey))
val generatePublic = KeyFactory.getInstance("RSA").generatePublic(x509EncodedKeySpec)
return publicKeyToJwk(generatePublic as RSAPublicKey, kid)
}
fun publicKeyToJwk(publicKey: RSAPublicKey, kid: String): String {
val e = encodeBase64UInt(publicKey.publicExponent)
val n = encodeBase64UInt(publicKey.modulus)
return """{"keys":[{"e":"$e","n":"$n","use":"sig","kid":"$kid","kty":"RSA"}]}"""
}
private fun encodeBase64UInt(bigInteger: BigInteger, minLength: Int = -1): String {
require(bigInteger.signum() >= 0) { "Cannot encode negative numbers" }
var bytes = bigInteger.toByteArray()
if (bigInteger.bitLength() % 8 == 0 && (bytes[0] == 0.toByte()) && bytes.size > 1) {
bytes = Arrays.copyOfRange(bytes, 1, bytes.size)
}
if (minLength != -1) {
if (bytes.size < minLength) {
val array = ByteArray(minLength)
System.arraycopy(bytes, 0, array, minLength - bytes.size, bytes.size)
bytes = array
}
}
return Base64.getUrlEncoder().withoutPadding().encodeToString(bytes)
}
}