RLMSyncUser.h 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518
  1. ////////////////////////////////////////////////////////////////////////////
  2. //
  3. // Copyright 2016 Realm Inc.
  4. //
  5. // Licensed under the Apache License, Version 2.0 (the "License");
  6. // you may not use this file except in compliance with the License.
  7. // You may obtain a copy of the License at
  8. //
  9. // http://www.apache.org/licenses/LICENSE-2.0
  10. //
  11. // Unless required by applicable law or agreed to in writing, software
  12. // distributed under the License is distributed on an "AS IS" BASIS,
  13. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. // See the License for the specific language governing permissions and
  15. // limitations under the License.
  16. //
  17. ////////////////////////////////////////////////////////////////////////////
  18. #import <Foundation/Foundation.h>
  19. #import "RLMRealmConfiguration.h"
  20. #import "RLMResults.h"
  21. #import "RLMSyncCredentials.h"
  22. #import "RLMSyncPermission.h"
  23. @class RLMSyncUser, RLMSyncUserInfo, RLMSyncCredentials, RLMSyncPermission, RLMSyncSession, RLMRealm;
  24. /**
  25. The state of the user object.
  26. */
  27. typedef NS_ENUM(NSUInteger, RLMSyncUserState) {
  28. /// The user is logged out. Call `logInWithCredentials:...` with valid credentials to log the user back in.
  29. RLMSyncUserStateLoggedOut,
  30. /// The user is logged in, and any Realms associated with it are syncing with the Realm Object Server.
  31. RLMSyncUserStateActive,
  32. /// The user has encountered a fatal error state, and cannot be used.
  33. RLMSyncUserStateError,
  34. };
  35. /// A block type used for APIs which asynchronously vend an `RLMSyncUser`.
  36. typedef void(^RLMUserCompletionBlock)(RLMSyncUser * _Nullable, NSError * _Nullable);
  37. /// A block type used to report the status of a password change operation.
  38. /// If the `NSError` argument is nil, the operation succeeded.
  39. typedef void(^RLMPasswordChangeStatusBlock)(NSError * _Nullable);
  40. /// A block type used to report the status of a permission apply or revoke operation.
  41. /// If the `NSError` argument is nil, the operation succeeded.
  42. typedef void(^RLMPermissionStatusBlock)(NSError * _Nullable);
  43. /// A block type used to report the status of a permission offer operation.
  44. typedef void(^RLMPermissionOfferStatusBlock)(NSString * _Nullable, NSError * _Nullable);
  45. /// A block type used to report the status of a permission offer response operation.
  46. typedef void(^RLMPermissionOfferResponseStatusBlock)(NSURL * _Nullable, NSError * _Nullable);
  47. /// A block type used to asynchronously report results of a permissions get operation.
  48. /// Exactly one of the two arguments will be populated.
  49. typedef void(^RLMPermissionResultsBlock)(RLMResults<RLMSyncPermission *> * _Nullable, NSError * _Nullable);
  50. /// A block type used to asynchronously report results of a user info retrieval.
  51. /// Exactly one of the two arguments will be populated.
  52. typedef void(^RLMRetrieveUserBlock)(RLMSyncUserInfo * _Nullable, NSError * _Nullable);
  53. /// A block type used to report an error related to a specific user.
  54. typedef void(^RLMUserErrorReportingBlock)(RLMSyncUser * _Nonnull, NSError * _Nonnull);
  55. NS_ASSUME_NONNULL_BEGIN
  56. /**
  57. A `RLMSyncUser` instance represents a single Realm Object Server user account.
  58. A user may have one or more credentials associated with it. These credentials
  59. uniquely identify the user to the authentication provider, and are used to sign
  60. into a Realm Object Server user account.
  61. Note that user objects are only vended out via SDK APIs, and cannot be directly
  62. initialized. User objects can be accessed from any thread.
  63. */
  64. @interface RLMSyncUser : NSObject
  65. /**
  66. A dictionary of all valid, logged-in user identities corresponding to their user objects.
  67. */
  68. + (NSDictionary<NSString *, RLMSyncUser *> *)allUsers NS_REFINED_FOR_SWIFT;
  69. /**
  70. The logged-in user. `nil` if none exists.
  71. @warning Throws an exception if more than one logged-in user exists.
  72. */
  73. + (nullable RLMSyncUser *)currentUser NS_REFINED_FOR_SWIFT;
  74. /**
  75. The unique Realm Object Server user ID string identifying this user.
  76. */
  77. @property (nullable, nonatomic, readonly) NSString *identity;
  78. /**
  79. The URL of the authentication server this user will communicate with.
  80. */
  81. @property (nullable, nonatomic, readonly) NSURL *authenticationServer;
  82. /**
  83. Whether the user is a Realm Object Server administrator. Value reflects the
  84. state at the time of the last successful login of this user.
  85. */
  86. @property (nonatomic, readonly) BOOL isAdmin;
  87. /**
  88. The current state of the user.
  89. */
  90. @property (nonatomic, readonly) RLMSyncUserState state;
  91. #pragma mark - Lifecycle
  92. /**
  93. Create, log in, and asynchronously return a new user object, specifying a custom
  94. timeout for the network request and a custom queue to run the callback upon.
  95. Credentials identifying the user must be passed in. The user becomes available in
  96. the completion block, at which point it is ready for use.
  97. */
  98. + (void)logInWithCredentials:(RLMSyncCredentials *)credentials
  99. authServerURL:(NSURL *)authServerURL
  100. timeout:(NSTimeInterval)timeout
  101. callbackQueue:(dispatch_queue_t)callbackQueue
  102. onCompletion:(RLMUserCompletionBlock)completion NS_REFINED_FOR_SWIFT;
  103. /**
  104. Create, log in, and asynchronously return a new user object.
  105. If the login completes successfully, the completion block will invoked with
  106. a `RLMSyncUser` object representing the logged-in user. This object can be
  107. used to open synchronized Realms. If the login fails, the completion block
  108. will be invoked with an error.
  109. The completion block always runs on the main queue.
  110. @param credentials A credentials value identifying the user to be logged in.
  111. @param authServerURL The URL of the authentication server (e.g. "http://realm.example.org:9080").
  112. @param completion A callback block that returns a user object or an error,
  113. indicating the completion of the login operation.
  114. */
  115. + (void)logInWithCredentials:(RLMSyncCredentials *)credentials
  116. authServerURL:(NSURL *)authServerURL
  117. onCompletion:(RLMUserCompletionBlock)completion
  118. NS_SWIFT_UNAVAILABLE("Use the full version of this API.");
  119. /**
  120. Returns the default configuration for the user. The default configuration
  121. points to the default query-based Realm on the server the user authenticated against.
  122. */
  123. - (RLMRealmConfiguration *)configuration NS_REFINED_FOR_SWIFT;
  124. /**
  125. Create a query-based configuration instance for the given url.
  126. @param url The unresolved absolute URL to the Realm on the Realm Object Server,
  127. e.g. "realm://example.org/~/path/to/realm". "Unresolved" means the
  128. path should contain the wildcard marker `~`, which will automatically
  129. be filled in with the user identity by the Realm Object Server.
  130. @return A default configuration object with the sync configuration set to use the given URL.
  131. */
  132. - (RLMRealmConfiguration *)configurationWithURL:(nullable NSURL *)url NS_REFINED_FOR_SWIFT;
  133. /**
  134. Create a configuration instance for the given url.
  135. @param url The unresolved absolute URL to the Realm on the Realm Object Server,
  136. e.g. "realm://example.org/~/path/to/realm". "Unresolved" means the
  137. path should contain the wildcard marker `~`, which will automatically
  138. be filled in with the user identity by the Realm Object Server.
  139. @param fullSynchronization If YES, all objects in the server Realm are
  140. automatically synchronized, and the query subscription
  141. methods cannot be used.
  142. @return A default configuration object with the sync configuration set to use
  143. the given URL and options.
  144. */
  145. - (RLMRealmConfiguration *)configurationWithURL:(nullable NSURL *)url
  146. fullSynchronization:(bool)fullSynchronization NS_REFINED_FOR_SWIFT;
  147. /**
  148. Create a configuration instance for the given url.
  149. @param url The unresolved absolute URL to the Realm on the Realm Object Server,
  150. e.g. "realm://example.org/~/path/to/realm". "Unresolved" means the
  151. path should contain the wildcard marker `~`, which will automatically
  152. be filled in with the user identity by the Realm Object Server.
  153. @param fullSynchronization If YES, all objects in the server Realm are
  154. automatically synchronized, and the query subscription
  155. methods cannot be used.
  156. @param enableSSLValidation If NO, invalid SSL certificates for the server will
  157. not be rejected. THIS SHOULD NEVER BE USED IN
  158. PRODUCTION AND EXISTS ONLY FOR TESTING PURPOSES.
  159. @param urlPrefix A prefix which is prepending to URLs constructed for
  160. the server. This should normally be `nil`, and customized only
  161. to match corresponding settings on the server.
  162. @return A default configuration object with the sync configuration set to use
  163. the given URL and options.
  164. */
  165. - (RLMRealmConfiguration *)configurationWithURL:(nullable NSURL *)url
  166. fullSynchronization:(bool)fullSynchronization
  167. enableSSLValidation:(bool)enableSSLValidation
  168. urlPrefix:(nullable NSString *)urlPrefix NS_REFINED_FOR_SWIFT;
  169. /**
  170. Log a user out, destroying their server state, unregistering them from the SDK,
  171. and removing any synced Realms associated with them from on-disk storage on
  172. next app launch. If the user is already logged out or in an error state, this
  173. method does nothing.
  174. This method should be called whenever the application is committed to not using
  175. a user again unless they are recreated.
  176. Failing to call this method may result in unused files and metadata needlessly
  177. taking up space.
  178. */
  179. - (void)logOut;
  180. /**
  181. An optional error handler which can be set to notify the host application when
  182. the user encounters an error. Errors reported by this error handler are always
  183. `RLMSyncAuthError`s.
  184. @note Check for `RLMSyncAuthErrorInvalidAccessToken` to see if the user has
  185. been remotely logged out because its refresh token expired, or because the
  186. third party authentication service providing the user's identity has
  187. logged the user out.
  188. @warning Regardless of whether an error handler is installed, certain user errors
  189. will automatically cause the user to enter the logged out state.
  190. */
  191. @property (nullable, nonatomic) RLMUserErrorReportingBlock errorHandler NS_REFINED_FOR_SWIFT;
  192. #pragma mark - Sessions
  193. /**
  194. Retrieve a valid session object belonging to this user for a given URL, or `nil`
  195. if no such object exists.
  196. */
  197. - (nullable RLMSyncSession *)sessionForURL:(NSURL *)url;
  198. /**
  199. Retrieve all the valid sessions belonging to this user.
  200. */
  201. - (NSArray<RLMSyncSession *> *)allSessions;
  202. #pragma mark - Passwords
  203. /**
  204. Change this user's password asynchronously.
  205. @warning Changing a user's password using an authentication server that doesn't
  206. use HTTPS is a major security flaw, and should only be done while
  207. testing.
  208. @param newPassword The user's new password.
  209. @param completion Completion block invoked when login has completed or failed.
  210. The callback will be invoked on a background queue provided
  211. by `NSURLSession`.
  212. */
  213. - (void)changePassword:(NSString *)newPassword completion:(RLMPasswordChangeStatusBlock)completion;
  214. /**
  215. Change an arbitrary user's password asynchronously.
  216. @note The current user must be an admin user for this operation to succeed.
  217. @warning Changing a user's password using an authentication server that doesn't
  218. use HTTPS is a major security flaw, and should only be done while
  219. testing.
  220. @param newPassword The user's new password.
  221. @param userID The identity of the user whose password should be changed.
  222. @param completion Completion block invoked when login has completed or failed.
  223. The callback will be invoked on a background queue provided
  224. by `NSURLSession`.
  225. */
  226. - (void)changePassword:(NSString *)newPassword forUserID:(NSString *)userID completion:(RLMPasswordChangeStatusBlock)completion;
  227. /**
  228. Ask the server to send a password reset email to the given email address.
  229. If `email` is an email address which is associated with a user account that was
  230. registered using the "password" authentication service, the server will send an
  231. email to that address with a password reset token. No error is reported if the
  232. email address is invalid or not associated with an account.
  233. @param serverURL The authentication server URL for the user.
  234. @param email The email address to send the email to.
  235. @param completion A block which will be called when the request completes or
  236. fails. The callback will be invoked on a background queue
  237. provided by `NSURLSession`, and not on the calling queue.
  238. */
  239. + (void)requestPasswordResetForAuthServer:(NSURL *)serverURL
  240. userEmail:(NSString *)email
  241. completion:(RLMPasswordChangeStatusBlock)completion;
  242. /**
  243. Change a user's password using a one-time password reset token.
  244. By default, the password reset email sent by ROS will link to a web site where
  245. the user can select a new password, and the app will not need to call this
  246. method. If you wish to instead handle this within your native app, you must
  247. change the `baseURL` in the server configuration for `PasswordAuthProvider` to
  248. a scheme registered for your app, extract the token from the URL, and call this
  249. method after prompting the user for a new password.
  250. @warning Changing a user's password using an authentication server that doesn't
  251. use HTTPS is a major security flaw, and should only be done while
  252. testing.
  253. @param serverURL The authentication server URL for the user.
  254. @param token The one-time use token from the URL.
  255. @param newPassword The user's new password.
  256. @param completion A block which will be called when the request completes or
  257. fails. The callback will be invoked on a background queue
  258. provided by `NSURLSession`, and not on the calling queue.
  259. */
  260. + (void)completePasswordResetForAuthServer:(NSURL *)serverURL
  261. token:(NSString *)token
  262. password:(NSString *)newPassword
  263. completion:(RLMPasswordChangeStatusBlock)completion;
  264. /**
  265. Ask the server to send a confirmation email to the given email address.
  266. If `email` is an email address which is associated with a user account that was
  267. registered using the "password" authentication service, the server will send an
  268. email to that address with a confirmation token. No error is reported if the
  269. email address is invalid or not associated with an account.
  270. @param serverURL The authentication server URL for the user.
  271. @param email The email address to send the email to.
  272. @param completion A block which will be called when the request completes or
  273. fails. The callback will be invoked on a background queue
  274. provided by `NSURLSession`, and not on the calling queue.
  275. */
  276. + (void)requestEmailConfirmationForAuthServer:(NSURL *)serverURL
  277. userEmail:(NSString *)email
  278. completion:(RLMPasswordChangeStatusBlock)completion;
  279. /**
  280. Confirm a user's email using a one-time confirmation token.
  281. By default, the confirmation email sent by ROS will link to a web site with
  282. a generic "thank you for confirming your email" message, and the app will not
  283. need to call this method. If you wish to instead handle this within your native
  284. app, you must change the `baseURL` in the server configuration for
  285. `PasswordAuthProvider` to a scheme registered for your app, extract the token
  286. from the URL, and call this method.
  287. @param serverURL The authentication server URL for the user.
  288. @param token The one-time use token from the URL.
  289. @param completion A block which will be called when the request completes or
  290. fails. The callback will be invoked on a background queue
  291. provided by `NSURLSession`, and not on the calling queue.
  292. */
  293. + (void)confirmEmailForAuthServer:(NSURL *)serverURL
  294. token:(NSString *)token
  295. completion:(RLMPasswordChangeStatusBlock)completion;
  296. #pragma mark - Administrator
  297. /**
  298. Given a Realm Object Server authentication provider and a provider identifier for a user
  299. (for example, a username), look up and return user information for that user.
  300. @param providerUserIdentity The username or identity of the user as issued by the authentication provider.
  301. In most cases this is different from the Realm Object Server-issued identity.
  302. @param provider The authentication provider that manages the user whose information is desired.
  303. @param completion Completion block invoked when request has completed or failed.
  304. The callback will be invoked on a background queue provided
  305. by `NSURLSession`.
  306. */
  307. - (void)retrieveInfoForUser:(NSString *)providerUserIdentity
  308. identityProvider:(RLMIdentityProvider)provider
  309. completion:(RLMRetrieveUserBlock)completion;
  310. #pragma mark - Permissions
  311. /**
  312. Asynchronously retrieve all permissions associated with the user calling this method.
  313. The results will be returned through the callback block, or an error if the operation failed.
  314. The callback block will be run on the same thread the method was called on.
  315. @warning This method must be called from a thread with a currently active run loop. Unless
  316. you have manually configured a run loop on a side thread, this will usually be the
  317. main thread.
  318. */
  319. - (void)retrievePermissionsWithCallback:(RLMPermissionResultsBlock)callback NS_REFINED_FOR_SWIFT;
  320. /**
  321. Apply a given permission.
  322. The operation will take place asynchronously, and the callback will be used to report whether
  323. the permission change succeeded or failed. The user calling this method must have the right
  324. to grant the given permission, or else the operation will fail.
  325. @see `RLMSyncPermission`
  326. */
  327. - (void)applyPermission:(RLMSyncPermission *)permission callback:(RLMPermissionStatusBlock)callback;
  328. /**
  329. Revoke a given permission.
  330. The operation will take place asynchronously, and the callback will be used to report whether
  331. the permission change succeeded or failed. The user calling this method must have the right
  332. to grant the given permission, or else the operation will fail.
  333. @see `RLMSyncPermission`
  334. */
  335. - (void)revokePermission:(RLMSyncPermission *)permission callback:(RLMPermissionStatusBlock)callback;
  336. /**
  337. Create a permission offer for a Realm.
  338. A permission offer is used to grant access to a Realm this user manages to another
  339. user. Creating a permission offer produces a string token which can be passed to the
  340. recepient in any suitable way (for example, via e-mail).
  341. The operation will take place asynchronously. The token can be accepted by the recepient
  342. using the `-[RLMSyncUser acceptOfferForToken:callback:]` method.
  343. @param url The URL of the Realm for which the permission offer should pertain. This
  344. may be the URL of any Realm which this user is allowed to manage. If the URL
  345. has a `~` wildcard it will be replaced with this user's user identity.
  346. @param accessLevel What access level to grant to whoever accepts the token.
  347. @param expirationDate Optionally, a date which indicates when the offer expires. If the
  348. recepient attempts to accept the offer after the date it will be rejected.
  349. @param callback A callback indicating whether the operation succeeded or failed. If it
  350. succeeded the token will be passed in as a string.
  351. @see `acceptOfferForToken:callback:`
  352. */
  353. - (void)createOfferForRealmAtURL:(NSURL *)url
  354. accessLevel:(RLMSyncAccessLevel)accessLevel
  355. expiration:(nullable NSDate *)expirationDate
  356. callback:(RLMPermissionOfferStatusBlock)callback NS_REFINED_FOR_SWIFT;
  357. /**
  358. Accept a permission offer.
  359. Pass in a token representing a permission offer. The operation will take place asynchronously.
  360. If the operation succeeds, the callback will be passed the URL of the Realm for which the
  361. offer applied, so the Realm can be opened.
  362. The token this method accepts can be created by the offering user through the
  363. `-[RLMSyncUser createOfferForRealmAtURL:accessLevel:expiration:callback:]` method.
  364. @see `createOfferForRealmAtURL:accessLevel:expiration:callback:`
  365. */
  366. - (void)acceptOfferForToken:(NSString *)token
  367. callback:(RLMPermissionOfferResponseStatusBlock)callback;
  368. /// :nodoc:
  369. - (instancetype)init __attribute__((unavailable("RLMSyncUser cannot be created directly")));
  370. /// :nodoc:
  371. + (instancetype)new __attribute__((unavailable("RLMSyncUser cannot be created directly")));
  372. @end
  373. #pragma mark - User info classes
  374. /**
  375. A data object representing a user account associated with a user.
  376. @see `RLMSyncUserInfo`
  377. */
  378. @interface RLMSyncUserAccountInfo : NSObject
  379. /// The authentication provider which manages this user account.
  380. @property (nonatomic, readonly) RLMIdentityProvider provider;
  381. /// The username or identity of this user account.
  382. @property (nonatomic, readonly) NSString *providerUserIdentity;
  383. /// :nodoc:
  384. - (instancetype)init __attribute__((unavailable("RLMSyncUserAccountInfo cannot be created directly")));
  385. /// :nodoc:
  386. + (instancetype)new __attribute__((unavailable("RLMSyncUserAccountInfo cannot be created directly")));
  387. @end
  388. /**
  389. A data object representing information about a user that was retrieved from a user lookup call.
  390. */
  391. @interface RLMSyncUserInfo : NSObject
  392. /**
  393. An array of all the user accounts associated with this user.
  394. */
  395. @property (nonatomic, readonly) NSArray<RLMSyncUserAccountInfo *> *accounts;
  396. /**
  397. The identity issued to this user by the Realm Object Server.
  398. */
  399. @property (nonatomic, readonly) NSString *identity;
  400. /**
  401. Metadata about this user stored on the Realm Object Server.
  402. */
  403. @property (nonatomic, readonly) NSDictionary<NSString *, NSString *> *metadata;
  404. /**
  405. Whether the user is flagged on the Realm Object Server as an administrator.
  406. */
  407. @property (nonatomic, readonly) BOOL isAdmin;
  408. /// :nodoc:
  409. - (instancetype)init __attribute__((unavailable("RLMSyncUserInfo cannot be created directly")));
  410. /// :nodoc:
  411. + (instancetype)new __attribute__((unavailable("RLMSyncUserInfo cannot be created directly")));
  412. @end
  413. NS_ASSUME_NONNULL_END