Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
//
// AccountService+Apple.swift
// FirebaseUI
//
// Created by Russell Wheatley on 21/10/2025.
//

@preconcurrency import FirebaseAuth
import FirebaseAuthSwiftUI
import Observation

protocol AppleOperationReauthentication {
var appleProvider: AppleProviderSwift { get }
}

extension AppleOperationReauthentication {
@MainActor func reauthenticate() async throws -> AuthenticationToken {
guard let user = Auth.auth().currentUser else {
throw AuthServiceError.reauthenticationRequired("No user currently signed-in")
}

do {
let credential = try await appleProvider.createAuthCredential()
try await user.reauthenticate(with: credential)

return .firebase("")
} catch {
throw AuthServiceError.signInFailed(underlying: error)
}
}
}

@MainActor
class AppleDeleteUserOperation: AuthenticatedOperation,
@preconcurrency AppleOperationReauthentication {
let appleProvider: AppleProviderSwift
init(appleProvider: AppleProviderSwift) {
self.appleProvider = appleProvider
}

func callAsFunction(on user: User) async throws {
try await callAsFunction(on: user) {
try await user.delete()
}
}
}

Original file line number Diff line number Diff line change
@@ -0,0 +1,163 @@
// Copyright 2025 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

import AuthenticationServices
import CryptoKit
import FirebaseAuth
import FirebaseAuthSwiftUI
import FirebaseCore
import SwiftUI

// MARK: - Data Extensions

extension Data {
var utf8String: String? {
return String(data: self, encoding: .utf8)
}
}

extension ASAuthorizationAppleIDCredential {
var authorizationCodeString: String? {
return authorizationCode?.utf8String
}

var idTokenString: String? {
return identityToken?.utf8String
}
}

// MARK: - Authenticate With Apple Dialog

private func authenticateWithApple(
scopes: [ASAuthorization.Scope]
) async throws -> (ASAuthorizationAppleIDCredential, String) {
return try await AuthenticateWithAppleDialog(scopes: scopes).authenticate()
}

private class AuthenticateWithAppleDialog: NSObject {
private var continuation: CheckedContinuation<(ASAuthorizationAppleIDCredential, String), Error>?
private var currentNonce: String?
private let scopes: [ASAuthorization.Scope]

init(scopes: [ASAuthorization.Scope]) {
self.scopes = scopes
super.init()
}

func authenticate() async throws -> (ASAuthorizationAppleIDCredential, String) {
return try await withCheckedThrowingContinuation { continuation in
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

(ASAuthorizationAppleIDCredential, String) tuple is being returned but I don't see where.

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ah nevermind seen, interesting didn't think this was a way to go

self.continuation = continuation

let appleIDProvider = ASAuthorizationAppleIDProvider()
let request = appleIDProvider.createRequest()
request.requestedScopes = scopes

do {
let nonce = try CryptoUtils.randomNonceString()
currentNonce = nonce
request.nonce = CryptoUtils.sha256(nonce)
} catch {
continuation.resume(throwing: AuthServiceError.signInFailed(underlying: error))
return
}

let authorizationController = ASAuthorizationController(authorizationRequests: [request])
authorizationController.delegate = self
authorizationController.performRequests()
}
}
}

extension AuthenticateWithAppleDialog: ASAuthorizationControllerDelegate {
func authorizationController(
controller: ASAuthorizationController,
didCompleteWithAuthorization authorization: ASAuthorization
) {
if let appleIDCredential = authorization.credential as? ASAuthorizationAppleIDCredential {
if let nonce = currentNonce {
continuation?.resume(returning: (appleIDCredential, nonce))
} else {
continuation?.resume(
throwing: AuthServiceError.signInFailed(
underlying: NSError(
domain: "AppleSignIn",
code: -1,
userInfo: [NSLocalizedDescriptionKey: "Missing nonce"]
)
)
)
}
} else {
continuation?.resume(
throwing: AuthServiceError.invalidCredentials("Missing Apple ID credential")
)
}
continuation = nil
}

func authorizationController(
controller: ASAuthorizationController,
didCompleteWithError error: Error
) {
continuation?.resume(throwing: AuthServiceError.signInFailed(underlying: error))
continuation = nil
}
}

// MARK: - Apple Provider Swift

public class AppleProviderSwift: AuthProviderSwift, DeleteUserSwift {
public let scopes: [ASAuthorization.Scope]
let providerId = "apple.com"

public init(scopes: [ASAuthorization.Scope] = [.fullName, .email]) {
self.scopes = scopes
}

@MainActor public func createAuthCredential() async throws -> AuthCredential {
let (appleIDCredential, nonce) = try await authenticateWithApple(scopes: scopes)

guard let idTokenString = appleIDCredential.idTokenString else {
throw AuthServiceError.invalidCredentials("Unable to fetch identity token from Apple")
}

let credential = OAuthProvider.appleCredential(
withIDToken: idTokenString,
rawNonce: nonce,
fullName: appleIDCredential.fullName
)

return credential
}

public func deleteUser(user: User) async throws {
let operation = AppleDeleteUserOperation(appleProvider: self)
try await operation(on: user)
}
}

public class AppleProviderAuthUI: AuthProviderUI {
public var provider: AuthProviderSwift

public init(provider: AuthProviderSwift) {
self.provider = provider
}

public let id: String = "apple.com"

@MainActor public func authButton() -> AnyView {
AnyView(SignInWithAppleButton(provider: provider))
}
}

Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
// Copyright 2025 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

//
// AuthService+Apple.swift
// FirebaseUI
//
// Created by Russell Wheatley on 21/10/2025.
//

import FirebaseAuthSwiftUI

public extension AuthService {
@discardableResult
func withAppleSignIn(_ provider: AppleProviderSwift? = nil) -> AuthService {
registerProvider(providerWithButton: AppleProviderAuthUI(provider: provider ??
AppleProviderSwift()))
return self
}
}

Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
// Copyright 2025 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

import Foundation
import CryptoKit

/// Set of utility APIs for generating cryptographical artifacts.
enum CryptoUtils {
enum NonceGenerationError: Error {
case generationFailure(status: OSStatus)
}

static func randomNonceString(length: Int = 32) throws -> String {
precondition(length > 0)
var randomBytes = [UInt8](repeating: 0, count: length)
let errorCode = SecRandomCopyBytes(kSecRandomDefault, randomBytes.count, &randomBytes)
if errorCode != errSecSuccess {
throw NonceGenerationError.generationFailure(status: errorCode)
}

let charset: [Character] =
Array("0123456789ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvwxyz-._")

let nonce = randomBytes.map { byte in
// Pick a random character from the set, wrapping around if needed.
charset[Int(byte) % charset.count]
}

return String(nonce)
}

static func sha256(_ input: String) -> String {
let inputData = Data(input.utf8)
let hashedData = SHA256.hash(data: inputData)
let hashString = hashedData.compactMap {
String(format: "%02x", $0)
}.joined()

return hashString
}
}

Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
// Copyright 2025 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

import FirebaseAuthSwiftUI
import SwiftUI

/// A button for signing in with Apple
@MainActor
public struct SignInWithAppleButton {
@Environment(AuthService.self) private var authService
let provider: AuthProviderSwift
public init(provider: AuthProviderSwift) {
self.provider = provider
}
}

extension SignInWithAppleButton: View {
public var body: some View {
Button(action: {
Task {
try await authService.signIn(provider)
}
}) {
HStack {
Image(systemName: "apple.logo")
.resizable()
.renderingMode(.template)
.scaledToFit()
.frame(width: 24, height: 24)
.foregroundColor(.white)
Text("Sign in with Apple")
.fontWeight(.semibold)
.foregroundColor(.white)
}
.frame(maxWidth: .infinity, alignment: .leading)
.padding()
.background(Color.black)
.cornerRadius(8)
}
.accessibilityIdentifier("sign-in-with-apple-button")
}
}

Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
// Copyright 2025 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

@testable import FirebaseAppleSwiftUI
import Testing

@Test func example() async throws {
// Write your test here and use APIs like `#expect(...)` to check expected conditions.
}

Loading
Loading