apen6.okkam-http_2.12.0.1.3.source-code.BasicAuth.scala Maven / Gradle / Ivy
package okkam.http
import scala.concurrent.Future
import akka.actor.ActorSystem
import akka.stream.Materializer
import akka.http.scaladsl.model._
import akka.http.scaladsl.model.headers.{BasicHttpCredentials, Authorization}
import akka.http.scaladsl.settings.ConnectionPoolSettings
import BasicAuth._
object BasicAuth {
case class User(user: String, password: String) {
def toAuthorization: Authorization =
new Authorization(BasicHttpCredentials(user, password))
}
}
trait BasicAuthClientFactory {
/**
* Creates an HTTP client with Basic Authentication.
*
* @param user User information.
*
* @param system (Implicit) Actor system.
* @param materializer (Implicit) Materializer.
* @param settings (Implicit) Client's settings.
*/
def apply(
user: User
)(
implicit system: ActorSystem, materializer: Materializer,
settings: OHttpClientSettings
): BasicAuthClient = new BasicAuthClient(user)
}
object BasicAuthClient extends BasicAuthClientFactory {
}
/**
* HTTP Client with Basic Authentication
*/
final class BasicAuthClient(
user: User
)(
implicit system: ActorSystem, materializer: Materializer,
settings: OHttpClientSettings
) extends OHttpClient {
private[this] val auth = user.toAuthorization
def authorize(request: OHttpRequest): OHttpRequest =
request.addHeaders(auth)
/**
* Makes an HTTP request with Basic authorization
* and receive the response and the body at the same time.
* Automatically consumes the data byte stream of the response body.
*
* @param request Request as `OHttpRequest`.
* @param ignoreBody If `true`, the response body is ignored and discarded.
* The default is `false`.
* @param rawSettings (Advanced) Raw `ConnectionPoolSettings` for each request.
* Not `None` value overrides the client's `settings`.
*
* @return `Future` for `OHttpResponse`.
*/
override def makeRequest(
request: OHttpRequest,
ignoreBody: Boolean = false,
rawSettings: Option[ConnectionPoolSettings] = None
): Future[OHttpResponse] =
super.makeRequest(authorize(request), ignoreBody, rawSettings)
/**
* Makes an HTTP request with Basic authorization. (for advanced use)
*
* When the response is arrived, this function passes it to the given `callback` function
* that converts data bytes of the response body into some modeled data.
*
* By Akka's stream nature, `callback` must consume data bytes of the response body.
*
* @param request Request as `OHttpRequest`.
* @param rawSettings (Advanced) Raw `ConnectionPoolSettings` for each request.
* Not `None` value overrides the client's `settings`.
* @param callback Callback function.
*
* @return Same as the result of the `callback`.
*/
override def makeRequestWithCallback[R](
request: OHttpRequest,
rawSettings: Option[ConnectionPoolSettings] = None
)(
callback: HttpResponse => R
): Future[R] =
super.makeRequestWithCallback(authorize(request), rawSettings)(callback)
}