-
Notifications
You must be signed in to change notification settings - Fork 327
/
Copy pathAccountManager.swift
182 lines (148 loc) · 8.94 KB
/
AccountManager.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
import AuthenticationServices
import Foundation
import os
import ExpoModulesCore
@available(iOS 15.0, *)
struct AuthorizationResponse {
var registration: ASAuthorizationPlatformPublicKeyCredentialRegistration?
var assertion: ASAuthorizationPlatformPublicKeyCredentialAssertion?
}
@available(iOS 15.0, *)
class AccountManager: NSObject, ASAuthorizationControllerPresentationContextProviding, ASAuthorizationControllerDelegate {
private var authCallback: ((AuthorizationResponse?,ASAuthorizationError.Code?) -> Void)?
var authController: ASAuthorizationController?
func createPasskey(challengeBase64: String, rpId: String, displayName: String, userIdBase64: String, promise: Promise) {
let publicKeyCredentialProvider = ASAuthorizationPlatformPublicKeyCredentialProvider(relyingPartyIdentifier: rpId)
let challenge = dataFromBase64URL(base64urlString: challengeBase64)!
let userId = dataFromBase64URL(base64urlString: userIdBase64)!
let registrationRequest = publicKeyCredentialProvider.createCredentialRegistrationRequest(challenge: challenge,
name: displayName, userID: userId)
let authController = ASAuthorizationController(authorizationRequests: [ registrationRequest ] )
authController.delegate = self
authController.presentationContextProvider = self
authController.performRequests()
self.authCallback = { result,error in
if (error != nil) {
promise.reject(String(error!.rawValue), handleAuthorizationError(error!).rawValue)
return
}
if let response = result?.registration {
let authResult: NSDictionary = [
"id": base64URLFromBase64(base64String: response.credentialID.base64EncodedString()),
"rawId": base64URLFromBase64(base64String: response.credentialID.base64EncodedString()),
"type": "public-key",
"response": [
"attestationObject": base64URLFromBase64(base64String: response.rawAttestationObject!.base64EncodedString()),
"clientDataJSON": base64URLFromBase64(base64String: response.rawClientDataJSON.base64EncodedString())
]
]
promise.resolve(authResult);
} else {
promise.reject(Errors.notHandled.rawValue, "Not valid registration result");
}
}
}
func getPasskey(challengeBase64URL: String, rpId: String, promise: Promise) {
let publicKeyCredentialProvider = ASAuthorizationPlatformPublicKeyCredentialProvider(relyingPartyIdentifier: rpId)
let challenge = dataFromBase64URL(base64urlString: challengeBase64URL)!
let assertionRequest = publicKeyCredentialProvider.createCredentialAssertionRequest(challenge: challenge)
let authController = ASAuthorizationController(authorizationRequests: [ assertionRequest ] )
authController.delegate = self
authController.presentationContextProvider = self
authController.performRequests()
self.authCallback = { result,error in
if (error != nil) {
promise.reject(String(error!.rawValue), handleAuthorizationError(error!).rawValue);
return
}
if let response = result?.assertion {
let authResult: NSDictionary = [
"id": base64URLFromBase64(base64String: response.credentialID.base64EncodedString()),
"rawId": base64URLFromBase64(base64String: response.credentialID.base64EncodedString()),
"type":"public-key",
"response": [
"authenticatorData":base64URLFromBase64(base64String: response.rawAuthenticatorData.base64EncodedString()),
"clientDataJSON": base64URLFromBase64(base64String: response.rawClientDataJSON.base64EncodedString()),
"signature": base64URLFromBase64(base64String: response.signature.base64EncodedString()),
"userHandle": base64URLFromBase64(base64String: response.userID.base64EncodedString()),
] ]
promise.resolve(authResult);
} else {
promise.reject("Response is invalid", "Could not retrieve passkey");
}
}
}
@available(iOS 16.0, *)
func beginAutoFillAssistedPasskeySignIn(challengeBase64URL: String, rpId: String, promise: Promise) {
let publicKeyCredentialProvider = ASAuthorizationPlatformPublicKeyCredentialProvider(relyingPartyIdentifier: rpId)
let challenge = dataFromBase64URL(base64urlString: challengeBase64URL)!
let assertionRequest = publicKeyCredentialProvider.createCredentialAssertionRequest(challenge: challenge)
let authController = ASAuthorizationController(authorizationRequests: [ assertionRequest ] )
authController.delegate = self
authController.presentationContextProvider = self
authController.performAutoFillAssistedRequests()
self.authCallback = { result,error in
if (error != nil) {
promise.reject(String(error!.rawValue), handleAuthorizationError(error!).rawValue);
return
}
if let response = result?.assertion {
let authResult: NSDictionary = [
"id": base64URLFromBase64(base64String: response.credentialID.base64EncodedString()),
"rawId": base64URLFromBase64(base64String: response.credentialID.base64EncodedString()),
"type":"public-key",
"response": [
"authenticatorData":base64URLFromBase64(base64String: response.rawAuthenticatorData.base64EncodedString()),
"clientDataJSON": base64URLFromBase64(base64String: response.rawClientDataJSON.base64EncodedString()),
"signature": base64URLFromBase64(base64String: response.signature.base64EncodedString()),
"userHandle": base64URLFromBase64(base64String: response.userID.base64EncodedString()),
] ]
promise.resolve(authResult);
} else {
promise.reject("Response is invalid", "Could not retrieve passkey");
}
}
}
@available(iOS 16.0, *)
func cancelAutoFillAssistedPasskeySignIn() {
if authController != nil {
self.authController?.cancel()
self.authController = nil
}
}
func authorizationController(controller: ASAuthorizationController, didCompleteWithAuthorization authorization: ASAuthorization) {
let logger = Logger()
switch authorization.credential {
case let credentialRegistration as ASAuthorizationPlatformPublicKeyCredentialRegistration:
self.authCallback!(AuthorizationResponse(registration: credentialRegistration),nil)
logger.log("A new passkey was registered: \(credentialRegistration)")
case let credentialAssertion as ASAuthorizationPlatformPublicKeyCredentialAssertion:
self.authCallback!(AuthorizationResponse(assertion: credentialAssertion),nil)
logger.log("A passkey was used to sign in: \(credentialAssertion)")
default:
self.authCallback!(AuthorizationResponse(registration: nil), ASAuthorizationError.unknown)
}
}
func authorizationController(controller: ASAuthorizationController, didCompleteWithError error: Error) {
let logger = Logger()
guard let authorizationError = error as? ASAuthorizationError else {
self.authCallback!(AuthorizationResponse(registration: nil), ASAuthorizationError.unknown)
logger.error("Unexpected authorization error: \(error.localizedDescription)")
return
}
if authorizationError.code == .canceled {
// Either the system doesn't find any credentials and the request ends silently, or the user cancels the request.
// This is a good time to show a traditional login form, or ask the user to create an account.
self.authCallback!(AuthorizationResponse(registration: nil),ASAuthorizationError.canceled)
logger.log("Request canceled.")
} else {
// Another ASAuthorization error.
// Note: The userInfo dictionary contains useful information.
self.authCallback!(AuthorizationResponse(registration: nil),ASAuthorizationError.unknown)
logger.error("Error: \((error as NSError).userInfo)")
}
}
func presentationAnchor(for controller: ASAuthorizationController) -> ASPresentationAnchor {
return UIApplication.shared.keyWindow!;
}
}