JWTManager.swift 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. // LoopFollow
  2. // JWTManager.swift
  3. import Foundation
  4. import SwiftJWT
  5. struct JWTClaims: Claims {
  6. let iss: String
  7. let iat: Date
  8. }
  9. class JWTManager {
  10. static let shared = JWTManager()
  11. private init() {}
  12. func getOrGenerateJWT(keyId: String, teamId: String, apnsKey: String) -> String? {
  13. // 1. Check for a valid, non-expired JWT directly from Storage.shared
  14. if let jwt = Storage.shared.cachedJWT.value,
  15. let expiration = Storage.shared.jwtExpirationDate.value,
  16. Date() < expiration
  17. {
  18. return jwt
  19. }
  20. // 2. If no valid JWT is found, generate a new one
  21. let header = Header(kid: keyId)
  22. let claims = JWTClaims(iss: teamId, iat: Date())
  23. var jwt = JWT(header: header, claims: claims)
  24. do {
  25. let privateKey = Data(apnsKey.utf8)
  26. let jwtSigner = JWTSigner.es256(privateKey: privateKey)
  27. let signedJWT = try jwt.sign(using: jwtSigner)
  28. // 3. Save the new JWT and its expiration date directly to Storage.shared
  29. Storage.shared.cachedJWT.value = signedJWT
  30. Storage.shared.jwtExpirationDate.value = Date().addingTimeInterval(3600) // Expires in 1 hour
  31. return signedJWT
  32. } catch {
  33. LogManager.shared.log(category: .apns, message: "Failed to sign JWT: \(error.localizedDescription)")
  34. return nil
  35. }
  36. }
  37. // Invalidate the cache by clearing values in Storage.shared
  38. func invalidateCache() {
  39. Storage.shared.cachedJWT.value = nil
  40. Storage.shared.jwtExpirationDate.value = nil
  41. }
  42. }