Ejemplo n.º 1
0
        /// <summary>
        /// Creates a Sync Gateway user account if it doesn't already exist and then creates a
        /// new local Couchbase Lite database associated with the account.
        /// </summary>
        /// <param name="userId">The user ID.</param>
        /// <param name="channels">The optional channels to be associated with the user.</param>
        /// <param name="roles">The optional roles to be associated with the user.</param>
        /// <returns>Information about thge local database.</returns>
        /// <remarks>
        /// If both <paramref name="channels"/> and <paramref name="roles"/> are <c>null</c>
        /// then the user will be associated with all channels.
        /// </remarks>
        public async Task <LocalDatabase> CreateLocalDatabaseAsync(string userId, IEnumerable <string> channels = null, IEnumerable <RoleProperties> roles = null)
        {
            var userExists = localDatabases.SingleOrDefault(d => d.UserId == userId) != null;
            var password   = userId + "-password";

            if (!userExists)
            {
                if (roles != null)
                {
                    foreach (var role in roles)
                    {
                        if (!existingRoles.Contains(role.Name))
                        {
                            await gatewayManager.RoleCreateAsync(DatabaseName, role);

                            existingRoles.Add(role.Name);
                        }
                    }
                }

                if (channels == null && roles == null)
                {
                    channels = new string[] { "*" };
                }

                if (channels == null)
                {
                    channels = new string[0];
                }

                var roleNames = new List <string>();

                if (roles != null)
                {
                    foreach (var role in roles)
                    {
                        roleNames.Add(role.Name);
                    }
                }

                await gatewayManager.UserCreateAsync(
                    DatabaseName,
                    new UserProperties()
                {
                    Name          = userId,
                    Password      = password,
                    IsDisabled    = false,
                    AdminChannels = channels.ToList(),
                    Roles         = roleNames,
                    Email         = $"{userId}@test.com"
                });
            }

            var localDatabase = new LocalDatabase(gateway.GetDatabaseUri(DatabaseName), userId, password);

            localDatabases.Add(localDatabase);

            return(localDatabase);
        }