RLMSyncUser.h 19 KB

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