Skip to content
This repository has been archived by the owner on Apr 20, 2024. It is now read-only.

Commit

Permalink
Merge pull request #91 from nodes-vapor/feature/specify-header
Browse files Browse the repository at this point in the history
Make it possible to configure source and error
  • Loading branch information
steffendsommer authored Jan 25, 2019
2 parents e403b05 + 618d85c commit cdb9bdb
Showing 1 changed file with 12 additions and 3 deletions.
15 changes: 12 additions & 3 deletions Sources/Sugar/Middlewares/SimpleAuthMiddleware.swift
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,20 @@ import AuthProvider

public final class SimpleAuthMiddleware: Middleware {
private let token: String
private let authSource: (Request) -> String?
private let shouldAuth: (Request) -> Bool
private let error: AbortError

public init(token: String, shouldAuth: @escaping (Request) -> Bool = { _ in true }) {
public init(
token: String,
authSource: @escaping (Request) -> String? = { $0.auth.header?.string },
shouldAuth: @escaping (Request) -> Bool = { _ in true },
error: AbortError = Abort.unauthorized
) {
self.token = token
self.authSource = authSource
self.shouldAuth = shouldAuth
self.error = error
}

public func respond(to request: Request, chainingTo next: Responder) throws -> Response {
Expand All @@ -18,8 +27,8 @@ public final class SimpleAuthMiddleware: Middleware {
}

// Check for token
guard let header = request.auth.header, header.string == token else {
throw Abort.unauthorized
guard let authSource = authSource(request), authSource == token else {
throw error
}

return try next.respond(to: request)
Expand Down

0 comments on commit cdb9bdb

Please sign in to comment.