Skip to content

Commit

Permalink
fix: Support validating dates on linux
Browse files Browse the repository at this point in the history
  • Loading branch information
kylef committed Dec 2, 2016
1 parent 8cd089b commit d945892
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 7 deletions.
31 changes: 25 additions & 6 deletions Sources/Claims.swift
Original file line number Diff line number Diff line change
Expand Up @@ -39,12 +39,31 @@ func validateIssuer(_ payload: Payload, issuer: String?) throws {
}

func validateDate(_ payload:Payload, key:String, comparison:ComparisonResult, failure:InvalidToken, decodeError:String) throws {
if let timestamp = payload[key] as? TimeInterval ?? (payload[key] as? NSString)?.doubleValue as TimeInterval? {
let date = Date(timeIntervalSince1970: timestamp)
if date.compare(Date()) == comparison {
throw failure
}
} else if payload[key] != nil {
if payload[key] == nil {
return
}

guard let date = extractDate(payload: payload, key: key) else {
throw InvalidToken.decodeError(decodeError)
}

if date.compare(Date()) == comparison {
throw failure
}
}

fileprivate func extractDate(payload: Payload, key: String) -> Date? {
if let timestamp = payload[key] as? TimeInterval {
return Date(timeIntervalSince1970: timestamp)
}

if let timestamp = payload[key] as? Int {
return Date(timeIntervalSince1970: Double(timestamp))
}

if let timestampString = payload[key] as? String, let timestamp = Double(timestampString) {
return Date(timeIntervalSince1970: timestamp)
}

return nil
}
2 changes: 1 addition & 1 deletion Tests/JWTTests/JWTTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -176,7 +176,7 @@ class DecodeTests: XCTestCase {
XCTAssertEqual(payload as! [String: Int], ["iat": 1428189720])
}
}

func testIssuedAtClaimInThePastString() {
let jwt = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpYXQiOiIxNDI4MTg5NzIwIn0.M8veWtsY52oBwi7LRKzvNnzhjK0QBS8Su1r0atlns2k"
assertSuccess(try decode(jwt, algorithm: .hs256("secret".data(using: .utf8)!))) { payload in
Expand Down

0 comments on commit d945892

Please sign in to comment.