Swiftpack.co - ptrkstr/APIKeyMiddleware as Swift Package

Swiftpack.co is a collection of thousands of indexed Swift packages. Search packages.
See all packages published by ptrkstr.
ptrkstr/APIKeyMiddleware 1.0.0
Swift package for adding API Key requirement to vapor backends.
⭐️ 3
🕓 2 years ago
macOS
.package(url: "https://github.com/ptrkstr/APIKeyMiddleware.git", from: "1.0.0")

APIKeyMiddleware



Minimum Supported Vapor Version is 4

Swift package for adding API Key requirement to vapor backends.

Features

  • ✅ Supports an array of keys
  • ✅ Supports overriding thrown errors
  • ✅ 100% Test Coverage

Usage

Requests are expected to have the header api-key.

Simple

public func configure(_ app: Application) throws {
    app.middleware.use(APIKeyMiddleware(keys: ["123"]))
}

See Vapor Docs if wanting to add to individual routes.

Override Errors

The following errors are used by default:

  • Missing API key: Abort(.badRequest, reason: "Missing api-key.")
  • Unauthorized API Key: Abort(.unauthorized, reason: "Unauthorized api-key.")

To override these errors, assign a delegate to the APIKeyMiddleware. Returning nil uses defaults.

class Delegate: APIKeyMiddlewareDelegate {

    static let shared = Delegate()

    init() {}

    func errorForMissingKey(in middleware: APIKeyMiddleware) -> Error? {
        Abort(.imATeapot, reason: "Missing api-key was found by teapot.")
    }

    func errorForUnauthorizedKey(in middleware: APIKeyMiddleware) -> Error? {
        Abort(.imATeapot, reason: "Unauthorized api-key was found by teapot.")
    }
}

public func configure(_ app: Application) throws {
    let middleware = APIKeyMiddleware(keys: ["123"], delegate: Delegate.shared)
    app.middleware.use(middleware)
}

Installation

SPM

Add the following to your project:

https://github.com/ptrkstr/APIKeyMiddleware

Possible Future Features

Raise an issue if you need these

  • Allow overriding API-Key header name

GitHub

link
Stars: 3
Last commit: 2 years ago
Advertisement: IndiePitcher.com - Cold Email Software for Startups

Dependencies

Swiftpack is being maintained by Petr Pavlik | @ptrpavlik | @swiftpackco | API | Analytics