Implemented the Authentication middleware (#3)
This PR contains the work done to implement the `AuthMiddleware` middleware, to authenticate the requests sent to the backend service, based on [their specifications](https://www.discogs.com/developers/#page:authentication). In addition, some documentation has been added/updated and some boilerplate source code has been removed from the project. 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:
@@ -8,6 +8,26 @@
|
||||
|
||||
## Topics
|
||||
|
||||
### <!--@START_MENU_TOKEN@-->Group<!--@END_MENU_TOKEN@-->
|
||||
### Clients
|
||||
|
||||
- <!--@START_MENU_TOKEN@-->``Symbol``<!--@END_MENU_TOKEN@-->
|
||||
- ``Client``
|
||||
|
||||
### Servers
|
||||
|
||||
- ``Servers/Server1``
|
||||
|
||||
### Authentication
|
||||
|
||||
- ``AuthMiddleware``
|
||||
- ``AuthMethod``
|
||||
- ``AuthTransport``
|
||||
|
||||
### Types
|
||||
|
||||
- ``Components``
|
||||
- ``Operations``
|
||||
- ``Servers``
|
||||
|
||||
### Protocols
|
||||
|
||||
- ``APIProtocol``
|
||||
|
||||
@@ -0,0 +1,36 @@
|
||||
// ===----------------------------------------------------------------------===
|
||||
//
|
||||
// This source file is part of the DiscogsService open source project
|
||||
//
|
||||
// Copyright (c) 2025 Röck+Cöde VoF. and the DiscogsService project authors
|
||||
// Licensed under Apache license v2.0
|
||||
//
|
||||
// See LICENSE for license information
|
||||
// See CONTRIBUTORS for the list of DiscogsService project authors
|
||||
//
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
//
|
||||
// ===----------------------------------------------------------------------===
|
||||
|
||||
extension String {
|
||||
/// An empty string.
|
||||
static let empty = ""
|
||||
|
||||
/// A namespaces assigned for the names of parameters.
|
||||
enum Parameter {
|
||||
/// A name for the consumer key.
|
||||
static let key = "key"
|
||||
/// A name for the consumer secret.
|
||||
static let secret = "secret"
|
||||
/// A name for the user token.
|
||||
static let token = "token"
|
||||
}
|
||||
/// A namespaces assigned for the formats of string values.
|
||||
enum Format {
|
||||
/// A format for the consumer authentication header.
|
||||
static let authConsumer = "Discogs \(String.Parameter.key)=%@, \(String.Parameter.secret)=%@"
|
||||
/// A format for the user authentication header.
|
||||
static let authUser = "Discogs \(String.Parameter.token)=%@"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,33 @@
|
||||
// ===----------------------------------------------------------------------===
|
||||
//
|
||||
// This source file is part of the DiscogsService open source project
|
||||
//
|
||||
// Copyright (c) 2025 Röck+Cöde VoF. and the DiscogsService project authors
|
||||
// Licensed under Apache license v2.0
|
||||
//
|
||||
// See LICENSE for license information
|
||||
// See CONTRIBUTORS for the list of DiscogsService project authors
|
||||
//
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
//
|
||||
// ===----------------------------------------------------------------------===
|
||||
|
||||
/// A representation of the available authentication methods at the Discogs service.
|
||||
///
|
||||
/// The differences between these authentication methods.
|
||||
///
|
||||
/// Credentials in request | Rate limiting? | Image URLs? |Authenticated as user?
|
||||
/// --- | :---: | :---: | :---:
|
||||
/// None | 🐢 Low tier | ❌ No |❌ No
|
||||
/// Only Consumer key/secret | 🐰 High tier | ✔️ Yes | ❌ No
|
||||
/// Personal access token | 🐰 High tier | ✔️ Yes | ✔️ Yes, for token holder only 👩
|
||||
///
|
||||
/// Please refer to the [Discogs documentation](https://www.discogs.com/developers#page:authentication,header:authentication-discogs-auth-flow) for further details.
|
||||
public enum AuthMethod: Equatable, Sendable {
|
||||
/// A consumer key and secret that allows access to endpoints that requires authentication.
|
||||
case consumer(key: String, secret: String)
|
||||
/// No authentication method defined.
|
||||
case none
|
||||
/// A user token that allows access to its own account information.
|
||||
case user(token: String)
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
// ===----------------------------------------------------------------------===
|
||||
//
|
||||
// This source file is part of the DiscogsService open source project
|
||||
//
|
||||
// Copyright (c) 2025 Röck+Cöde VoF. and the DiscogsService project authors
|
||||
// Licensed under Apache license v2.0
|
||||
//
|
||||
// See LICENSE for license information
|
||||
// See CONTRIBUTORS for the list of DiscogsService project authors
|
||||
//
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
//
|
||||
// ===----------------------------------------------------------------------===
|
||||
|
||||
/// A representation of the available transport options to send credentials in authenticated requests.
|
||||
public enum AuthTransport: Sendable {
|
||||
/// Authentication credential are sent in a request as an `Authentication` header.
|
||||
///
|
||||
/// This means that the header will be added to any existing header in a request, like this:
|
||||
/// ```bash
|
||||
/// curl "https://api.discogs.com/database/search?q=Slayer" -H "Authorization: Discogs key=foo123, secret=bar456"
|
||||
/// curl "https://api.discogs.com/database/search?q=Slayer" -H "Authorization: Discogs token=abcxyz123456"
|
||||
/// ```
|
||||
case onHeader
|
||||
/// Authentication credential are sent in a request as parameters in the query string.
|
||||
///
|
||||
/// This means that the parameters will be injected into the query in a request, like this:
|
||||
/// ```bash
|
||||
/// curl "https://api.discogs.com/database/search?q=Slayer&key=foo123&secret=bar456"
|
||||
/// curl "https://api.discogs.com/database/search?q=Slayer&token=abcxyz123456"
|
||||
/// ```
|
||||
case onQuery
|
||||
}
|
||||
@@ -0,0 +1,160 @@
|
||||
// ===----------------------------------------------------------------------===
|
||||
//
|
||||
// This source file is part of the DiscogsService open source project
|
||||
//
|
||||
// Copyright (c) 2025 Röck+Cöde VoF. and the DiscogsService project authors
|
||||
// Licensed under Apache license v2.0
|
||||
//
|
||||
// See LICENSE for license information
|
||||
// See CONTRIBUTORS for the list of DiscogsService project authors
|
||||
//
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
//
|
||||
// ===----------------------------------------------------------------------===
|
||||
|
||||
import class OpenAPIRuntime.HTTPBody
|
||||
|
||||
import protocol OpenAPIRuntime.ClientMiddleware
|
||||
|
||||
import struct Foundation.URL
|
||||
import struct Foundation.URLComponents
|
||||
import struct Foundation.URLQueryItem
|
||||
import struct HTTPTypes.HTTPFields
|
||||
import struct HTTPTypes.HTTPRequest
|
||||
import struct HTTPTypes.HTTPResponse
|
||||
|
||||
/// A middleware that attaches any defined authentication credentials into the requests for the service.
|
||||
///
|
||||
/// Please refer to the [Discogs documentation](https://www.discogs.com/developers#page:authentication) for further information.
|
||||
public struct AuthMiddleware {
|
||||
|
||||
// MARK: Properties
|
||||
|
||||
/// A representation of an authentication method to use to authenticate requests.
|
||||
private let method: AuthMethod
|
||||
|
||||
/// A representation of a transport option to send credentials in requests.
|
||||
private let transport: AuthTransport
|
||||
|
||||
// MARK: Initializers
|
||||
|
||||
/// Initializes this middleware.
|
||||
/// - Parameters:
|
||||
/// - method: A representation of an authentication method to use to authenticate requests.
|
||||
/// - transport: A representation of a transport option to send credentials in requests.
|
||||
public init(
|
||||
method: AuthMethod = .none,
|
||||
transport: AuthTransport
|
||||
) {
|
||||
self.method = method
|
||||
self.transport = transport
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
// 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 method != .none else {
|
||||
return try await next(request, body, baseURL)
|
||||
}
|
||||
|
||||
let headerFields = if transport == .onHeader {
|
||||
authenticateHeader(request.headerFields)
|
||||
} else {
|
||||
request.headerFields
|
||||
}
|
||||
|
||||
let path = if transport == .onQuery {
|
||||
authenticatePath(request.path)
|
||||
} else {
|
||||
request.path
|
||||
}
|
||||
|
||||
return try await next(
|
||||
.init(
|
||||
method: request.method,
|
||||
scheme: request.scheme,
|
||||
authority: request.authority,
|
||||
path: path,
|
||||
headerFields: headerFields
|
||||
),
|
||||
body,
|
||||
baseURL
|
||||
)
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
// MARK: - Helpers
|
||||
|
||||
private extension AuthMiddleware {
|
||||
|
||||
// MARK: Functions
|
||||
|
||||
/// Adds an authorization header to the existing header fields.
|
||||
/// - Parameter fields: A set of header fields to update.
|
||||
/// - Returns: An updated set of header fields.
|
||||
func authenticateHeader(_ fields: HTTPFields) -> HTTPFields {
|
||||
var fields = fields
|
||||
|
||||
let authorization: String = switch method {
|
||||
case let .consumer(key, secret): .init(format: .Format.authConsumer, key, secret)
|
||||
case let .user(token): .init(format: .Format.authUser, token)
|
||||
default: .empty
|
||||
}
|
||||
|
||||
fields.append(.init(
|
||||
name: .authorization,
|
||||
value: authorization
|
||||
))
|
||||
|
||||
return fields
|
||||
}
|
||||
|
||||
/// Adds the authentication parameters to the query of a path
|
||||
/// - Parameter path: A request path to authenticate.
|
||||
/// - Returns: An updated request path including the authentication parameters.
|
||||
func authenticatePath(_ path: String?) -> String? {
|
||||
guard
|
||||
let path,
|
||||
var urlComponents = URLComponents(string: path)
|
||||
else {
|
||||
return path
|
||||
}
|
||||
|
||||
let authItems: [URLQueryItem] = switch method {
|
||||
case let .consumer(key, secret): [
|
||||
.init(name: .Parameter.key, value: key),
|
||||
.init(name: .Parameter.secret, value: secret)
|
||||
]
|
||||
case let .user(token): [
|
||||
.init(name: .Parameter.token, value: token)
|
||||
]
|
||||
default: []
|
||||
}
|
||||
|
||||
var queryItems = urlComponents.queryItems ?? []
|
||||
|
||||
queryItems.append(contentsOf: authItems)
|
||||
|
||||
urlComponents.queryItems = queryItems
|
||||
|
||||
return if let urlQuery = urlComponents.query {
|
||||
urlComponents.path + "?" + urlQuery
|
||||
} else {
|
||||
urlComponents.path
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,2 +0,0 @@
|
||||
// The Swift Programming Language
|
||||
// https://docs.swift.org/swift-book
|
||||
Reference in New Issue
Block a user