Skip to content

Instantly share code, notes, and snippets.

@Skeptick
Created May 15, 2023 07:27
Show Gist options
  • Save Skeptick/8eea4e99f3d8f7d3b30b38ae47b02975 to your computer and use it in GitHub Desktop.
Save Skeptick/8eea4e99f3d8f7d3b30b38ae47b02975 to your computer and use it in GitHub Desktop.
Подпись запроса в ktor
package com.example.data.network.features
import io.ktor.client.HttpClient
import io.ktor.client.features.HttpClientFeature
import io.ktor.client.request.HttpRequestBuilder
import io.ktor.client.request.HttpRequestPipeline
import io.ktor.client.request.header
import io.ktor.content.TextContent
import io.ktor.http.clone
import io.ktor.util.AttributeKey
import com.example.domain.extensions.md5
/**
* Формирует подпись запроса и добавляет её в соответствующий заголовок
*/
class MyCustomSigner(private val apiUrl: String, private val apiKey: String) {
class Config {
var apiUrl = ""
var apiKey = ""
}
companion object Feature : HttpClientFeature<Config, MyCustomSigner> {
override val key = AttributeKey<MyCustomSigner>("MyCustomSigner")
private fun HttpRequestBuilder.buildSign(feature: MyCustomSigner, body: TextContent?): String {
val parts = mutableListOf<String>()
parts += method.value
parts += url.clone().buildString().substringAfter(feature.apiUrl)
parts += headers[MyCustomHeaders.ApiUser] ?: ""
parts += headers[MyCustomHeaders.ApiPassword] ?: ""
parts += headers[MyCustomHeaders.ClientLogin] ?: ""
parts += headers[MyCustomHeaders.ClientPasswordHash] ?: ""
parts += body?.text ?: ""
parts += headers[MyCustomHeaders.ClientUid] ?: ""
parts += feature.apiKey
return parts.joinToString(":").md5
}
override fun prepare(block: Config.() -> Unit): MyCustomSigner {
val config = Config().apply(block)
return MyCustomSigner(config.apiUrl, config.apiKey)
}
override fun install(feature: MyCustomSigner, scope: HttpClient) {
scope.requestPipeline.intercept(HttpRequestPipeline.Transform) { payload ->
val hash = context.buildSign(feature, payload as? TextContent)
context.header(MyCustomHeaders.Hash, hash)
proceed()
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment