Skip to content

Commit

Permalink
JWT token auto update for APNS
Browse files Browse the repository at this point in the history
  • Loading branch information
Halimjon Juraev committed Mar 30, 2018
1 parent ef83965 commit 418786c
Show file tree
Hide file tree
Showing 3 changed files with 15 additions and 7 deletions.
2 changes: 1 addition & 1 deletion Sources/VaporNotifications/Apple/APNSErrors.swift
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
import Foundation

public struct APNSError: Codable {
let reason: APNSErrors
public let reason: APNSErrors
}
public enum APNSErrors: String, Codable {
case BadCollapseId = "BadCollapseId"
Expand Down
8 changes: 6 additions & 2 deletions Sources/VaporNotifications/Apple/APNSMessage.swift
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,11 @@ public struct ApplePushMessage {
if let threadId = threadIdentifier {
headers.add(name: HTTPHeaderName("thread-id"), value: threadId)
}
headers.add(name: HTTPHeaderName("authorization"), value: "bearer \(profile.Token)")
if profile.tokenExpiration <= Date() {
try? profile.generateToken()
}

headers.add(name: HTTPHeaderName("authorization"), value: "bearer \(profile.Token ?? "")")
return headers
}

Expand Down Expand Up @@ -98,7 +102,7 @@ public struct ApplePushMessage {
struct APNSJWTPayload: JWTPayload {
let iss: String
let iat = IssuedAtClaim(value: Date())
let exp = ExpirationClaim(value: Date(timeInterval: 10000, since: Date()))
let exp = ExpirationClaim(value: Date(timeInterval: 3500, since: Date()))
func verify() throws {
}
}
Expand Down
12 changes: 8 additions & 4 deletions Sources/VaporNotifications/Apple/APNSProfile.swift
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
import Foundation
import JWT

public struct APNSProfile {
public class APNSProfile {
public enum Port: Int {
case p443 = 443, p2197 = 2197
}
Expand All @@ -17,8 +17,8 @@ public struct APNSProfile {
public var port: Port = .p443
public var teamId: String
public var keyId: String
public let Token: String

public var Token: String?
public var tokenExpiration: Date = Date()
var privateKey: Data
var publicKey: Data

Expand Down Expand Up @@ -53,10 +53,13 @@ public struct APNSProfile {
let (priv, pub) = KeyUtilities.generateKeys(Path: keyPath)
self.publicKey = pub
self.privateKey = priv
try generateToken()
}

func generateToken() throws {
let JWTheaders = JWTHeader(alg: "ES256", cty: nil, crit: nil, kid: keyId)
let payload = APNSJWTPayload(iss: teamId)


let signer = JWTSigner.es256(key: privateKey)

var jwt = JWT(header: JWTheaders, payload: payload)
Expand All @@ -66,6 +69,7 @@ public struct APNSProfile {
guard let token = stringToken else {
throw TokenError.tokenWasNotGeneratedCorrectly
}
tokenExpiration = Date(timeInterval: 3500, since: Date())
self.Token = token
}

Expand Down

0 comments on commit 418786c

Please sign in to comment.