Implemented the Auth middleware (#3)

This PR contains the work done to implement the `AuthMiddleware` middleware that, when plugged into a `Client` object, adds authentication parameters to any request the client would make.

Reviewed-on: #3
Co-authored-by: Javier Cicchelli <javier@rock-n-code.com>
Co-committed-by: Javier Cicchelli <javier@rock-n-code.com>
This commit was merged in pull request #3.
This commit is contained in:
2025-10-04 10:57:15 +00:00
committed by Javier Cicchelli
parent 7006aa1bc8
commit ce0ec02c03
10 changed files with 599 additions and 0 deletions
@@ -0,0 +1,25 @@
//===----------------------------------------------------------------------===
//
// This source file is part of the MarvelService open source project
//
// Copyright (c) -2025 Röck+Cöde VoF. and the MarvelService project authors
// Licensed under the EUPL 1.2 or later.
//
// See LICENSE for license information
// See CONTRIBUTORS for the list of MarvelService project authors
//
//===----------------------------------------------------------------------===
import struct Foundation.TimeInterval
extension TimeInterval {
// MARK: Functions
/// Converts a time interval to a string value.
/// - Returns: A time interval as a string.
var asString: String {
.init(format: "%f", self)
}
}
@@ -0,0 +1,60 @@
//===----------------------------------------------------------------------===
//
// This source file is part of the MarvelService open source project
//
// Copyright (c) -2025 Röck+Cöde VoF. and the MarvelService project authors
// Licensed under the EUPL 1.2 or later.
//
// See LICENSE for license information
// See CONTRIBUTORS for the list of MarvelService project authors
//
//===----------------------------------------------------------------------===
import CryptoKit
import struct Foundation.Data
import struct Foundation.TimeInterval
/// A use case that generates a MD5 hash value, which is required to authenticate any request.
struct GenerateHashUseCase {
// MARK: Properties
/// A private key.
private let privateKey: String
/// A public key.
private let publicKey: String
// MARK: Initializers
/// Initializes this use case.
/// - Parameters:
/// - privateKey: A private key.
/// - publicKey: A public key.
init(
privateKey: String,
publicKey: String,
) {
self.privateKey = privateKey
self.publicKey = publicKey
}
// MARK: Functions
/// Generates a MD5 hash value out of a given public key, private key and a timestamp.
/// - Parameter timestamp: A timestamp that changes on a request-by-request basis.
/// - Returns: A MD5 hash generated out of a private key, an public key, and a timestamp.
func callAsFunction(
timestamp: TimeInterval
) -> String {
let stringToHash = timestamp.asString + self.privateKey + self.publicKey
let dataToHash = Data(stringToHash.utf8)
return Insecure.MD5
.hash(data: dataToHash)
.map { String(format: "%02x", $0) }
.joined()
}
}
@@ -0,0 +1,104 @@
//===----------------------------------------------------------------------===
//
// This source file is part of the MarvelService open source project
//
// Copyright (c) 2025 Röck+Cöde VoF. and the MarvelService project authors
// Licensed under the EUPL 1.2 or later.
//
// See LICENSE for license information
// See CONTRIBUTORS for the list of MarvelService project authors
//
//===----------------------------------------------------------------------===
import class OpenAPIRuntime.HTTPBody
import protocol OpenAPIRuntime.ClientMiddleware
import struct Foundation.Date
import struct Foundation.TimeInterval
import struct Foundation.URL
import struct Foundation.URLComponents
import struct HTTPTypes.HTTPRequest
import struct HTTPTypes.HTTPResponse
/// A middleware that attaches the necessary authentication parameters to the path of the request.
public struct AuthMiddleware {
// MARK: Properties
/// A use case that generates a MD5 hash value to use as an authentication parameter.
private let hash: GenerateHashUseCase
/// A Marvel API public key.
private let publicKey: String
// MARK: Initializers
/// Initializes this middleware with private and public keys.
///
/// The middleware attaches the required `apikey`, `ts`, and `hash` parameters to the URI path of the intercepted request.
/// This initializer should be used for server-side applications, as indicated in the [Marvel API documentation](https://developer.marvel.com/documentation/authorization)
///
/// - Parameters:
/// - privateKey: A Marvel API private key.
/// - publicKey: A Marvel API public key.
public init(
privateKey: String,
publicKey: String
) {
self.hash = .init(
privateKey: privateKey,
publicKey: publicKey
)
self.publicKey = publicKey
}
}
// MARK: - ClientMiddleware
extension AuthMiddleware: ClientMiddleware {
// MARK: Functions
public func intercept(
_ request: HTTPRequest,
body: HTTPBody?,
baseURL: URL,
operationID: String,
next: @Sendable (HTTPRequest, HTTPBody?, URL) async throws -> (HTTPResponse, HTTPBody?)
) async throws -> (HTTPResponse, HTTPBody?) {
guard
let uriPath = request.path,
var urlComponents = URLComponents(string: uriPath)
else {
return try await next(request, body, baseURL)
}
let queryItems = urlComponents.queryItems ?? []
let timestamp = Date().timeIntervalSince1970
urlComponents.queryItems = queryItems + [
.init(name: "ts", value: timestamp.asString),
.init(name: "apikey", value: publicKey),
.init(name: "hash", value: hash(timestamp: timestamp))
]
let newPath = if let urlQuery = urlComponents.query {
urlComponents.path + "?" + urlQuery
} else {
urlComponents.path
}
let newRequest = HTTPRequest(
method: request.method,
scheme: request.scheme,
authority: request.authority,
path: newPath,
headerFields: request.headerFields
)
return try await next(newRequest, body, baseURL)
}
}