Skip to content

Commit

Permalink
chore: Add example for native Sign in with Apple (#62)
Browse files Browse the repository at this point in the history
* Adds signInWithApple method

* Mark signInWithApple as Experimental

* Add method for SIWA as a 2 steps process

* Remove signInWithApple method and add example

* Remove import not needed

* Fix preview

* Import GoTrue as Experimental
  • Loading branch information
grdsdev committed Jul 9, 2023
1 parent 5ddaad6 commit 7e68cae
Show file tree
Hide file tree
Showing 6 changed files with 101 additions and 1 deletion.
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/Examples.entitlements
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,10 @@
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>com.apple.developer.applesignin</key>
<array>
<string>Default</string>
</array>
<key>com.apple.security.app-sandbox</key>
<true/>
<key>com.apple.security.network.client</key>
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
87 changes: 87 additions & 0 deletions Examples/Shared/Sources/SignInWithAppleView.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,87 @@
//
// SignInWithAppleView.swift
// Examples
//
// Created by Guilherme Souza on 07/07/23.
//

import AuthenticationServices
import CryptoKit
import SwiftUI
@_spi(Experimental) import GoTrue

struct SignInWithAppleView: View {
@Environment(\.goTrueClient) private var client
@State var nonce: String?

var body: some View {
SignInWithAppleButton { request in
// self.nonce = sha256(randomString())
// request.nonce = nonce
request.requestedScopes = [.email, .fullName]
} onCompletion: { result in
Task {
do {
guard let credential = try result.get().credential as? ASAuthorizationAppleIDCredential
else {
return
}

guard let idToken = credential.identityToken
.flatMap({ String(data: $0, encoding: .utf8) })
else {
return
}

try await client.signInWithIdToken(
credentials: .init(
provider: .apple,
idToken: idToken/*,
nonce: self.nonce*/
)
)
} catch {
dump(error)
}
}
}
.fixedSize()
}
}

func randomString(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)
}

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
}

struct SignInWithApple_PreviewProvider: PreviewProvider {
static var previews: some View {
SignInWithAppleView()
}
}
1 change: 1 addition & 0 deletions Sources/GoTrue/GoTrueClient.swift
Original file line number Diff line number Diff line change
Expand Up @@ -167,6 +167,7 @@ public final class GoTrueClient {

/// Allows signing in with an ID token issued by certain supported providers.
/// The ID token is verified for validity and a new session is established.
@_spi(Experimental)

This comment has been minimized.

Copy link
@workbytaylor

workbytaylor Aug 2, 2023

Hi Guilherme, marking this as experimental unfortunately broke my app. I created a pull request that removes this line - any chance you can approve this quickly? Thanks from Canada!

@discardableResult
public func signInWithIdToken(credentials: OpenIDConnectCredentials) async throws -> Session {
try await _signIn(
Expand Down
2 changes: 1 addition & 1 deletion Tests/GoTrueTests/GoTrueTests.swift
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import Mocker
import XCTest

@testable import GoTrue
@testable @_spi(Experimental) import GoTrue

final class InMemoryLocalStorage: GoTrueLocalStorage, @unchecked Sendable {
private let queue = DispatchQueue(label: "InMemoryLocalStorage")
Expand Down

0 comments on commit 7e68cae

Please sign in to comment.