-
Notifications
You must be signed in to change notification settings - Fork 2
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
7 changed files
with
215 additions
and
87 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
133 changes: 133 additions & 0 deletions
133
Sources/AppleMapsKit/Authorization/AuthorizationProvider.swift
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,133 @@ | ||
// | ||
// AuthorizationProvider.swift | ||
// apple-maps-kit | ||
// | ||
// Created by FarouK on 11/10/2024. | ||
// | ||
|
||
import AsyncHTTPClient | ||
import Foundation | ||
import JWTKit | ||
import NIOHTTP1 | ||
|
||
// MARK: - auth/c & auth/z | ||
internal actor AuthorizationProvider { | ||
|
||
private let httpClient: HTTPClient | ||
private let apiServer: String | ||
private let teamID: String | ||
private let keyID: String | ||
private let key: String | ||
|
||
private var currentToken: TokenResponse? | ||
private var refreshTask: Task<TokenResponse, any Error>? | ||
|
||
internal init(httpClient: HTTPClient, apiServer: String, teamID: String, keyID: String, key: String) { | ||
self.httpClient = httpClient | ||
self.apiServer = apiServer | ||
self.teamID = teamID | ||
self.keyID = keyID | ||
self.key = key | ||
} | ||
|
||
func validToken() async throws -> TokenResponse { | ||
// If we're currently refreshing a token, await the value for our refresh task to make sure we return the refreshed token. | ||
if let handle = refreshTask { | ||
return try await handle.value | ||
} | ||
|
||
// If we don't have a current token, we request a new one. | ||
guard let token = currentToken else { | ||
return try await refreshToken() | ||
} | ||
|
||
if token.isValid { | ||
return token | ||
} | ||
|
||
// None of the above applies so we'll need to refresh the token. | ||
return try await refreshToken() | ||
} | ||
|
||
private func refreshToken() async throws -> TokenResponse { | ||
if let refreshTask = refreshTask { | ||
return try await refreshTask.value | ||
} | ||
|
||
let task = Task { () throws -> TokenResponse in | ||
defer { refreshTask = nil } | ||
let authToken = try await createJWT(teamID: teamID, keyID: keyID, key: key) | ||
let newToken = try await getAccessToken(authToken: authToken) | ||
currentToken = newToken | ||
return newToken | ||
} | ||
|
||
self.refreshTask = task | ||
return try await task.value | ||
} | ||
} | ||
|
||
// MARK: - HELPERS | ||
extension AuthorizationProvider { | ||
|
||
/// Makes an HTTP request to exchange Auth token for Access token. | ||
/// | ||
/// - Parameters: | ||
/// - httpClient: The HTTP client to use. | ||
/// - authToken: The authorization token. | ||
/// | ||
/// - Throws: Error response object. | ||
/// | ||
/// - Returns: An access token. | ||
fileprivate func getAccessToken(authToken: String) async throws -> TokenResponse { | ||
var headers = HTTPHeaders() | ||
headers.add(name: "Authorization", value: "Bearer \(authToken)") | ||
|
||
var request = HTTPClientRequest(url: "\(apiServer)/v1/token") | ||
request.headers = headers | ||
|
||
let response = try await httpClient.execute(request, timeout: .seconds(30)) | ||
|
||
if response.status == .ok { | ||
return try await JSONDecoder() | ||
.decode(TokenResponse.self, from: response.body.collect(upTo: 1024 * 1024)) | ||
} else { | ||
throw try await JSONDecoder().decode(ErrorResponse.self, from: response.body.collect(upTo: 1024 * 1024)) | ||
} | ||
} | ||
|
||
/// Creates a JWT token, which is auth token in this context. | ||
/// | ||
/// - Parameters: | ||
/// - teamID: A 10-character Team ID obtained from your Apple Developer account. | ||
/// - keyID: A 10-character key identifier that provides the ID of the private key that you obtain from your Apple Developer account. | ||
/// - key: A MapKit JS private key. | ||
/// | ||
/// - Returns: A JWT token represented as `String`. | ||
fileprivate func createJWT(teamID: String, keyID: String, key: String) async throws -> String { | ||
let keys = try await JWTKeyCollection().add(ecdsa: ES256PrivateKey(pem: key)) | ||
|
||
var header = JWTHeader() | ||
header.alg = "ES256" | ||
header.kid = keyID | ||
header.typ = "JWT" | ||
|
||
struct Payload: JWTPayload { | ||
let iss: IssuerClaim | ||
let iat: IssuedAtClaim | ||
let exp: ExpirationClaim | ||
|
||
func verify(using key: some JWTAlgorithm) throws { | ||
try self.exp.verifyNotExpired() | ||
} | ||
} | ||
|
||
let payload = Payload( | ||
iss: IssuerClaim(value: teamID), | ||
iat: IssuedAtClaim(value: Date()), | ||
exp: ExpirationClaim(value: Date().addingTimeInterval(30 * 60)) | ||
) | ||
|
||
return try await keys.sign(payload, header: header) | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,38 @@ | ||
import Foundation | ||
|
||
/// An object that contains an access token and an expiration time in seconds. | ||
internal struct TokenResponse: Codable { | ||
/// A string that represents the access token. | ||
let accessToken: String | ||
|
||
/// An integer that indicates the time, in seconds from now until the token expires. | ||
let expiresInSeconds: Int | ||
|
||
/// A date that indicates when then token will expire. | ||
let expirationDate: Date | ||
|
||
internal init(from decoder: any Decoder) throws { | ||
let container = try decoder.container(keyedBy: CodingKeys.self) | ||
self.accessToken = try container.decode(String.self, forKey: .accessToken) | ||
self.expiresInSeconds = try container.decode(Int.self, forKey: .expiresInSeconds) | ||
self.expirationDate = Date.now.addingTimeInterval(TimeInterval(expiresInSeconds)) | ||
} | ||
|
||
internal init(accessToken: String, expiresInSeconds: Int) { | ||
self.accessToken = accessToken | ||
self.expiresInSeconds = expiresInSeconds | ||
self.expirationDate = Date.now.addingTimeInterval(TimeInterval(expiresInSeconds)) | ||
} | ||
|
||
} | ||
|
||
extension TokenResponse { | ||
|
||
/// A boolean indicates whether to token is valid 10 seconds before it's actual expiry time. | ||
var isValid: Bool { | ||
let currentDate = Date.now | ||
// we consider a token invalid 10 seconds before it actual expiry time, so we have some time to refresh it. | ||
let expirationBuffer: TimeInterval = 10 | ||
return currentDate < (expirationDate - expirationBuffer) | ||
} | ||
} |
This file was deleted.
Oops, something went wrong.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,28 @@ | ||
// | ||
// AuthorizationProviderTests.swift | ||
// apple-maps-kit | ||
// | ||
// Created by FarouK on 12/10/2024. | ||
// | ||
|
||
import Testing | ||
|
||
@testable import AppleMapsKit | ||
|
||
struct AuthorizationProviderTests { | ||
|
||
struct TokenValidityTests { | ||
// It's 1 second actually due to the expiration buffer on the token. | ||
let token = TokenResponse(accessToken: "some token", expiresInSeconds: 11) | ||
|
||
@Test func tokenInvalidCheck() async { | ||
try? await Task.sleep(for: .seconds(2)) | ||
#expect(token.isValid == false) | ||
} | ||
|
||
@Test func tokenValidCheck() async { | ||
#expect(token.isValid) | ||
} | ||
} | ||
|
||
} |