Exemple #1
0
        /// <summary>
        /// Logs the user in to the Realm Object Server.
        /// </summary>
        /// <param name="credentials">The credentials to use for authentication.</param>
        /// <param name="serverUri">The URI of the server that the user is authenticated against.</param>
        /// <returns>An awaitable Task, that, upon completion, contains the logged in user.</returns>
        public static async Task <User> LoginAsync(Credentials credentials, Uri serverUri)
        {
            Argument.NotNull(credentials, nameof(credentials));
            Argument.NotNull(serverUri, nameof(serverUri));
            Argument.Ensure(serverUri.Scheme.StartsWith("http"), "Unexpected protocol for login url. Expected http:// or https://.", nameof(serverUri));

            SharedRealmHandleExtensions.DoInitialFileSystemConfiguration();

            if (credentials.IdentityProvider == Credentials.Provider.AdminToken)
            {
                return(new User(SyncUserHandle.GetAdminTokenUser(serverUri.AbsoluteUri, credentials.Token)));
            }

            if (credentials.IdentityProvider == Credentials.Provider.CustomRefreshToken)
            {
                var userId  = (string)credentials.UserInfo[Credentials.Keys.Identity];
                var isAdmin = (bool)credentials.UserInfo[Credentials.Keys.IsAdmin];
                return(new User(SyncUserHandle.GetSyncUser(userId, serverUri.AbsoluteUri, credentials.Token, isAdmin)));
            }

            var result = await AuthenticationHelper.LoginAsync(credentials, serverUri);

            var handle = SyncUserHandle.GetSyncUser(result.UserId, serverUri.AbsoluteUri, result.RefreshToken, result.IsAdmin);

            return(new User(handle));
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="SyncConfiguration"/> class.
        /// </summary>
        /// <param name="user">
        /// A valid <see cref="User"/>. If not provided, the currently logged-in user will be used.
        /// </param>
        /// <param name="serverUri">
        /// A unique <see cref="Uri"/> that identifies the Realm. In URIs, <c>~</c> can be used as a placeholder for a user Id.
        /// If a relative Uri is provided, it will be resolved using the user's <see cref="ServerUri"/> as baseUri.
        /// If <c>null</c> is passed, a Uri will be constructed from the user's <see cref="ServerUri"/>, combined with
        /// <c>/default</c> and <see cref="IsPartial"/> will be set to <c>true</c>.
        /// </param>
        /// <param name="optionalPath">
        /// Path to the realm, must be a valid full path for the current platform, relative subdirectory, or just filename.
        /// </param>
        public SyncConfiguration(User user = null, Uri serverUri = null, string optionalPath = null)
        {
            Argument.Ensure(user != null || User.AllLoggedIn.Length == 1,
                            "The user must be explicitly specified when the number of logged-in users is not 1.",
                            nameof(user));

            User = user ?? User.Current;
            if (serverUri == null)
            {
                // Using default realm
                IsPartial = true;
                ServerUri = User.GetUriForRealm("/default");
            }
            else if (!serverUri.IsAbsoluteUri)
            {
                ServerUri = User.GetUriForRealm(serverUri);
            }
            else
            {
                Argument.Ensure(serverUri.Scheme.StartsWith("realm"), "Unexpected protocol for server url. Expected realm:// or realms://.", nameof(serverUri));
                ServerUri = serverUri;
            }

            DatabasePath = GetPathToRealm(optionalPath ?? SharedRealmHandleExtensions.GetRealmPath(User, ServerUri));
        }
        internal override async Task <Realm> CreateRealmAsync(RealmSchema schema)
        {
            var session = new Session(SharedRealmHandleExtensions.GetSession(DatabasePath, ToNative(), EncryptionKey));
            await session.WaitForDownloadAsync();

            return(CreateRealm(schema));
        }
Exemple #4
0
        /// <summary>
        /// Configures user persistence. If you need to call this, be sure to do so before accessing any other Realm API.
        /// </summary>
        /// <param name="mode">The persistence mode.</param>
        /// <param name="encryptionKey">The key to encrypt the persistent user store with.</param>
        /// <param name="resetOnError">If set to <c>true</c> reset the persistent user store on error.</param>
        /// <remarks>
        /// Users are persisted in a realm file within the application's sandbox.
        /// <para>
        /// By default <see cref="User"/> objects are persisted and are additionally protected with an encryption key stored
        /// in the iOS Keychain when running on an iOS device (but not on a Simulator).
        /// On Android users are persisted in plaintext, because the AndroidKeyStore API is only supported on API level 18 and up.
        /// You might want to provide your own encryption key on Android or disable persistence for security reasons.
        /// </para>
        /// </remarks>
        public static void ConfigurePersistence(UserPersistenceMode mode, byte[] encryptionKey = null, bool resetOnError = false)
        {
            if (mode == UserPersistenceMode.Encrypted && encryptionKey != null && encryptionKey.Length != 64)
            {
                throw new ArgumentException("The encryption key must be 64 bytes long", nameof(encryptionKey));
            }

            SharedRealmHandleExtensions.ConfigureFileSystem(mode, encryptionKey, resetOnError);
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="SyncConfiguration"/> class.
        /// </summary>
        /// <param name="user">A valid <see cref="User"/>.</param>
        /// <param name="serverUri">
        /// A unique <see cref="Uri"/> that identifies the Realm. In URIs, <c>~</c> can be used as a placeholder for a user Id.
        /// </param>
        /// <param name="optionalPath">
        /// Path to the realm, must be a valid full path for the current platform, relative subdirectory, or just filename.
        /// </param>
        public SyncConfiguration(User user, Uri serverUri, string optionalPath = null)
            : base(optionalPath ?? SharedRealmHandleExtensions.GetRealmPath(user, serverUri))
        {
            Argument.NotNull(user, nameof(user));
            Argument.NotNull(serverUri, nameof(serverUri));
            Argument.Ensure(serverUri.Scheme.StartsWith("realm"), "Unexpected protocol for server url. Expected realm:// or realms://.", nameof(serverUri));

            User      = user ?? throw new ArgumentNullException(nameof(user));
            ServerUri = serverUri ?? throw new ArgumentNullException(nameof(serverUri));
        }
Exemple #6
0
        /// <summary>
        /// Gets a logged in user with a specified identity.
        /// </summary>
        /// <returns>A user instance if a logged in user with that id exists, <c>null</c> otherwise.</returns>
        /// <param name="identity">The identity of the user.</param>
        /// <param name="serverUri">The URI of the server that the user is authenticated against.</param>
        public static User GetLoggedInUser(string identity, Uri serverUri)
        {
            SharedRealmHandleExtensions.DoInitialFileSystemConfiguration();

            if (SyncUserHandle.TryGetLoggedInUser(identity, serverUri.AbsoluteUri, out var userHandle))
            {
                return(new User(userHandle));
            }

            return(null);
        }
        internal override Realm CreateRealm(RealmSchema schema)
        {
            var configuration = new Realms.Native.Configuration
            {
                Path           = DatabasePath,
                schema_version = SchemaVersion
            };

            var srHandle = SharedRealmHandleExtensions.OpenWithSync(configuration, ToNative(), schema, EncryptionKey);

            return(new Realm(srHandle, this, schema));
        }
Exemple #8
0
        /// <summary>
        /// Gets a logged in user with a specified identity.
        /// </summary>
        /// <returns>A user instance if a logged in user with that id exists, <c>null</c> otherwise.</returns>
        /// <param name="identity">The identity of the user.</param>
        /// <param name="serverUrl">The URI of the server that the user is authenticated against.</param>
        public static User GetLoggedInUser(string identity, Uri serverUrl)
        {
            SharedRealmHandleExtensions.DoInitialFileSystemConfiguration();

            var handle = SyncUserHandle.GetLoggedInUser(identity, serverUrl.AbsoluteUri);

            if (handle == null)
            {
                return(null);
            }

            return(new User(handle));
        }
Exemple #9
0
        public static User GetLoggedInUser(string identity, Uri serverUri)
        {
            Argument.NotNull(identity, nameof(identity));
            Argument.NotNull(serverUri, nameof(serverUri));

            SharedRealmHandleExtensions.DoInitialMetadataConfiguration();

            if (SyncUserHandle.TryGetLoggedInUser(identity, serverUri.AbsoluteUri, out var userHandle))
            {
                return(new User(userHandle));
            }

            return(null);
        }
Exemple #10
0
        /// <summary>
        /// Logs the user in to the Realm Object Server.
        /// </summary>
        /// <param name="credentials">The credentials to use for authentication.</param>
        /// <param name="serverUrl">The URI of the server that the user is authenticated against.</param>
        /// <returns>An awaitable Task, that, upon completion, contains the logged in user.</returns>
        public static async Task <User> LoginAsync(Credentials credentials, Uri serverUrl)
        {
            SharedRealmHandleExtensions.DoInitialFileSystemConfiguration();

            if (credentials.IdentityProvider == Credentials.Providers.AccessToken)
            {
                var identity = (string)credentials.UserInfo[Credentials.Keys.Identity];
                var isAdmin  = (bool)credentials.UserInfo[Credentials.Keys.IsAdmin];
                return(new User(SyncUserHandle.GetSyncUser(identity, credentials.Token, serverUrl?.AbsoluteUri, isAdmin)));
            }

            var result = await AuthenticationHelper.Login(credentials, serverUrl);

            return(new User(SyncUserHandle.GetSyncUser(result.Item1, result.Item2, serverUrl.AbsoluteUri, isAdmin: false)));
        }
        internal override Realm CreateRealm(RealmSchema schema)
        {
            var configuration = new Realms.Native.Configuration
            {
                schema_version = SchemaVersion
            };

            var syncConfiguration = new Native.SyncConfiguration
            {
                SyncUserHandle = User.Handle,
                Url            = ServerUri.ToString()
            };

            var srHandle = SharedRealmHandleExtensions.OpenWithSync(configuration, syncConfiguration, schema, EncryptionKey);

            return(new Realm(srHandle, this, schema));
        }
Exemple #12
0
        internal override Realm CreateRealm(RealmSchema schema)
        {
            var configuration = new Realms.Native.Configuration
            {
                Path           = DatabasePath,
                schema_version = SchemaVersion,
                enable_cache   = EnableCache
            };

            var srHandle = SharedRealmHandleExtensions.OpenWithSync(configuration, ToNative(), schema, EncryptionKey);

            if (IsDynamic && !schema.Any())
            {
                srHandle.GetSchema(nativeSchema => schema = RealmSchema.CreateFromObjectStoreSchema(nativeSchema));
            }

            return(new Realm(srHandle, this, schema));
        }
Exemple #13
0
        internal override Realm CreateRealm(RealmSchema schema)
        {
            var configuration = new Realms.Native.Configuration
            {
                Path           = DatabasePath,
                schema_version = SchemaVersion
            };

            var syncConfiguration = new Native.SyncConfiguration
            {
                SyncUserHandle      = User.Handle,
                Url                 = ServerUri.ToString(),
                client_validate_ssl = EnableSSLValidation,
            };

            var srHandle = SharedRealmHandleExtensions.OpenWithSync(configuration, syncConfiguration, schema, EncryptionKey);

            return(new Realm(srHandle, this, schema));
        }
        public static async Task <IQueryable <T> > SubscribeToObjectsAsync <T>(this Realm realm, string query)
        {
            Argument.NotNull(realm, nameof(realm));
            Argument.Ensure(realm.Config is SyncConfigurationBase, "Cannot get a Session for a Realm without a SyncConfiguration", nameof(realm));

            var type = typeof(T);

            if (!realm.Metadata.TryGetValue(type.GetTypeInfo().GetMappedOrOriginalName(), out var metadata) || metadata.Schema.Type.AsType() != type)
            {
                throw new ArgumentException($"The class {type.Name} is not in the limited set of classes for this realm");
            }

            var tcs = new TaskCompletionSource <ResultsHandle>();

            SharedRealmHandleExtensions.SubscribeForObjects(realm.SharedRealmHandle, type, query, tcs);

            var resultsHandle = await tcs.Task;

            return(new RealmResults <T>(realm, metadata, resultsHandle));
        }
Exemple #15
0
 /// <summary>
 /// Attempts to reconnect all sessions.
 /// </summary>
 /// <remarks>
 /// By default, the sync engine will attempt to reconnect sessions at incrementing intervals. This method is
 /// useful when you are monitoring connectivity yourself, using e.g.
 /// <see href="https://github.com/jamesmontemagno/ConnectivityPlugin">Connectivity Plugin</see> or through the
 /// native connectivity API and you wish to cancel that delay and try to reconnect immediately.
 /// </remarks>
 public static void Reconnect()
 {
     SharedRealmHandleExtensions.ReconnectSessions();
 }
        /// <summary>
        /// Initializes a new instance of the <see cref="SyncConfiguration"/> class.
        /// </summary>
        /// <param name="user">A valid <see cref="User"/>.</param>
        /// <param name="serverUri">A unique <see cref="Uri"/> that identifies the Realm. In URIs, <c>~</c> can be used as a placeholder for a user Id.</param>
        /// <param name="optionalPath">Path to the realm, must be a valid full path for the current platform, relative subdirectory, or just filename.</param>
        public SyncConfiguration(User user, Uri serverUri, string optionalPath = null) : base(optionalPath ?? SharedRealmHandleExtensions.GetRealmPath(user, serverUri))
        {
            if (user == null)
            {
                throw new ArgumentNullException(nameof(user));
            }

            if (serverUri == null)
            {
                throw new ArgumentNullException(nameof(serverUri));
            }

            User      = user;
            ServerUri = serverUri;
        }
        /// <summary>
        /// Sets the feature token, associated with your edition. You only need to call it if you're using a professional
        /// or higher edition and only on platforms where features are disabled for lower editions.
        /// </summary>
        /// <param name="token">The feature token provided to you by the Realm team.</param>
        /// <seealso href="https://realm.io/docs/realm-object-server/pe-ee/#enabling-professional-and-enterprise-apis">
        /// See more details on Enabling Professional and Enterprise APIs in the documentation.
        /// </seealso>
        public static void SetFeatureToken(string token)
        {
            Argument.NotNullOrEmpty(token, nameof(token));

            SharedRealmHandleExtensions.SetFeatureToken(token);
        }