-
Notifications
You must be signed in to change notification settings - Fork 2.2k
/
Copy pathApp.swift
527 lines (466 loc) · 18.9 KB
/
App.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
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
////////////////////////////////////////////////////////////////////////////
//
// Copyright 2020 Realm Inc.
//
// 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 Combine
import Foundation
import Realm
import Realm.Private
/**
An object representing the Realm App configuration
- see: `RLMAppConfiguration`
*/
public typealias AppConfiguration = RLMAppConfiguration
/**
An object representing a client which performs network calls on
Realm Cloud user api keys
- see: `RLMAPIKeyAuth`
*/
public typealias APIKeyAuth = RLMAPIKeyAuth
/**
An object representing a client which performs network calls on
Realm Cloud user registration & password functions
- see: `RLMEmailPasswordAuth`
*/
public typealias EmailPasswordAuth = RLMEmailPasswordAuth
/**
An object representing the social profile of a User.
*/
public typealias UserProfile = RLMUserProfile
extension UserProfile {
/**
The metadata of the user.
The auth provider of the user is responsible for populating this `Document`.
*/
public var metadata: Document {
guard let rlmMetadata = self.__metadata as RLMBSON?,
let anyBSON = ObjectiveCSupport.convert(object: rlmMetadata),
case let .document(metadata) = anyBSON else {
return [:]
}
return metadata
}
}
/// A block type used to report an error
public typealias EmailPasswordAuthOptionalErrorBlock = RLMEmailPasswordAuthOptionalErrorBlock
extension EmailPasswordAuth {
/// Resets the password of an email identity using the
/// password reset function set up in the application.
/// - Parameters:
/// - email: The email address of the user.
/// - password: The desired new password.
/// - args: A list of arguments passed in as a BSON array.
/// - completion: A callback to be invoked once the call is complete.
public func callResetPasswordFunction(email: String,
password: String,
args: [AnyBSON],
_ completion: @escaping EmailPasswordAuthOptionalErrorBlock) {
let bson = ObjectiveCSupport.convert(object: .array(args))
__callResetPasswordFunction(email, password: password, args: bson as! [RLMBSON], completion: completion)
}
/**
Resets the password of an email identity using the
password reset function set up in the application.
@param email The email address of the user.
@param password The desired new password.
@param args A list of arguments passed in as a BSON array.
@returns A publisher that eventually return `Result.success` or `Error`.
*/
@available(macOS 10.15, watchOS 6.0, iOS 13.0, tvOS 13.0, *)
public func callResetPasswordFunction(email: String, password: String, args: [AnyBSON]) -> Future<Void, Error> {
promisify {
self.callResetPasswordFunction(email: email, password: password, args: args, $0)
}
}
/// Resets the password of an email identity using the
/// password reset function set up in the application.
/// - Parameters:
/// - email: The email address of the user.
/// - password: The desired new password.
/// - args: A list of arguments passed in as a BSON array.
@available(macOS 10.15, watchOS 6.0, iOS 13.0, tvOS 13.0, *)
public func callResetPasswordFunction(email: String,
password: String,
args: [AnyBSON]) async throws {
let bson = ObjectiveCSupport.convert(object: .array(args))
return try await __callResetPasswordFunction(email, password: password, args: bson as! [RLMBSON])
}
}
/**
An object representing a client which performs network calls on
Realm Cloud for registering devices to push notifications
- see `RLMPushClient`
*/
public typealias PushClient = RLMPushClient
/// An object which is used within UserAPIKeyProviderClient
public typealias UserAPIKey = RLMUserAPIKey
extension UserAPIKey {
/// The ObjectId of the API key.
public var objectId: ObjectId {
__objectId as! ObjectId
}
}
/**
`Credentials`is an enum representing supported authentication types for Atlas App Services.
Example Usage:
```
let credentials = Credentials.JWT(token: myToken)
```
*/
@frozen public enum Credentials: Sendable {
/// Credentials from a Facebook access token.
case facebook(accessToken: String)
/// Credentials from a Google serverAuthCode.
case google(serverAuthCode: String)
/// Credentials from a Google idToken.
case googleId(token: String)
/// Credentials from an Apple id token.
case apple(idToken: String)
/// Credentials from an email and password.
case emailPassword(email: String, password: String)
/// Credentials from a JSON Web Token
case jwt(token: String)
/// Credentials for an Atlas App Services function using a mongodb document as a json payload.
/// If the json can not be successfully serialised and error will be produced and the object will be nil.
case function(payload: Document)
/// Credentials from a user api key.
case userAPIKey(String)
/// Credentials from a sever api key.
case serverAPIKey(String)
/// Represents anonymous credentials
case anonymous
}
/// The `App` has the fundamental set of methods for communicating with a Realm
/// application backend.
/// This interface provides access to login and authentication.
public typealias App = RLMApp
public extension App {
/**
Login to a user for the Realm app.
- parameter credentials: The credentials identifying the user.
- parameter completion: A callback invoked after completion. Will return `Result.success(User)` or `Result.failure(Error)`.
*/
@preconcurrency
func login(credentials: Credentials, _ completion: @Sendable @escaping (Result<User, Error>) -> Void) {
self.__login(withCredential: ObjectiveCSupport.convert(object: credentials)) { user, error in
if let user = user {
completion(.success(user))
} else {
completion(.failure(error ?? Realm.Error.callFailed))
}
}
}
/// Login to a user for the Realm app.
/// @param credentials The credentials identifying the user.
/// @returns A publisher that eventually return `User` or `Error`.
@available(macOS 10.15, watchOS 6.0, iOS 13.0, tvOS 13.0, *)
func login(credentials: Credentials) -> Future<User, Error> {
return future { self.login(credentials: credentials, $0) }
}
/// Login to a user for the Realm app.
/// @param credentials The credentials identifying the user.
/// @returns A publisher that eventually return `User` or `Error`.
@available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *)
func login(credentials: Credentials) async throws -> User {
try await __login(withCredential: ObjectiveCSupport.convert(object: credentials))
}
}
/// Use this delegate to be provided a callback once authentication has succeed or failed
@available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *)
public typealias ASLoginDelegate = RLMASLoginDelegate
@available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *)
extension App {
/**
Sets the ASAuthorizationControllerDelegate to be handled by `App`
- Parameter controller: The ASAuthorizationController in which you want `App` to consume its delegate.
Usage:
```
let app = App(id: "my-app-id")
let appleIDProvider = ASAuthorizationAppleIDProvider()
let request = appleIDProvider.createRequest()
request.requestedScopes = [.fullName, .email]
let authorizationController = ASAuthorizationController(authorizationRequests: [request])
app.setASAuthorizationControllerDelegate(controller: authorizationController)
authorizationController.presentationContextProvider = self
authorizationController.performRequests()
```
*/
public func setASAuthorizationControllerDelegate(for controller: ASAuthorizationController) {
self.__setASAuthorizationControllerDelegateFor(controller)
}
}
/// :nodoc:
@available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *)
@frozen public struct AppSubscription: Subscription {
private let token: RLMAppSubscriptionToken
internal init(token: RLMAppSubscriptionToken) {
self.token = token
}
/// A unique identifier for identifying publisher streams.
public var combineIdentifier: CombineIdentifier {
return CombineIdentifier(token)
}
/// This function is not implemented.
///
/// Realm publishers do not support backpressure and so this function does nothing.
public func request(_ demand: Subscribers.Demand) {
}
/// Stop emitting values on this subscription.
public func cancel() {
token.unsubscribe()
}
}
/// :nodoc:
@available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *)
public struct AppPublisher: Publisher, @unchecked Sendable { // DispatchQueue
/// This publisher cannot fail.
public typealias Failure = Never
/// This publisher emits App.
public typealias Output = App
private let app: App
private let scheduler: any Scheduler
internal init<S: Scheduler>(_ app: App, scheduler: S) {
self.app = app
self.scheduler = scheduler
}
/// :nodoc:
public func receive<S: Sendable>(subscriber: S) where S: Subscriber, S.Failure == Never, Output == S.Input {
let token = app.subscribe { app in
self.scheduler.schedule {
_ = subscriber.receive(app)
}
}
subscriber.receive(subscription: AppSubscription(token: token))
}
/// :nodoc:
public func receive<S: Scheduler>(on scheduler: S) -> Self {
return Self(app, scheduler: scheduler)
}
}
@available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *)
extension App: ObservableObject {
/// A publisher that emits Void each time the app changes.
///
/// Despite the name, this actually emits *after* the app has changed.
public var objectWillChange: AppPublisher {
return AppPublisher(self, scheduler: DispatchQueue.main)
}
}
@available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *)
internal func promisify(_ fn: @escaping (@escaping @Sendable (Error?) -> Void) -> Void) -> Future<Void, Error> {
return future { promise in
fn { error in
if let error = error {
promise(.failure(error))
} else {
promise(.success(()))
}
}
}
}
@available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *)
public extension EmailPasswordAuth {
/**
Registers a new email identity with the username/password provider,
and sends a confirmation email to the provided address.
@param email The email address of the user to register.
@param password The password that the user created for the new username/password identity.
@returns A publisher that eventually return `Result.success` or `Error`.
*/
func registerUser(email: String, password: String) -> Future<Void, Error> {
promisify {
self.registerUser(email: email, password: password, completion: $0)
}
}
/**
Confirms an email identity with the username/password provider.
@param token The confirmation token that was emailed to the user.
@param tokenId The confirmation token id that was emailed to the user.
@returns A publisher that eventually return `Result.success` or `Error`.
*/
func confirmUser(_ token: String, tokenId: String) -> Future<Void, Error> {
promisify {
self.confirmUser(token, tokenId: tokenId, completion: $0)
}
}
/**
Re-sends a confirmation email to a user that has registered but
not yet confirmed their email address.
@param email The email address of the user to re-send a confirmation for.
@returns A publisher that eventually return `Result.success` or `Error`.
*/
func resendConfirmationEmail(email: String) -> Future<Void, Error> {
promisify {
self.resendConfirmationEmail(email, completion: $0)
}
}
/**
Retries custom confirmation function for a given email address.
@param email The email address of the user to retry custom confirmation logic.
@returns A publisher that eventually return `Result.success` or `Error`.
*/
func retryCustomConfirmation(email: String) -> Future<Void, Error> {
promisify {
self.retryCustomConfirmation(email, completion: $0)
}
}
/**
Sends a password reset email to the given email address.
@param email The email address of the user to send a password reset email for.
@returns A publisher that eventually return `Result.success` or `Error`.
*/
func sendResetPasswordEmail(email: String) -> Future<Void, Error> {
promisify {
self.sendResetPasswordEmail(email, completion: $0)
}
}
/**
Resets the password of an email identity using the
password reset token emailed to a user.
@param password The new password.
@param token The password reset token that was emailed to the user.
@param tokenId The password reset token id that was emailed to the user.
@returns A publisher that eventually return `Result.success` or `Error`.
*/
func resetPassword(to: String, token: String, tokenId: String) -> Future<Void, Error> {
promisify {
self.resetPassword(to: to, token: token, tokenId: tokenId, completion: $0)
}
}
}
@available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *)
public extension APIKeyAuth {
/**
Creates a user API key that can be used to authenticate as the current user.
@param name The name of the API key to be created.
@returns A publisher that eventually return `UserAPIKey` or `Error`.
*/
func createAPIKey(named: String) -> Future<UserAPIKey, Error> {
return future { self.createAPIKey(named: named, completion: $0) }
}
/**
Fetches a user API key associated with the current user.
@param objectId The ObjectId of the API key to fetch.
@returns A publisher that eventually return `UserAPIKey` or `Error`.
*/
func fetchAPIKey(_ objectId: ObjectId) -> Future<UserAPIKey, Error> {
return future { self.fetchAPIKey(objectId, $0) }
}
/**
Fetches the user API keys associated with the current user.
@returns A publisher that eventually return `[UserAPIKey]` or `Error`.
*/
func fetchAPIKeys() -> Future<[UserAPIKey], Error> {
return future { self.fetchAPIKeys($0) }
}
/**
Deletes a user API key associated with the current user.
@param objectId The ObjectId of the API key to delete.
@returns A publisher that eventually return `Result.success` or `Error`.
*/
func deleteAPIKey(_ objectId: ObjectId) -> Future<Void, Error> {
promisify {
self.deleteAPIKey(objectId, completion: $0)
}
}
/**
Enables a user API key associated with the current user.
@param objectId The ObjectId of the API key to enable.
@returns A publisher that eventually return `Result.success` or `Error`.
*/
func enableAPIKey(_ objectId: ObjectId) -> Future<Void, Error> {
promisify {
self.enableAPIKey(objectId, completion: $0)
}
}
/**
Disables a user API key associated with the current user.
@param objectId The ObjectId of the API key to disable.
@returns A publisher that eventually return `Result.success` or `Error`.
*/
func disableAPIKey(_ objectId: ObjectId) -> Future<Void, Error> {
promisify {
self.disableAPIKey(objectId, completion: $0)
}
}
}
@available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *)
public extension PushClient {
/// Request to register device token to the server
/// @param token device token
/// @param user - device's user
/// @returns A publisher that eventually return `Result.success` or `Error`.
func registerDevice(token: String, user: User) -> Future<Void, Error> {
promisify {
self.registerDevice(token: token, user: user, completion: $0)
}
}
/// Request to deregister a device for a user
/// @param user - devoce's user
/// @returns A publisher that eventually return `Result.success` or `Error`.
func deregisterDevice(user: User) -> Future<Void, Error> {
promisify {
self.deregisterDevice(user: user, completion: $0)
}
}
}
public extension APIKeyAuth {
/**
Creates a user API key that can be used to authenticate as the current user.
@param name The name of the API key to be created.
@completion A completion that eventually return `Result.success(UserAPIKey)` or `Result.failure(Error)`.
*/
@preconcurrency
func createAPIKey(named: String, completion: @escaping @Sendable (Result<UserAPIKey, Error>) -> Void) {
createAPIKey(named: named) { (userApiKey, error) in
if let userApiKey = userApiKey {
completion(.success(userApiKey))
} else {
completion(.failure(error ?? Realm.Error.callFailed))
}
}
}
/**
Fetches a user API key associated with the current user.
@param objectId The ObjectId of the API key to fetch.
@completion A completion that eventually return `Result.success(UserAPIKey)` or `Result.failure(Error)`.
*/
@preconcurrency
func fetchAPIKey(_ objectId: ObjectId, _ completion: @escaping @Sendable (Result<UserAPIKey, Error>) -> Void) {
fetchAPIKey(objectId) { (userApiKey, error) in
if let userApiKey = userApiKey {
completion(.success(userApiKey))
} else {
completion(.failure(error ?? Realm.Error.callFailed))
}
}
}
/**
Fetches the user API keys associated with the current user.
@completion A completion that eventually return `Result.success([UserAPIKey])` or `Result.failure(Error)`.
*/
@preconcurrency
func fetchAPIKeys(_ completion: @escaping @Sendable (Result<[UserAPIKey], Error>) -> Void) {
fetchAPIKeys { (userApiKeys, error) in
if let userApiKeys = userApiKeys {
completion(.success(userApiKeys))
} else {
completion(.failure(error ?? Realm.Error.callFailed))
}
}
}
}