Skip to content

Commit

Permalink
Adds signInWithApple method
Browse files Browse the repository at this point in the history
  • Loading branch information
grdsdev committed Jul 7, 2023
1 parent a57ef51 commit 54f50d2
Show file tree
Hide file tree
Showing 4 changed files with 102 additions and 0 deletions.
4 changes: 4 additions & 0 deletions Examples/Examples.xcodeproj/project.pbxproj
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
798AD52129072C22001B4801 /* AppView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 798AD52029072C22001B4801 /* AppView.swift */; };
798AD5232907309C001B4801 /* SessionView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 798AD5222907309C001B4801 /* SessionView.swift */; };
798AD525290731A0001B4801 /* AuthWithEmailAndPasswordView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 798AD524290731A0001B4801 /* AuthWithEmailAndPasswordView.swift */; };
79C17A802A589EC000C67A61 /* SignInWithAppleView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 79C17A7F2A589EC000C67A61 /* SignInWithAppleView.swift */; };
/* End PBXBuildFile section */

/* Begin PBXFileReference section */
Expand All @@ -26,6 +27,7 @@
798AD52029072C22001B4801 /* AppView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AppView.swift; sourceTree = "<group>"; };
798AD5222907309C001B4801 /* SessionView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SessionView.swift; sourceTree = "<group>"; };
798AD524290731A0001B4801 /* AuthWithEmailAndPasswordView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AuthWithEmailAndPasswordView.swift; sourceTree = "<group>"; };
79C17A7F2A589EC000C67A61 /* SignInWithAppleView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SignInWithAppleView.swift; sourceTree = "<group>"; };
/* End PBXFileReference section */

/* Begin PBXFrameworksBuildPhase section */
Expand Down Expand Up @@ -83,6 +85,7 @@
18DE589E286B2C77005F7FF2 /* ExamplesApp.swift */,
1820720D286B449B0009D0BF /* Secrets.swift */,
798AD5222907309C001B4801 /* SessionView.swift */,
79C17A7F2A589EC000C67A61 /* SignInWithAppleView.swift */,
);
path = Sources;
sourceTree = "<group>";
Expand Down Expand Up @@ -164,6 +167,7 @@
798AD52129072C22001B4801 /* AppView.swift in Sources */,
798AD525290731A0001B4801 /* AuthWithEmailAndPasswordView.swift in Sources */,
798AD5232907309C001B4801 /* SessionView.swift in Sources */,
79C17A802A589EC000C67A61 /* SignInWithAppleView.swift in Sources */,
);
runOnlyForDeploymentPostprocessing = 0;
};
Expand Down
4 changes: 4 additions & 0 deletions Examples/Shared/Sources/AppView.swift
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,10 @@ struct AppView: View {
NavigationLink("Auth with Email and Password") {
AuthWithEmailAndPasswordView()
}

NavigationLink("Sign in with Apple") {
SignInWithAppleView()
}
}
.listStyle(.plain)
.navigationTitle("Examples")
Expand Down
84 changes: 84 additions & 0 deletions Examples/Shared/Sources/SignInWithAppleView.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
//
// SignInWithAppleView.swift
// Examples
//
// Created by Guilherme Souza on 07/07/23.
//

import SwiftUI
import AuthenticationServices
import CryptoKit

struct SignInWithAppleView: View {
@Environment(\.goTrueClient) private var client

@State var nonce: String?

var body: some View {
SignInWithAppleButton { request in
self.nonce = sha256(randomNonceString())
request.requestedScopes = [.fullName, .email]
request.nonce = nonce
} onCompletion: { result in
switch result {
case .success(let authorization):
guard let credential = authorization.credential as? ASAuthorizationAppleIDCredential else {
return
}

signInWithApple(credential: credential)

case .failure(let error):
dump(error)
}
}
.fixedSize()
}

private func signInWithApple(credential: ASAuthorizationAppleIDCredential) {
Task {
do {
try await client.signInWithApple(credential: credential, nonce: nonce)
} catch {
dump(error)
}
}
}
}

private func randomNonceString(length: Int = 32) -> String {
precondition(length > 0)
var randomBytes = [UInt8](repeating: 0, count: length)
let errorCode = SecRandomCopyBytes(kSecRandomDefault, randomBytes.count, &randomBytes)
if errorCode != errSecSuccess {
fatalError(
"Unable to generate nonce. SecRandomCopyBytes failed with OSStatus \(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)
}

@available(iOS 13, *)
private 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
}


#Preview {
SignInWithAppleView()
}
10 changes: 10 additions & 0 deletions Sources/GoTrue/GoTrueClient.swift
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import Foundation
import AuthenticationServices
import Get

#if canImport(FoundationNetworking)
Expand Down Expand Up @@ -177,6 +178,15 @@ public final class GoTrueClient {
)
}

@discardableResult
public func signInWithApple(credential: ASAuthorizationAppleIDCredential, nonce: String? = nil) async throws -> Session {
guard let idToken = credential.identityToken.flatMap({ String(data: $0, encoding: .utf8) }) else {
throw GoTrueError.sessionNotFound
}

return try await signInWithIdToken(credentials: .init(provider: .apple, idToken: idToken))
}

private func _signIn(request: Request<Session>) async throws -> Session {
await env.sessionManager.remove()

Expand Down

0 comments on commit 54f50d2

Please sign in to comment.