Unify sharing codec and wire iOS KMP actuals
This commit is contained in:
@@ -768,6 +768,7 @@
|
||||
1C685CD92EC5539000A9669B /* Debug */ = {
|
||||
isa = XCBuildConfiguration;
|
||||
buildSettings = {
|
||||
ARCHS = arm64;
|
||||
BUNDLE_LOADER = "$(TEST_HOST)";
|
||||
CODE_SIGN_STYLE = Automatic;
|
||||
CURRENT_PROJECT_VERSION = 1;
|
||||
@@ -779,11 +780,13 @@
|
||||
PRODUCT_BUNDLE_IDENTIFIER = "com.t-t.CaseraTests";
|
||||
PRODUCT_NAME = "$(TARGET_NAME)";
|
||||
STRING_CATALOG_GENERATE_SYMBOLS = NO;
|
||||
SWIFT_ENABLE_EXPLICIT_MODULES = NO;
|
||||
SWIFT_APPROACHABLE_CONCURRENCY = YES;
|
||||
SWIFT_EMIT_LOC_STRINGS = NO;
|
||||
SWIFT_UPCOMING_FEATURE_MEMBER_IMPORT_VISIBILITY = YES;
|
||||
SWIFT_VERSION = 5.0;
|
||||
TARGETED_DEVICE_FAMILY = "1,2";
|
||||
TEST_TARGET_NAME = Casera;
|
||||
TEST_HOST = "$(BUILT_PRODUCTS_DIR)/Casera.app/$(BUNDLE_EXECUTABLE_FOLDER_PATH)/Casera";
|
||||
};
|
||||
name = Debug;
|
||||
@@ -791,6 +794,7 @@
|
||||
1C685CDA2EC5539000A9669B /* Release */ = {
|
||||
isa = XCBuildConfiguration;
|
||||
buildSettings = {
|
||||
ARCHS = arm64;
|
||||
BUNDLE_LOADER = "$(TEST_HOST)";
|
||||
CODE_SIGN_STYLE = Automatic;
|
||||
CURRENT_PROJECT_VERSION = 1;
|
||||
@@ -802,11 +806,13 @@
|
||||
PRODUCT_BUNDLE_IDENTIFIER = "com.t-t.CaseraTests";
|
||||
PRODUCT_NAME = "$(TARGET_NAME)";
|
||||
STRING_CATALOG_GENERATE_SYMBOLS = NO;
|
||||
SWIFT_ENABLE_EXPLICIT_MODULES = NO;
|
||||
SWIFT_APPROACHABLE_CONCURRENCY = YES;
|
||||
SWIFT_EMIT_LOC_STRINGS = NO;
|
||||
SWIFT_UPCOMING_FEATURE_MEMBER_IMPORT_VISIBILITY = YES;
|
||||
SWIFT_VERSION = 5.0;
|
||||
TARGETED_DEVICE_FAMILY = "1,2";
|
||||
TEST_TARGET_NAME = Casera;
|
||||
TEST_HOST = "$(BUILT_PRODUCTS_DIR)/Casera.app/$(BUNDLE_EXECUTABLE_FOLDER_PATH)/Casera";
|
||||
};
|
||||
name = Release;
|
||||
|
||||
@@ -19,12 +19,6 @@ class ContractorSharingManager: ObservableObject {
|
||||
|
||||
// MARK: - Private Properties
|
||||
|
||||
private let jsonEncoder: JSONEncoder = {
|
||||
let encoder = JSONEncoder()
|
||||
encoder.outputFormatting = .prettyPrinted
|
||||
return encoder
|
||||
}()
|
||||
|
||||
private let jsonDecoder = JSONDecoder()
|
||||
|
||||
private init() {}
|
||||
@@ -38,23 +32,17 @@ class ContractorSharingManager: ObservableObject {
|
||||
// Get current username for export metadata
|
||||
let currentUsername = DataManagerObservable.shared.currentUser?.username ?? "Unknown"
|
||||
|
||||
// Convert Contractor to SharedContractor using Kotlin extension
|
||||
let sharedContractor = contractor.toSharedContractor(exportedBy: currentUsername)
|
||||
let jsonContent = CaseraShareCodec.shared.encodeContractorPackage(
|
||||
contractor: contractor,
|
||||
exportedBy: currentUsername
|
||||
)
|
||||
|
||||
// Create Swift-compatible structure for JSON encoding
|
||||
let exportData = SharedContractorExport(from: sharedContractor)
|
||||
|
||||
guard let jsonData = try? jsonEncoder.encode(exportData) else {
|
||||
print("ContractorSharingManager: Failed to encode contractor to JSON")
|
||||
guard let jsonData = jsonContent.data(using: .utf8) else {
|
||||
print("ContractorSharingManager: Failed to encode contractor package as UTF-8")
|
||||
return nil
|
||||
}
|
||||
|
||||
// Create a safe filename
|
||||
let safeName = contractor.name
|
||||
.replacingOccurrences(of: " ", with: "_")
|
||||
.replacingOccurrences(of: "/", with: "-")
|
||||
.prefix(50)
|
||||
let fileName = "\(safeName).casera"
|
||||
let fileName = CaseraShareCodec.shared.safeShareFileName(displayName: contractor.name)
|
||||
let tempURL = FileManager.default.temporaryDirectory.appendingPathComponent(fileName)
|
||||
|
||||
do {
|
||||
|
||||
@@ -12,6 +12,8 @@
|
||||
<string>com.example.casera.pro.annual</string>
|
||||
<key>CASERA_IAP_MONTHLY_PRODUCT_ID</key>
|
||||
<string>com.example.casera.pro.monthly</string>
|
||||
<key>CASERA_GOOGLE_WEB_CLIENT_ID</key>
|
||||
<string></string>
|
||||
<key>CFBundleDocumentTypes</key>
|
||||
<array>
|
||||
<dict>
|
||||
|
||||
@@ -1,5 +1,8 @@
|
||||
import Foundation
|
||||
import AuthenticationServices
|
||||
import CryptoKit
|
||||
import Security
|
||||
import UIKit
|
||||
import ComposeApp
|
||||
|
||||
/// Handles Google OAuth flow using ASWebAuthenticationSession.
|
||||
@@ -15,14 +18,18 @@ final class GoogleSignInManager: NSObject, ObservableObject, ASWebAuthentication
|
||||
var onSignInSuccess: ((Bool) -> Void)?
|
||||
|
||||
private var webAuthSession: ASWebAuthenticationSession?
|
||||
private var codeVerifier: String?
|
||||
private var oauthState: String?
|
||||
|
||||
private let redirectScheme = "casera"
|
||||
private var redirectURI: String { "\(redirectScheme):/oauth2callback" }
|
||||
|
||||
// MARK: - Public
|
||||
|
||||
func signIn() {
|
||||
guard !isLoading else { return }
|
||||
|
||||
let clientId = ApiConfig.shared.GOOGLE_WEB_CLIENT_ID
|
||||
guard ApiConfig.shared.isGoogleSignInConfigured else {
|
||||
guard let clientId = resolvedClientID() else {
|
||||
errorMessage = "Google Sign-In is not configured. A Google Cloud client ID is required."
|
||||
return
|
||||
}
|
||||
@@ -30,9 +37,14 @@ final class GoogleSignInManager: NSObject, ObservableObject, ASWebAuthentication
|
||||
isLoading = true
|
||||
errorMessage = nil
|
||||
|
||||
// PKCE + state are required for secure native OAuth.
|
||||
let verifier = Self.randomURLSafeString(length: 64)
|
||||
let challenge = Self.sha256Base64URL(verifier)
|
||||
let state = Self.randomURLSafeString(length: 32)
|
||||
codeVerifier = verifier
|
||||
oauthState = state
|
||||
|
||||
// Build Google OAuth URL
|
||||
let redirectScheme = "com.tt.casera"
|
||||
let redirectURI = "\(redirectScheme):/oauth2callback"
|
||||
var components = URLComponents(string: "https://accounts.google.com/o/oauth2/v2/auth")!
|
||||
components.queryItems = [
|
||||
URLQueryItem(name: "client_id", value: clientId),
|
||||
@@ -41,6 +53,9 @@ final class GoogleSignInManager: NSObject, ObservableObject, ASWebAuthentication
|
||||
URLQueryItem(name: "scope", value: "openid email profile"),
|
||||
URLQueryItem(name: "access_type", value: "offline"),
|
||||
URLQueryItem(name: "prompt", value: "select_account"),
|
||||
URLQueryItem(name: "code_challenge", value: challenge),
|
||||
URLQueryItem(name: "code_challenge_method", value: "S256"),
|
||||
URLQueryItem(name: "state", value: state),
|
||||
]
|
||||
|
||||
guard let authURL = components.url else {
|
||||
@@ -57,6 +72,7 @@ final class GoogleSignInManager: NSObject, ObservableObject, ASWebAuthentication
|
||||
guard let self else { return }
|
||||
|
||||
if let error {
|
||||
self.resetOAuthState()
|
||||
self.isLoading = false
|
||||
// Don't show error for user cancellation
|
||||
if (error as NSError).code != ASWebAuthenticationSessionError.canceledLogin.rawValue {
|
||||
@@ -66,14 +82,42 @@ final class GoogleSignInManager: NSObject, ObservableObject, ASWebAuthentication
|
||||
}
|
||||
|
||||
guard let callbackURL,
|
||||
let components = URLComponents(url: callbackURL, resolvingAgainstBaseURL: false),
|
||||
let code = components.queryItems?.first(where: { $0.name == "code" })?.value else {
|
||||
let components = URLComponents(url: callbackURL, resolvingAgainstBaseURL: false) else {
|
||||
self.isLoading = false
|
||||
self.resetOAuthState()
|
||||
self.errorMessage = "Failed to get authorization code from Google"
|
||||
return
|
||||
}
|
||||
|
||||
await self.exchangeCodeForToken(code: code, redirectURI: redirectURI, clientId: clientId)
|
||||
if let oauthError = components.queryItems?.first(where: { $0.name == "error" })?.value {
|
||||
self.isLoading = false
|
||||
self.resetOAuthState()
|
||||
self.errorMessage = "Google Sign-In error: \(oauthError)"
|
||||
return
|
||||
}
|
||||
|
||||
guard let callbackState = components.queryItems?.first(where: { $0.name == "state" })?.value,
|
||||
callbackState == self.oauthState else {
|
||||
self.isLoading = false
|
||||
self.resetOAuthState()
|
||||
self.errorMessage = "Invalid Google OAuth state. Please try again."
|
||||
return
|
||||
}
|
||||
|
||||
guard let code = components.queryItems?.first(where: { $0.name == "code" })?.value,
|
||||
let verifier = self.codeVerifier else {
|
||||
self.isLoading = false
|
||||
self.resetOAuthState()
|
||||
self.errorMessage = "Failed to get authorization code from Google"
|
||||
return
|
||||
}
|
||||
|
||||
await self.exchangeCodeForToken(
|
||||
code: code,
|
||||
redirectURI: self.redirectURI,
|
||||
clientId: clientId,
|
||||
codeVerifier: verifier
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -86,16 +130,23 @@ final class GoogleSignInManager: NSObject, ObservableObject, ASWebAuthentication
|
||||
// MARK: - ASWebAuthenticationPresentationContextProviding
|
||||
|
||||
nonisolated func presentationAnchor(for session: ASWebAuthenticationSession) -> ASPresentationAnchor {
|
||||
// Return the key window for presentation
|
||||
let scenes = UIApplication.shared.connectedScenes
|
||||
let windowScene = scenes.first(where: { $0.activationState == .foregroundActive }) as? UIWindowScene
|
||||
return windowScene?.windows.first(where: { $0.isKeyWindow }) ?? ASPresentationAnchor()
|
||||
MainActor.assumeIsolated {
|
||||
// Return the key window for presentation
|
||||
let scenes = UIApplication.shared.connectedScenes
|
||||
let windowScene = scenes.first(where: { $0.activationState == .foregroundActive }) as? UIWindowScene
|
||||
return windowScene?.windows.first(where: { $0.isKeyWindow }) ?? ASPresentationAnchor()
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Private
|
||||
|
||||
/// Exchange authorization code for ID token via Google's token endpoint
|
||||
private func exchangeCodeForToken(code: String, redirectURI: String, clientId: String) async {
|
||||
private func exchangeCodeForToken(
|
||||
code: String,
|
||||
redirectURI: String,
|
||||
clientId: String,
|
||||
codeVerifier: String
|
||||
) async {
|
||||
let tokenURL = URL(string: "https://oauth2.googleapis.com/token")!
|
||||
var request = URLRequest(url: tokenURL)
|
||||
request.httpMethod = "POST"
|
||||
@@ -106,16 +157,18 @@ final class GoogleSignInManager: NSObject, ObservableObject, ASWebAuthentication
|
||||
"client_id": clientId,
|
||||
"redirect_uri": redirectURI,
|
||||
"grant_type": "authorization_code",
|
||||
"code_verifier": codeVerifier,
|
||||
]
|
||||
request.httpBody = body
|
||||
.map { "\($0.key)=\($0.value.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed) ?? $0.value)" }
|
||||
.joined(separator: "&")
|
||||
.data(using: .utf8)
|
||||
|
||||
var encoded = URLComponents()
|
||||
encoded.queryItems = body.map { URLQueryItem(name: $0.key, value: $0.value) }
|
||||
request.httpBody = encoded.percentEncodedQuery?.data(using: .utf8)
|
||||
|
||||
do {
|
||||
let (data, response) = try await URLSession.shared.data(for: request)
|
||||
|
||||
guard let httpResponse = response as? HTTPURLResponse, httpResponse.statusCode == 200 else {
|
||||
resetOAuthState()
|
||||
isLoading = false
|
||||
errorMessage = "Failed to exchange authorization code"
|
||||
return
|
||||
@@ -123,6 +176,7 @@ final class GoogleSignInManager: NSObject, ObservableObject, ASWebAuthentication
|
||||
|
||||
guard let json = try? JSONSerialization.jsonObject(with: data) as? [String: Any],
|
||||
let idToken = json["id_token"] as? String else {
|
||||
resetOAuthState()
|
||||
isLoading = false
|
||||
errorMessage = "Failed to get ID token from Google"
|
||||
return
|
||||
@@ -131,6 +185,7 @@ final class GoogleSignInManager: NSObject, ObservableObject, ASWebAuthentication
|
||||
// Send ID token to backend
|
||||
await sendToBackend(idToken: idToken)
|
||||
} catch {
|
||||
resetOAuthState()
|
||||
isLoading = false
|
||||
errorMessage = "Network error: \(error.localizedDescription)"
|
||||
}
|
||||
@@ -142,12 +197,14 @@ final class GoogleSignInManager: NSObject, ObservableObject, ASWebAuthentication
|
||||
let result = try? await APILayer.shared.googleSignIn(request: request)
|
||||
|
||||
guard let result else {
|
||||
resetOAuthState()
|
||||
isLoading = false
|
||||
errorMessage = "Sign in failed. Please try again."
|
||||
return
|
||||
}
|
||||
|
||||
if let success = result as? ApiResultSuccess<GoogleSignInResponse>, let response = success.data {
|
||||
resetOAuthState()
|
||||
isLoading = false
|
||||
|
||||
// Share token and API URL with widget extension
|
||||
@@ -161,11 +218,46 @@ final class GoogleSignInManager: NSObject, ObservableObject, ASWebAuthentication
|
||||
onSignInSuccess?(response.user.verified)
|
||||
|
||||
} else if let error = ApiResultBridge.error(from: result) {
|
||||
resetOAuthState()
|
||||
isLoading = false
|
||||
errorMessage = ErrorMessageParser.parse(error.message)
|
||||
} else {
|
||||
resetOAuthState()
|
||||
isLoading = false
|
||||
errorMessage = "Sign in failed. Please try again."
|
||||
}
|
||||
}
|
||||
|
||||
private func resolvedClientID() -> String? {
|
||||
if let fromInfo = Bundle.main.object(forInfoDictionaryKey: "CASERA_GOOGLE_WEB_CLIENT_ID") as? String {
|
||||
let trimmed = fromInfo.trimmingCharacters(in: .whitespacesAndNewlines)
|
||||
if !trimmed.isEmpty {
|
||||
return trimmed
|
||||
}
|
||||
}
|
||||
|
||||
let fromShared = ApiConfig.shared.GOOGLE_WEB_CLIENT_ID.trimmingCharacters(in: .whitespacesAndNewlines)
|
||||
return fromShared.isEmpty ? nil : fromShared
|
||||
}
|
||||
|
||||
private func resetOAuthState() {
|
||||
codeVerifier = nil
|
||||
oauthState = nil
|
||||
}
|
||||
|
||||
private static func randomURLSafeString(length: Int) -> String {
|
||||
let allowed = Array("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~")
|
||||
var bytes = [UInt8](repeating: 0, count: length)
|
||||
_ = SecRandomCopyBytes(kSecRandomDefault, bytes.count, &bytes)
|
||||
return String(bytes.map { allowed[Int($0) % allowed.count] })
|
||||
}
|
||||
|
||||
private static func sha256Base64URL(_ input: String) -> String {
|
||||
let digest = SHA256.hash(data: Data(input.utf8))
|
||||
return Data(digest)
|
||||
.base64EncodedString()
|
||||
.replacingOccurrences(of: "+", with: "-")
|
||||
.replacingOccurrences(of: "/", with: "_")
|
||||
.replacingOccurrences(of: "=", with: "")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -29,12 +29,6 @@ class ResidenceSharingManager: ObservableObject {
|
||||
|
||||
// MARK: - Private Properties
|
||||
|
||||
private let jsonEncoder: JSONEncoder = {
|
||||
let encoder = JSONEncoder()
|
||||
encoder.outputFormatting = .prettyPrinted
|
||||
return encoder
|
||||
}()
|
||||
|
||||
private let jsonDecoder = JSONDecoder()
|
||||
|
||||
private init() {}
|
||||
@@ -70,21 +64,14 @@ class ResidenceSharingManager: ObservableObject {
|
||||
return nil
|
||||
}
|
||||
|
||||
// Create Swift-compatible structure for JSON encoding
|
||||
let exportData = SharedResidenceExport(from: sharedResidence)
|
||||
|
||||
guard let jsonData = try? jsonEncoder.encode(exportData) else {
|
||||
print("ResidenceSharingManager: Failed to encode residence to JSON")
|
||||
let jsonContent = CaseraShareCodec.shared.encodeSharedResidence(sharedResidence: sharedResidence)
|
||||
guard let jsonData = jsonContent.data(using: .utf8) else {
|
||||
print("ResidenceSharingManager: Failed to encode residence package as UTF-8")
|
||||
errorMessage = "Failed to create share file"
|
||||
return nil
|
||||
}
|
||||
|
||||
// Create a safe filename
|
||||
let safeName = residence.name
|
||||
.replacingOccurrences(of: " ", with: "_")
|
||||
.replacingOccurrences(of: "/", with: "-")
|
||||
.prefix(50)
|
||||
let fileName = "\(safeName).casera"
|
||||
let fileName = CaseraShareCodec.shared.safeShareFileName(displayName: residence.name)
|
||||
let tempURL = FileManager.default.temporaryDirectory.appendingPathComponent(fileName)
|
||||
|
||||
do {
|
||||
|
||||
Reference in New Issue
Block a user