RLMSyncUser.h 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377
  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. #pragma mark - Administrator
  177. /**
  178. Given a Realm Object Server authentication provider and a provider identifier for a user
  179. (for example, a username), look up and return user information for that user.
  180. @param providerUserIdentity The username or identity of the user as issued by the authentication provider.
  181. In most cases this is different from the Realm Object Server-issued identity.
  182. @param provider The authentication provider that manages the user whose information is desired.
  183. @param completion Completion block invoked when request has completed or failed.
  184. The callback will be invoked on a background queue provided
  185. by `NSURLSession`.
  186. */
  187. - (void)retrieveInfoForUser:(NSString *)providerUserIdentity
  188. identityProvider:(RLMIdentityProvider)provider
  189. completion:(RLMRetrieveUserBlock)completion;
  190. #pragma mark - Permissions
  191. /**
  192. Asynchronously retrieve all permissions associated with the user calling this method.
  193. The results will be returned through the callback block, or an error if the operation failed.
  194. The callback block will be run on the same thread the method was called on.
  195. @warning This method must be called from a thread with a currently active run loop. Unless
  196. you have manually configured a run loop on a side thread, this will usually be the
  197. main thread.
  198. */
  199. - (void)retrievePermissionsWithCallback:(RLMPermissionResultsBlock)callback NS_REFINED_FOR_SWIFT;
  200. /**
  201. Apply a given permission.
  202. The operation will take place asynchronously, and the callback will be used to report whether
  203. the permission change succeeded or failed. The user calling this method must have the right
  204. to grant the given permission, or else the operation will fail.
  205. @see `RLMSyncPermission`
  206. */
  207. - (void)applyPermission:(RLMSyncPermission *)permission callback:(RLMPermissionStatusBlock)callback;
  208. /**
  209. Revoke a given permission.
  210. The operation will take place asynchronously, and the callback will be used to report whether
  211. the permission change succeeded or failed. The user calling this method must have the right
  212. to grant the given permission, or else the operation will fail.
  213. @see `RLMSyncPermission`
  214. */
  215. - (void)revokePermission:(RLMSyncPermission *)permission callback:(RLMPermissionStatusBlock)callback;
  216. /**
  217. Create a permission offer for a Realm.
  218. A permission offer is used to grant access to a Realm this user manages to another
  219. user. Creating a permission offer produces a string token which can be passed to the
  220. recepient in any suitable way (for example, via e-mail).
  221. The operation will take place asynchronously. The token can be accepted by the recepient
  222. using the `-[RLMSyncUser acceptOfferForToken:callback:]` method.
  223. @param url The URL of the Realm for which the permission offer should pertain. This
  224. may be the URL of any Realm which this user is allowed to manage. If the URL
  225. has a `~` wildcard it will be replaced with this user's user identity.
  226. @param accessLevel What access level to grant to whoever accepts the token.
  227. @param expirationDate Optionally, a date which indicates when the offer expires. If the
  228. recepient attempts to accept the offer after the date it will be rejected.
  229. @param callback A callback indicating whether the operation succeeded or failed. If it
  230. succeeded the token will be passed in as a string.
  231. @see `acceptOfferForToken:callback:`
  232. */
  233. - (void)createOfferForRealmAtURL:(NSURL *)url
  234. accessLevel:(RLMSyncAccessLevel)accessLevel
  235. expiration:(nullable NSDate *)expirationDate
  236. callback:(RLMPermissionOfferStatusBlock)callback NS_REFINED_FOR_SWIFT;
  237. /**
  238. Accept a permission offer.
  239. Pass in a token representing a permission offer. The operation will take place asynchronously.
  240. If the operation succeeds, the callback will be passed the URL of the Realm for which the
  241. offer applied, so the Realm can be opened.
  242. The token this method accepts can be created by the offering user through the
  243. `-[RLMSyncUser createOfferForRealmAtURL:accessLevel:expiration:callback:]` method.
  244. @see `createOfferForRealmAtURL:accessLevel:expiration:callback:`
  245. */
  246. - (void)acceptOfferForToken:(NSString *)token
  247. callback:(RLMPermissionOfferResponseStatusBlock)callback;
  248. /// :nodoc:
  249. - (instancetype)init __attribute__((unavailable("RLMSyncUser cannot be created directly")));
  250. /// :nodoc:
  251. + (instancetype)new __attribute__((unavailable("RLMSyncUser cannot be created directly")));
  252. @end
  253. #pragma mark - User info classes
  254. /**
  255. A data object representing a user account associated with a user.
  256. @see `RLMSyncUserInfo`
  257. */
  258. @interface RLMSyncUserAccountInfo : NSObject
  259. /// The authentication provider which manages this user account.
  260. @property (nonatomic, readonly) RLMIdentityProvider provider;
  261. /// The username or identity of this user account.
  262. @property (nonatomic, readonly) NSString *providerUserIdentity;
  263. /// :nodoc:
  264. - (instancetype)init __attribute__((unavailable("RLMSyncUserAccountInfo cannot be created directly")));
  265. /// :nodoc:
  266. + (instancetype)new __attribute__((unavailable("RLMSyncUserAccountInfo cannot be created directly")));
  267. @end
  268. /**
  269. A data object representing information about a user that was retrieved from a user lookup call.
  270. */
  271. @interface RLMSyncUserInfo : NSObject
  272. /**
  273. An array of all the user accounts associated with this user.
  274. */
  275. @property (nonatomic, readonly) NSArray<RLMSyncUserAccountInfo *> *accounts;
  276. /**
  277. The identity issued to this user by the Realm Object Server.
  278. */
  279. @property (nonatomic, readonly) NSString *identity;
  280. /**
  281. Metadata about this user stored on the Realm Object Server.
  282. */
  283. @property (nonatomic, readonly) NSDictionary<NSString *, NSString *> *metadata;
  284. /**
  285. Whether the user is flagged on the Realm Object Server as an administrator.
  286. */
  287. @property (nonatomic, readonly) BOOL isAdmin;
  288. /// :nodoc:
  289. - (instancetype)init __attribute__((unavailable("RLMSyncUserInfo cannot be created directly")));
  290. /// :nodoc:
  291. + (instancetype)new __attribute__((unavailable("RLMSyncUserInfo cannot be created directly")));
  292. @end
  293. NS_ASSUME_NONNULL_END