Skip to content

Commit

Permalink
Merge pull request #120 from vapor-community/signature-helper
Browse files Browse the repository at this point in the history
Add signature verification helper to Request
  • Loading branch information
Andrewangeta authored Apr 30, 2020
2 parents 6263f01 + 6e582c2 commit 7c45d02
Showing 1 changed file with 37 additions and 0 deletions.
37 changes: 37 additions & 0 deletions Sources/Stripe/Stripe+Extensions.swift
Original file line number Diff line number Diff line change
Expand Up @@ -38,3 +38,40 @@ extension Request {
}
}
}

extension StripeClient {
/// Verifies a Stripe signature for a given `Request`. This automatically looks for the header in the headers of the request and the body.
/// - Parameters:
/// - req: The `Request` object to check header and body for
/// - secret: The webhook secret used to verify the signature
/// - tolerance: In seconds the time difference tolerance to prevent replay attacks: Default 300 seconds
/// - Throws: `StripeSignatureError`
public static func verifySignature(for req: Request, secret: String, tolerance: Double = 300) throws {
guard let header = req.headers.first(name: "Stripe-Signature") else {
throw StripeSignatureError.unableToParseHeader
}

guard let data = req.body.data else {
throw StripeSignatureError.noMatchingSignatureFound
}

try StripeClient.verifySignature(payload: Data(data.readableBytesView), header: header, secret: secret, tolerance: tolerance)
}
}

extension StripeSignatureError: AbortError {
public var reason: String {
switch self {
case .noMatchingSignatureFound:
return "No matching signature was found"
case .timestampNotTolerated:
return "Timestamp was not tolerated"
case .unableToParseHeader:
return "Unable to parse Stripe-Signature header"
}
}

public var status: HTTPResponseStatus {
.badRequest
}
}

0 comments on commit 7c45d02

Please sign in to comment.