mirror of
https://github.com/usbharu/Hideout.git
synced 2026-09-26 15:01:09 +00:00
first commit
This commit is contained in:
@@ -0,0 +1,67 @@
|
||||
package dev.usbharu.hideout
|
||||
|
||||
import com.fasterxml.jackson.module.kotlin.jacksonObjectMapper
|
||||
import dev.usbharu.hideout.config.Config
|
||||
import dev.usbharu.hideout.config.ConfigData
|
||||
import dev.usbharu.hideout.plugins.*
|
||||
import dev.usbharu.hideout.repository.IUserAuthRepository
|
||||
import dev.usbharu.hideout.repository.IUserRepository
|
||||
import dev.usbharu.hideout.repository.UserAuthRepository
|
||||
import dev.usbharu.hideout.repository.UserRepository
|
||||
import dev.usbharu.hideout.routing.login
|
||||
import dev.usbharu.hideout.routing.register
|
||||
import dev.usbharu.hideout.routing.user
|
||||
import dev.usbharu.hideout.routing.wellKnown
|
||||
import dev.usbharu.hideout.service.ActivityPubUserService
|
||||
import dev.usbharu.hideout.service.IUserAuthService
|
||||
import dev.usbharu.hideout.service.UserAuthService
|
||||
import dev.usbharu.hideout.service.UserService
|
||||
import io.ktor.server.application.*
|
||||
import io.ktor.server.auth.*
|
||||
import io.ktor.util.*
|
||||
import org.jetbrains.exposed.sql.Database
|
||||
import org.koin.ktor.ext.inject
|
||||
import java.util.Base64
|
||||
|
||||
fun main(args: Array<String>): Unit =
|
||||
io.ktor.server.netty.EngineMain.main(args)
|
||||
|
||||
@Suppress("unused") // application.conf references the main function. This annotation prevents the IDE from marking it as unused.
|
||||
fun Application.module() {
|
||||
val module = org.koin.dsl.module {
|
||||
|
||||
single<Database>{ Database.connect(
|
||||
url = "jdbc:h2:./test;MODE=POSTGRESQL",
|
||||
driver = "org.h2.Driver",
|
||||
) }
|
||||
single<ConfigData>{ ConfigData(
|
||||
environment.config.property("hideout.hostname").getString(),
|
||||
jacksonObjectMapper()
|
||||
) }
|
||||
single<IUserRepository>{UserRepository(get())}
|
||||
single<IUserAuthRepository>{UserAuthRepository(get())}
|
||||
single<IUserAuthService>{ UserAuthService(get(),get()) }
|
||||
single<UserService> { UserService(get()) }
|
||||
single<ActivityPubUserService> { ActivityPubUserService(get())}
|
||||
}
|
||||
configureKoin(module)
|
||||
val configData by inject<ConfigData>()
|
||||
Config.configData = configData
|
||||
val decode = Base64.getDecoder().decode("76pc9N9hspQqapj30kCaLJA14O/50ptCg50zCA1oxjA=")
|
||||
|
||||
val pair = "admin" to decode
|
||||
println(pair)
|
||||
val userAuthService by inject<IUserAuthService>()
|
||||
val userService by inject<UserService>()
|
||||
configureSecurity(userAuthService)
|
||||
configureHTTP()
|
||||
configureMonitoring()
|
||||
configureSerialization()
|
||||
configureSockets()
|
||||
configureRouting()
|
||||
val activityPubUserService by inject<ActivityPubUserService>()
|
||||
user(userService,activityPubUserService)
|
||||
login()
|
||||
register(userAuthService)
|
||||
wellKnown(userService)
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
package dev.usbharu.hideout.ap
|
||||
|
||||
open class Image : Object {
|
||||
private var mediaType: String? = null
|
||||
private var url: String? = null
|
||||
|
||||
protected constructor() : super()
|
||||
constructor(type: List<String> = emptyList(), name: String, mediaType: String?, url: String?) : super(
|
||||
type,
|
||||
name
|
||||
) {
|
||||
this.mediaType = mediaType
|
||||
this.url = url
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
package dev.usbharu.hideout.ap
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonAutoDetect
|
||||
import com.fasterxml.jackson.annotation.JsonCreator
|
||||
import com.fasterxml.jackson.annotation.JsonProperty
|
||||
|
||||
@JsonAutoDetect(fieldVisibility = JsonAutoDetect.Visibility.ANY)
|
||||
open class JsonLd {
|
||||
@JsonProperty("@context")
|
||||
var context:List<String> = emptyList()
|
||||
|
||||
@JsonCreator
|
||||
constructor(context:List<String>){
|
||||
this.context = context
|
||||
}
|
||||
|
||||
protected constructor()
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
package dev.usbharu.hideout.ap
|
||||
|
||||
open class Object : JsonLd {
|
||||
private var type: List<String> = emptyList()
|
||||
private var name: String? = null
|
||||
|
||||
protected constructor()
|
||||
constructor(type: List<String>, name: String) : super() {
|
||||
this.type = type
|
||||
this.name = name
|
||||
}
|
||||
|
||||
companion object {
|
||||
@JvmStatic
|
||||
protected fun add(list:List<String>,type:String):List<String> {
|
||||
list.toMutableList().add(type)
|
||||
return list.distinct()
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
package dev.usbharu.hideout.ap
|
||||
|
||||
open class Person : Object {
|
||||
private var id:String? = null
|
||||
private var preferredUsername:String? = null
|
||||
private var summary:String? = null
|
||||
private var inbox:String? = null
|
||||
private var outbox:String? = null
|
||||
private var url:String? = null
|
||||
private var icon:Image? = null
|
||||
protected constructor() : super()
|
||||
constructor(
|
||||
type: List<String> = emptyList(),
|
||||
name: String,
|
||||
id: String?,
|
||||
preferredUsername: String?,
|
||||
summary: String?,
|
||||
inbox: String?,
|
||||
outbox: String?,
|
||||
url: String?,
|
||||
icon: Image?
|
||||
) : super(add(type,"Person"), name) {
|
||||
this.id = id
|
||||
this.preferredUsername = preferredUsername
|
||||
this.summary = summary
|
||||
this.inbox = inbox
|
||||
this.outbox = outbox
|
||||
this.url = url
|
||||
this.icon = icon
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
package dev.usbharu.hideout.config
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper
|
||||
import com.fasterxml.jackson.module.kotlin.jacksonObjectMapper
|
||||
|
||||
object Config {
|
||||
var configData:ConfigData = ConfigData("", jacksonObjectMapper())
|
||||
}
|
||||
|
||||
data class ConfigData(val hostname:String,val objectMapper: ObjectMapper)
|
||||
@@ -0,0 +1,20 @@
|
||||
package dev.usbharu.hideout.domain.model
|
||||
|
||||
import org.jetbrains.exposed.dao.id.LongIdTable
|
||||
|
||||
data class User(val name: String, val screenName: String, val description: String)
|
||||
|
||||
data class UserEntity(
|
||||
val id: Long,
|
||||
val name: String,
|
||||
val screenName: String,
|
||||
val description: String
|
||||
) {
|
||||
constructor(id: Long, user: User) : this(id, user.name, user.screenName, user.description)
|
||||
}
|
||||
|
||||
object Users : LongIdTable("users") {
|
||||
val name = varchar("name", length = 64).uniqueIndex()
|
||||
val screenName = varchar("screen_name", length = 64)
|
||||
val description = varchar("description", length = 600)
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
package dev.usbharu.hideout.domain.model
|
||||
|
||||
import org.jetbrains.exposed.dao.id.LongIdTable
|
||||
import org.jetbrains.exposed.sql.ReferenceOption
|
||||
|
||||
data class UserAuthentication(
|
||||
val userId: Long,
|
||||
val hash: String,
|
||||
val publicKey: String,
|
||||
val privateKey: String
|
||||
)
|
||||
|
||||
data class UserAuthenticationEntity(
|
||||
val id: Long,
|
||||
val userId: Long,
|
||||
val hash: String,
|
||||
val publicKey: String,
|
||||
val privateKey: String
|
||||
) {
|
||||
constructor(id: Long, userAuthentication: UserAuthentication) : this(
|
||||
id,
|
||||
userAuthentication.userId,
|
||||
userAuthentication.hash,
|
||||
userAuthentication.publicKey,
|
||||
userAuthentication.privateKey
|
||||
)
|
||||
}
|
||||
|
||||
object UsersAuthentication : LongIdTable("users_auth") {
|
||||
val userId = long("user_id").references(Users.id, onUpdate = ReferenceOption.CASCADE)
|
||||
val hash = varchar("hash", length = 64)
|
||||
val publicKey = varchar("public_key", length = 1000_000)
|
||||
val privateKey = varchar("private_key", length = 1000_000)
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
package dev.usbharu.hideout.exception
|
||||
|
||||
class UserNotFoundException : 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)
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
package dev.usbharu.hideout.plugins
|
||||
|
||||
import dev.usbharu.hideout.ap.JsonLd
|
||||
import dev.usbharu.hideout.config.Config
|
||||
import dev.usbharu.hideout.util.HttpUtil.Activity
|
||||
import io.ktor.http.*
|
||||
import io.ktor.server.application.*
|
||||
import io.ktor.server.response.*
|
||||
|
||||
suspend fun <T : JsonLd> ApplicationCall.respondAp(message: T, status: HttpStatusCode = HttpStatusCode.OK) {
|
||||
message.context += "https://www.w3.org/activitystreams"
|
||||
val activityJson = Config.configData.objectMapper.writeValueAsString(message)
|
||||
respondText(activityJson, ContentType.Application.Activity, status)
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
package dev.usbharu.hideout.plugins
|
||||
|
||||
import io.ktor.http.*
|
||||
import io.ktor.server.plugins.cors.routing.*
|
||||
import io.ktor.server.plugins.defaultheaders.*
|
||||
import io.ktor.server.plugins.forwardedheaders.*
|
||||
import io.ktor.server.application.*
|
||||
|
||||
fun Application.configureHTTP() {
|
||||
install(CORS) {
|
||||
allowMethod(HttpMethod.Options)
|
||||
allowMethod(HttpMethod.Put)
|
||||
allowMethod(HttpMethod.Delete)
|
||||
allowMethod(HttpMethod.Patch)
|
||||
allowHeader(HttpHeaders.Authorization)
|
||||
allowHeader("MyCustomHeader")
|
||||
anyHost() // @TODO: Don't do this in production if possible. Try to limit it.
|
||||
}
|
||||
install(DefaultHeaders) {
|
||||
header("X-Engine", "Ktor") // will send this header with each response
|
||||
}
|
||||
install(ForwardedHeaders) // WARNING: for security, do not include this if not behind a reverse proxy
|
||||
install(XForwardedHeaders) // WARNING: for security, do not include this if not behind a reverse proxy
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
package dev.usbharu.hideout.plugins
|
||||
|
||||
import io.ktor.server.application.*
|
||||
import org.koin.core.module.Module
|
||||
import org.koin.ktor.plugin.Koin
|
||||
import org.koin.logger.slf4jLogger
|
||||
|
||||
fun Application.configureKoin(module: Module) {
|
||||
install(Koin) {
|
||||
slf4jLogger()
|
||||
modules(module)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
package dev.usbharu.hideout.plugins
|
||||
|
||||
import io.ktor.server.plugins.callloging.*
|
||||
import org.slf4j.event.*
|
||||
import io.ktor.server.request.*
|
||||
import io.ktor.server.application.*
|
||||
|
||||
fun Application.configureMonitoring() {
|
||||
install(CallLogging) {
|
||||
level = Level.INFO
|
||||
filter { call -> call.request.path().startsWith("/") }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
package dev.usbharu.hideout.plugins
|
||||
|
||||
import io.ktor.server.routing.*
|
||||
import io.ktor.server.response.*
|
||||
import io.ktor.server.plugins.autohead.*
|
||||
import io.ktor.server.application.*
|
||||
|
||||
fun Application.configureRouting() {
|
||||
install(AutoHeadResponse)
|
||||
routing {
|
||||
get("/") {
|
||||
call.respondText("Hello World!")
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
package dev.usbharu.hideout.plugins
|
||||
|
||||
import dev.usbharu.hideout.service.IUserAuthService
|
||||
import dev.usbharu.hideout.service.UserService
|
||||
import io.ktor.server.application.*
|
||||
import io.ktor.server.auth.*
|
||||
import io.ktor.server.sessions.*
|
||||
import kotlin.time.Duration.Companion.days
|
||||
|
||||
data class UserSession(val username: String) : Principal
|
||||
|
||||
const val tokenAuth = "token-auth"
|
||||
|
||||
fun Application.configureSecurity(userAuthService: IUserAuthService) {
|
||||
install(Authentication){
|
||||
bearer(tokenAuth) {
|
||||
authenticate {
|
||||
bearerTokenCredential ->
|
||||
UserIdPrincipal(bearerTokenCredential.token)
|
||||
}
|
||||
skipWhen { true }
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
package dev.usbharu.hideout.plugins
|
||||
|
||||
import io.ktor.serialization.jackson.*
|
||||
import io.ktor.server.application.*
|
||||
import io.ktor.server.plugins.contentnegotiation.*
|
||||
import io.ktor.server.response.*
|
||||
import io.ktor.server.routing.*
|
||||
|
||||
fun Application.configureSerialization() {
|
||||
install(ContentNegotiation) {
|
||||
jackson()
|
||||
}
|
||||
routing {
|
||||
get("/json/kotlinx-serialization") {
|
||||
call.respond(mapOf("hello" to "world"))
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
package dev.usbharu.hideout.plugins
|
||||
|
||||
import io.ktor.server.websocket.*
|
||||
import io.ktor.websocket.*
|
||||
import java.time.Duration
|
||||
import io.ktor.server.application.*
|
||||
import io.ktor.server.routing.*
|
||||
|
||||
fun Application.configureSockets() {
|
||||
install(WebSockets) {
|
||||
pingPeriod = Duration.ofSeconds(15)
|
||||
timeout = Duration.ofSeconds(15)
|
||||
maxFrameSize = Long.MAX_VALUE
|
||||
masking = false
|
||||
}
|
||||
routing {
|
||||
webSocket("/ws") { // websocketSession
|
||||
for (frame in incoming) {
|
||||
if (frame is Frame.Text) {
|
||||
val text = frame.readText()
|
||||
outgoing.send(Frame.Text("YOU SAID: $text"))
|
||||
if (text.equals("bye", ignoreCase = true)) {
|
||||
close(CloseReason(CloseReason.Codes.NORMAL, "Client said BYE"))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
package dev.usbharu.hideout.repository
|
||||
|
||||
import dev.usbharu.hideout.domain.model.UserAuthentication
|
||||
import dev.usbharu.hideout.domain.model.UserAuthenticationEntity
|
||||
|
||||
interface IUserAuthRepository {
|
||||
suspend fun create(userAuthentication: UserAuthentication):UserAuthenticationEntity
|
||||
|
||||
suspend fun findById(id:Long):UserAuthenticationEntity?
|
||||
|
||||
suspend fun update(userAuthenticationEntity: UserAuthenticationEntity)
|
||||
|
||||
suspend fun delete(id:Long)
|
||||
suspend fun findByUserId(id: Long): UserAuthenticationEntity?
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
package dev.usbharu.hideout.repository
|
||||
|
||||
interface IUserKeyRepository
|
||||
@@ -0,0 +1,20 @@
|
||||
package dev.usbharu.hideout.repository
|
||||
|
||||
import dev.usbharu.hideout.domain.model.User
|
||||
import dev.usbharu.hideout.domain.model.UserEntity
|
||||
|
||||
interface IUserRepository {
|
||||
suspend fun create(user: User): UserEntity
|
||||
|
||||
suspend fun findById(id: Long): UserEntity?
|
||||
|
||||
suspend fun findByName(name:String): UserEntity?
|
||||
|
||||
suspend fun update(userEntity: UserEntity)
|
||||
|
||||
suspend fun delete(id: Long)
|
||||
|
||||
suspend fun findAll():List<User>
|
||||
|
||||
suspend fun findAllByLimitAndByOffset(limit:Int,offset:Long = 0):List<UserEntity>
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
package dev.usbharu.hideout.repository
|
||||
|
||||
import dev.usbharu.hideout.domain.model.UserAuthentication
|
||||
import dev.usbharu.hideout.domain.model.UserAuthenticationEntity
|
||||
import dev.usbharu.hideout.domain.model.UsersAuthentication
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import org.jetbrains.exposed.sql.*
|
||||
import org.jetbrains.exposed.sql.transactions.experimental.newSuspendedTransaction
|
||||
import org.jetbrains.exposed.sql.transactions.transaction
|
||||
|
||||
class UserAuthRepository(private val database: Database) : IUserAuthRepository {
|
||||
|
||||
init {
|
||||
transaction(database) {
|
||||
SchemaUtils.create(UsersAuthentication)
|
||||
}
|
||||
}
|
||||
|
||||
private fun ResultRow.toUserAuth():UserAuthenticationEntity{
|
||||
return UserAuthenticationEntity(
|
||||
id = this[UsersAuthentication.id].value,
|
||||
userId = this[UsersAuthentication.userId],
|
||||
hash = this[UsersAuthentication.hash],
|
||||
publicKey = this[UsersAuthentication.publicKey],
|
||||
privateKey = this[UsersAuthentication.privateKey]
|
||||
)
|
||||
}
|
||||
|
||||
|
||||
suspend fun <T> query(block: suspend () -> T): T =
|
||||
newSuspendedTransaction(Dispatchers.IO) {block()}
|
||||
override suspend fun create(userAuthentication: UserAuthentication): UserAuthenticationEntity {
|
||||
return query {
|
||||
UserAuthenticationEntity(
|
||||
UsersAuthentication.insert {
|
||||
it[userId] = userAuthentication.userId
|
||||
it[hash] = userAuthentication.hash
|
||||
it[publicKey] = userAuthentication.publicKey
|
||||
it[privateKey] = userAuthentication.privateKey
|
||||
}[UsersAuthentication.id].value,userAuthentication
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
override suspend fun findById(id: Long): UserAuthenticationEntity? {
|
||||
TODO("Not yet implemented")
|
||||
}
|
||||
|
||||
override suspend fun findByUserId(id:Long):UserAuthenticationEntity? {
|
||||
return query {
|
||||
UsersAuthentication.select { UsersAuthentication.userId eq id }.map { it.toUserAuth() }.singleOrNull()
|
||||
}
|
||||
}
|
||||
|
||||
override suspend fun update(userAuthenticationEntity: UserAuthenticationEntity) {
|
||||
TODO("Not yet implemented")
|
||||
}
|
||||
|
||||
override suspend fun delete(id: Long) {
|
||||
TODO("Not yet implemented")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
package dev.usbharu.hideout.repository
|
||||
|
||||
class UserKeyRepository {
|
||||
}
|
||||
@@ -0,0 +1,93 @@
|
||||
package dev.usbharu.hideout.repository
|
||||
|
||||
import dev.usbharu.hideout.domain.model.User
|
||||
import dev.usbharu.hideout.domain.model.UserEntity
|
||||
import dev.usbharu.hideout.domain.model.Users
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import org.jetbrains.exposed.sql.*
|
||||
import org.jetbrains.exposed.sql.SqlExpressionBuilder.eq
|
||||
import org.jetbrains.exposed.sql.transactions.experimental.newSuspendedTransaction
|
||||
import org.jetbrains.exposed.sql.transactions.transaction
|
||||
|
||||
class UserRepository(private val database: Database) : IUserRepository {
|
||||
init {
|
||||
transaction(database) {
|
||||
SchemaUtils.create(Users)
|
||||
}
|
||||
}
|
||||
|
||||
private fun ResultRow.toUser(): User {
|
||||
return User(
|
||||
this[Users.name],
|
||||
this[Users.screenName],
|
||||
this[Users.description]
|
||||
)
|
||||
}
|
||||
|
||||
private fun ResultRow.toUserEntity(): UserEntity {
|
||||
return UserEntity(
|
||||
this[Users.id].value,
|
||||
this[Users.name],
|
||||
this[Users.screenName],
|
||||
this[Users.description]
|
||||
)
|
||||
}
|
||||
|
||||
suspend fun <T> query(block: suspend () -> T): T =
|
||||
newSuspendedTransaction(Dispatchers.IO) { block() }
|
||||
|
||||
override suspend fun create(user: User): UserEntity {
|
||||
return query {
|
||||
UserEntity(Users.insert {
|
||||
it[name] = user.name
|
||||
it[screenName] = user.screenName
|
||||
it[description] = user.description
|
||||
}[Users.id].value, user)
|
||||
}
|
||||
}
|
||||
|
||||
override suspend fun findById(id: Long): UserEntity? {
|
||||
return query {
|
||||
Users.select { Users.id eq id }.map {
|
||||
it.toUserEntity()
|
||||
}.singleOrNull()
|
||||
}
|
||||
}
|
||||
|
||||
override suspend fun findByName(name: String): UserEntity? {
|
||||
return query {
|
||||
Users.select { Users.name eq name }.map {
|
||||
it.toUserEntity()
|
||||
}.singleOrNull()
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
override suspend fun update(userEntity: UserEntity) {
|
||||
return query {
|
||||
Users.update({ Users.id eq userEntity.id }) {
|
||||
it[name] = userEntity.name
|
||||
it[screenName] = userEntity.screenName
|
||||
it[description] = userEntity.description
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
override suspend fun delete(id: Long) {
|
||||
query {
|
||||
Users.deleteWhere { Users.id.eq(id) }
|
||||
}
|
||||
}
|
||||
|
||||
override suspend fun findAll(): List<User> {
|
||||
return query {
|
||||
Users.selectAll().map { it.toUser() }
|
||||
}
|
||||
}
|
||||
|
||||
override suspend fun findAllByLimitAndByOffset(limit: Int, offset: Long): List<UserEntity> {
|
||||
return query {
|
||||
Users.selectAll().limit(limit, offset).map { it.toUserEntity() }
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
package dev.usbharu.hideout.routing
|
||||
|
||||
import dev.usbharu.hideout.plugins.UserSession
|
||||
import dev.usbharu.hideout.plugins.tokenAuth
|
||||
import io.ktor.http.*
|
||||
import io.ktor.server.application.*
|
||||
import io.ktor.server.auth.*
|
||||
import io.ktor.server.response.*
|
||||
import io.ktor.server.routing.*
|
||||
import io.ktor.server.sessions.*
|
||||
|
||||
fun Application.login(){
|
||||
routing {
|
||||
authenticate(tokenAuth) {
|
||||
post("/login") {
|
||||
println("aaaaaaaaaaaaaaaaaaaaa")
|
||||
val principal = call.principal<UserIdPrincipal>()
|
||||
call.sessions.set(UserSession(principal!!.name))
|
||||
call.respondRedirect("/users/${principal.name}")
|
||||
}
|
||||
}
|
||||
|
||||
get("/login"){
|
||||
call.respondText(contentType = ContentType.Text.Html) {
|
||||
|
||||
//language=HTML
|
||||
"""
|
||||
<html>
|
||||
<head>
|
||||
|
||||
</head>
|
||||
<body>
|
||||
<h2>login</h2>
|
||||
<form method='POST' action=''>
|
||||
<input type='text' name='username' value=''>
|
||||
<input type='password' name='password'>
|
||||
<input type='submit'>
|
||||
</form>
|
||||
</body>
|
||||
</html>
|
||||
""".trimIndent()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
package dev.usbharu.hideout.routing
|
||||
|
||||
import dev.usbharu.hideout.plugins.UserSession
|
||||
import dev.usbharu.hideout.service.IUserAuthService
|
||||
import io.ktor.http.*
|
||||
import io.ktor.server.application.*
|
||||
import io.ktor.server.auth.*
|
||||
import io.ktor.server.request.*
|
||||
import io.ktor.server.response.*
|
||||
import io.ktor.server.routing.*
|
||||
import io.ktor.server.sessions.*
|
||||
|
||||
fun Application.register(userAuthService: IUserAuthService) {
|
||||
|
||||
routing {
|
||||
get("/register") {
|
||||
val principal = call.principal<UserIdPrincipal>()
|
||||
if (principal != null) {
|
||||
call.respondRedirect("/users/${principal.name}")
|
||||
}
|
||||
call.respondText(ContentType.Text.Html) {
|
||||
//language=HTML
|
||||
"""
|
||||
<html>
|
||||
<head>
|
||||
</head>
|
||||
<body>
|
||||
<form method='post' action=''>
|
||||
<input type='text' name='username' value=''>
|
||||
<input type='password' name='password'>
|
||||
<input type="submit">
|
||||
</form>
|
||||
</body>
|
||||
</html>
|
||||
""".trimIndent()
|
||||
}
|
||||
}
|
||||
post("/register") {
|
||||
val parameters = call.receiveParameters()
|
||||
val password = parameters["password"] ?: return@post call.respondRedirect("/register")
|
||||
val username = parameters["username"] ?: return@post call.respondRedirect("/register")
|
||||
if (userAuthService.usernameAlreadyUse(username)) {
|
||||
return@post call.respondRedirect("/register")
|
||||
}
|
||||
|
||||
val hash = userAuthService.hash(password)
|
||||
userAuthService.registerAccount(username,hash)
|
||||
call.sessions.set(UserSession(username))
|
||||
// call.respondRedirect("/login")
|
||||
call.respondRedirect("/users/$username")
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,81 @@
|
||||
package dev.usbharu.hideout.routing
|
||||
|
||||
import dev.usbharu.hideout.domain.model.User
|
||||
import dev.usbharu.hideout.plugins.UserSession
|
||||
import dev.usbharu.hideout.plugins.respondAp
|
||||
import dev.usbharu.hideout.plugins.tokenAuth
|
||||
import dev.usbharu.hideout.service.ActivityPubUserService
|
||||
import dev.usbharu.hideout.service.UserService
|
||||
import dev.usbharu.hideout.util.HttpUtil
|
||||
import io.ktor.http.*
|
||||
import io.ktor.server.application.*
|
||||
import io.ktor.server.auth.*
|
||||
import io.ktor.server.request.*
|
||||
import io.ktor.server.response.*
|
||||
import io.ktor.server.routing.*
|
||||
import io.ktor.server.sessions.*
|
||||
|
||||
@Suppress("unused")
|
||||
fun Application.user(userService: UserService,activityPubUserService: ActivityPubUserService) {
|
||||
routing {
|
||||
route("/users") {
|
||||
authenticate( tokenAuth,optional = true) {
|
||||
|
||||
get {
|
||||
val limit = call.request.queryParameters["limit"]?.toInt()
|
||||
val offset = call.request.queryParameters["offset"]?.toLong()
|
||||
val result = userService.findAll(limit, offset)
|
||||
call.respond(result)
|
||||
}
|
||||
post {
|
||||
val user = call.receive<User>()
|
||||
userService.create(user)
|
||||
call.response.header(
|
||||
HttpHeaders.Location,
|
||||
call.request.path() + "/${user.name}"
|
||||
)
|
||||
call.respond(HttpStatusCode.Created)
|
||||
}
|
||||
get("/{name}") {
|
||||
val contentType = ContentType.parse(call.request.accept()?:"*/*")
|
||||
val typeOfActivityPub = HttpUtil.isContentTypeOfActivityPub(
|
||||
contentType.contentType,
|
||||
contentType.contentSubtype,
|
||||
contentType.parameter("profile").orEmpty()
|
||||
)
|
||||
val name = call.parameters["name"]
|
||||
if (typeOfActivityPub) {
|
||||
val userModel = activityPubUserService.generateUserModel(name!!)
|
||||
return@get call.respondAp(userModel)
|
||||
}
|
||||
|
||||
val principal = call.principal<UserIdPrincipal>()
|
||||
if (principal != null && name != null) {
|
||||
// iUserService.findByName(name)
|
||||
if (principal.name == name) {
|
||||
call.respondText {
|
||||
principal.name
|
||||
}
|
||||
//todo
|
||||
}
|
||||
}
|
||||
call.respondText {
|
||||
"hello $name !!"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
authenticate(tokenAuth) {
|
||||
get("/admin"){
|
||||
println("cccccccccccc "+call.principal<UserIdPrincipal>())
|
||||
println("cccccccccccc "+call.principal<UserSession>())
|
||||
|
||||
return@get call.respondText {
|
||||
"you alredy in admin !! hello " +
|
||||
call.principal<UserIdPrincipal>()?.name.toString()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
package dev.usbharu.hideout.routing
|
||||
|
||||
import dev.usbharu.hideout.config.Config
|
||||
import dev.usbharu.hideout.exception.UserNotFoundException
|
||||
import dev.usbharu.hideout.service.UserService
|
||||
import dev.usbharu.hideout.util.HttpUtil.Activity
|
||||
import io.ktor.http.*
|
||||
import io.ktor.server.application.*
|
||||
import io.ktor.server.response.*
|
||||
import io.ktor.server.routing.*
|
||||
import kotlinx.serialization.Serializable
|
||||
import org.intellij.lang.annotations.Language
|
||||
|
||||
fun Application.wellKnown(userService: UserService) {
|
||||
routing {
|
||||
route("/.well-known") {
|
||||
get("/host-meta") {
|
||||
//language=XML
|
||||
val xml = """
|
||||
<?xml version="1.0" encoding="UTF-8"?><XRD xmlns="http://docs.oasis-open.org/ns/xri/xrd-1.0"><Link rel="lrdd" type="application/xrd+xml" template="${Config.configData.hostname}/.well-known/webfinger?resource={uri}"/></XRD>
|
||||
""".trimIndent()
|
||||
return@get call.respondText(
|
||||
contentType = ContentType("application", "xrd+xml"),
|
||||
status = HttpStatusCode.OK,
|
||||
text = xml
|
||||
)
|
||||
}
|
||||
|
||||
get("/host-meta.json") {
|
||||
@Language("JSON") val json = """
|
||||
{
|
||||
"links": [
|
||||
{
|
||||
"rel": "lrdd",
|
||||
"type": "application/jrd+json",
|
||||
"template": "${Config.configData.hostname}/.well-known/webfinger?resource={uri}"
|
||||
}
|
||||
]
|
||||
}
|
||||
""".trimIndent()
|
||||
return@get call.respondText(
|
||||
contentType = ContentType("application", "xrd+json"),
|
||||
status = HttpStatusCode.OK,
|
||||
text = json
|
||||
)
|
||||
}
|
||||
|
||||
get("/webfinger") {
|
||||
val uri = call.request.queryParameters["resource"] ?: return@get call.respond(
|
||||
HttpStatusCode.BadRequest
|
||||
)
|
||||
|
||||
if (uri.startsWith("acct:")) {
|
||||
return@get call.respond(HttpStatusCode.BadRequest)
|
||||
}
|
||||
val accountName = uri.substringBeforeLast("@")
|
||||
val userEntity = userService.findByName(accountName)
|
||||
|
||||
return@get call.respond(WebFingerResource(
|
||||
subject = userEntity.name,
|
||||
listOf(
|
||||
WebFingerResource.Link(
|
||||
rel ="self",
|
||||
type = ContentType.Application.Activity.toString(),
|
||||
href = "${Config.configData.hostname}/users/${userEntity.name}"
|
||||
)
|
||||
)
|
||||
))
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Serializable
|
||||
data class WebFingerResource(val subject:String,val links:List<Link>){
|
||||
@Serializable
|
||||
data class Link(val rel:String,val type:String,val href:String)
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
package dev.usbharu.hideout.routing
|
||||
|
||||
import io.ktor.server.application.*
|
||||
import io.ktor.server.routing.*
|
||||
|
||||
fun Application.userActivityPubRouting(){
|
||||
routing {
|
||||
route("/users/{name}") {
|
||||
route("/inbox"){
|
||||
get {
|
||||
|
||||
}
|
||||
post {
|
||||
|
||||
}
|
||||
}
|
||||
route("/outbox") {
|
||||
get {
|
||||
|
||||
}
|
||||
post {
|
||||
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
package dev.usbharu.hideout.service
|
||||
|
||||
class ActivityPubService {
|
||||
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
package dev.usbharu.hideout.service
|
||||
|
||||
import dev.usbharu.hideout.ap.Image
|
||||
import dev.usbharu.hideout.ap.Person
|
||||
import dev.usbharu.hideout.config.Config
|
||||
|
||||
class ActivityPubUserService(private val userService: UserService) {
|
||||
suspend fun generateUserModel(name:String):Person{
|
||||
val userEntity = userService.findByName(name)
|
||||
val userUrl = "${Config.configData.hostname}/$name"
|
||||
return Person(
|
||||
emptyList(),
|
||||
"Icon",
|
||||
userUrl,
|
||||
name,
|
||||
userEntity.description,
|
||||
"$userUrl/inbox",
|
||||
"$userUrl/outbox",
|
||||
userUrl,
|
||||
Image(
|
||||
emptyList(),
|
||||
"$userUrl/icon.png",
|
||||
"image/png",
|
||||
"$userUrl/icon.png"
|
||||
)
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
package dev.usbharu.hideout.service
|
||||
|
||||
interface IUserAuthService {
|
||||
fun hash(password:String): String
|
||||
|
||||
suspend fun usernameAlreadyUse(username: String):Boolean
|
||||
suspend fun registerAccount(username: String, hash: String)
|
||||
|
||||
suspend fun verifyAccount(username: String,password: String): Boolean
|
||||
}
|
||||
@@ -0,0 +1,86 @@
|
||||
package dev.usbharu.hideout.service
|
||||
|
||||
import dev.usbharu.hideout.domain.model.User
|
||||
import dev.usbharu.hideout.domain.model.UserAuthentication
|
||||
import dev.usbharu.hideout.exception.UserNotFoundException
|
||||
import dev.usbharu.hideout.repository.IUserAuthRepository
|
||||
import dev.usbharu.hideout.repository.IUserRepository
|
||||
import io.ktor.util.*
|
||||
import java.security.KeyPair
|
||||
import java.security.KeyPairGenerator
|
||||
import java.security.MessageDigest
|
||||
import java.security.interfaces.RSAPrivateCrtKey
|
||||
import java.security.interfaces.RSAPrivateKey
|
||||
import java.security.interfaces.RSAPublicKey
|
||||
import java.util.*
|
||||
|
||||
class UserAuthService(
|
||||
val userRepository: IUserRepository,
|
||||
val userAuthRepository: IUserAuthRepository
|
||||
) : IUserAuthService {
|
||||
|
||||
|
||||
override fun hash(password: String): String {
|
||||
val digest = sha256.digest(password.toByteArray(Charsets.UTF_8))
|
||||
return hex(digest)
|
||||
}
|
||||
|
||||
override suspend fun usernameAlreadyUse(username: String): Boolean {
|
||||
userRepository.findByName(username) ?: return false
|
||||
return true
|
||||
}
|
||||
|
||||
override suspend fun registerAccount(username: String, hash: String) {
|
||||
val registerUser = User(
|
||||
name = username,
|
||||
screenName = username,
|
||||
description = ""
|
||||
)
|
||||
val createdUser = userRepository.create(registerUser)
|
||||
|
||||
val keyPair = generateKeyPair()
|
||||
val privateKey = keyPair.private as RSAPrivateKey
|
||||
val publicKey = keyPair.public as RSAPublicKey
|
||||
|
||||
|
||||
val userAuthentication = UserAuthentication(
|
||||
createdUser.id,
|
||||
hash,
|
||||
publicKey.toPem(),
|
||||
privateKey.toPem()
|
||||
)
|
||||
|
||||
userAuthRepository.create(userAuthentication)
|
||||
}
|
||||
|
||||
override suspend fun verifyAccount(username: String, password: String): Boolean {
|
||||
val userEntity = userRepository.findByName(username)
|
||||
?: throw UserNotFoundException("$username was not found")
|
||||
val userAuthEntity = userAuthRepository.findByUserId(userEntity.id)
|
||||
?: throw UserNotFoundException("$username auth data was not found")
|
||||
return userAuthEntity.hash == hash(password)
|
||||
}
|
||||
|
||||
private fun generateKeyPair(): KeyPair {
|
||||
val keyPairGenerator = KeyPairGenerator.getInstance("RSA")
|
||||
keyPairGenerator.initialize(1024)
|
||||
return keyPairGenerator.generateKeyPair()
|
||||
}
|
||||
|
||||
|
||||
private fun RSAPublicKey.toPem(): String {
|
||||
return "-----BEGIN RSA PUBLIC KEY-----\n" +
|
||||
Base64.getEncoder().encodeToString(encoded) + "\n" +
|
||||
"-----END RSA PUBLIC KEY-----"
|
||||
}
|
||||
|
||||
private fun RSAPrivateKey.toPem(): String {
|
||||
return "-----BEGIN RSA PRIVATE KEY-----\n" +
|
||||
Base64.getEncoder().encodeToString(encoded) + "\n" +
|
||||
"-----END RSA PRIVATE KEY-----"
|
||||
}
|
||||
|
||||
companion object {
|
||||
val sha256: MessageDigest = MessageDigest.getInstance("SHA-256")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
package dev.usbharu.hideout.service
|
||||
|
||||
import dev.usbharu.hideout.domain.model.User
|
||||
import dev.usbharu.hideout.domain.model.UserEntity
|
||||
import dev.usbharu.hideout.exception.UserNotFoundException
|
||||
import dev.usbharu.hideout.repository.IUserRepository
|
||||
import dev.usbharu.hideout.repository.UserRepository
|
||||
import org.jetbrains.exposed.sql.Database
|
||||
import java.lang.Integer.min
|
||||
|
||||
class UserService(private val userRepository: IUserRepository) {
|
||||
|
||||
private val maxLimit = 100
|
||||
suspend fun findAll(limit: Int? = maxLimit, offset: Long? = 0): List<UserEntity> {
|
||||
|
||||
return userRepository.findAllByLimitAndByOffset(
|
||||
min(limit ?: maxLimit, maxLimit),
|
||||
offset ?: 0
|
||||
)
|
||||
}
|
||||
|
||||
suspend fun findById(id: Long): UserEntity {
|
||||
return userRepository.findById(id) ?: throw UserNotFoundException("$id was not found.")
|
||||
}
|
||||
|
||||
suspend fun findByName(name:String): UserEntity {
|
||||
return userRepository.findByName(name) ?: throw UserNotFoundException("$name was not found.")
|
||||
}
|
||||
|
||||
suspend fun create(user: User): UserEntity {
|
||||
return userRepository.create(user)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
package dev.usbharu.hideout.util
|
||||
|
||||
import io.ktor.http.*
|
||||
|
||||
object HttpUtil {
|
||||
fun isContentTypeOfActivityPub(
|
||||
contentType: String,
|
||||
subType: String,
|
||||
parameter: String
|
||||
): Boolean {
|
||||
println("$contentType/$subType $parameter")
|
||||
if (contentType != "application") {
|
||||
return false
|
||||
}
|
||||
if (subType == "activity+json") {
|
||||
return true
|
||||
}
|
||||
if (subType == "ld+json" && parameter == "https://www.w3.org/ns/activitystreams") {
|
||||
return true
|
||||
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
val ContentType.Application.Activity: ContentType
|
||||
get() = ContentType("application","activity+json")
|
||||
// fun
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
ktor {
|
||||
development = true
|
||||
deployment {
|
||||
port = 8080
|
||||
port = ${?PORT}
|
||||
watch = [classes, resources]
|
||||
}
|
||||
application {
|
||||
modules = [dev.usbharu.hideout.ApplicationKt.module]
|
||||
}
|
||||
}
|
||||
|
||||
hideout {
|
||||
hostname = "https://localhost:8080"
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
<configuration>
|
||||
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
|
||||
<encoder>
|
||||
<pattern>%d{YYYY-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n</pattern>
|
||||
</encoder>
|
||||
</appender>
|
||||
<root level="trace">
|
||||
<appender-ref ref="STDOUT"/>
|
||||
</root>
|
||||
<logger name="org.eclipse.jetty" level="INFO"/>
|
||||
<logger name="io.netty" level="INFO"/>
|
||||
</configuration>
|
||||
@@ -0,0 +1,22 @@
|
||||
package dev.usbharu
|
||||
|
||||
import dev.usbharu.hideout.plugins.configureRouting
|
||||
import io.ktor.client.request.*
|
||||
import io.ktor.client.statement.*
|
||||
import io.ktor.http.*
|
||||
import io.ktor.server.testing.*
|
||||
import kotlin.test.Test
|
||||
import kotlin.test.assertEquals
|
||||
|
||||
class ApplicationTest {
|
||||
@Test
|
||||
fun testRoot() = testApplication {
|
||||
application {
|
||||
configureRouting()
|
||||
}
|
||||
client.get("/").apply {
|
||||
assertEquals(HttpStatusCode.OK, status)
|
||||
assertEquals("Hello World!", bodyAsText())
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user