RLMSyncUser.h 23 KB

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