Exemplo n.º 1
0
        /// <summary>
        /// Актуализация разрешений в RabbitMQ.
        /// </summary>
        /// <param name="clientId">ID клиента для актуализации разрешений.</param>
        public void SynchronizeSendingPermissions(string clientId = null)
        {
            if (string.IsNullOrEmpty(clientId))
            {
                List <Task> tasks = new List <Task>();
                List <SendingPermission> esbPermissions = _dataService.Query <SendingPermission>(SendingPermission.Views.ServiceBusView).ToList();
                List <string>            usersIds       = esbPermissions.Select(p => p.Client.ID).Distinct().ToList();
                foreach (string id in usersIds)
                {
                    _mqSubscriptionsManager.CreateClient(id, id);
                    User user = _managementClient.GetUserAsync(id).Result;
                    tasks.Add(SynchronizePermissionsForClient(user, esbPermissions));
                }

                List <Permission> mqPermissions = _managementClient.GetPermissionsAsync().Result.Where(p => !usersIds.Contains(p.User) && p.User != ConfigurationManager.AppSettings["DefaultRmqUserName"]).ToList();

                foreach (Permission mqPermission in mqPermissions)
                {
                    User user = _managementClient.GetUserAsync(mqPermission.User).Result;
                    tasks.Add(_managementClient.CreatePermissionAsync(CreatePermissionInfo(user)));
                }

                Task.WaitAll(tasks.ToArray());
            }
            else
            {
                User user = _managementClient.GetUserAsync(clientId).Result;
                SynchronizePermissionsForClient(user).Wait();
            }
        }
Exemplo n.º 2
0
        public async Task Should_be_able_to_create_permissions()
        {
            var user = (await managementClient.GetUsersAsync().ConfigureAwait(false)).SingleOrDefault(x => x.Name == testUser);

            if (user == null)
            {
                throw new EasyNetQTestException(string.Format("user '{0}' hasn't been created", testUser));
            }
            var vhost = (await managementClient.GetVhostsAsync().ConfigureAwait(false)).SingleOrDefault(x => x.Name == testVHost);

            if (vhost == null)
            {
                throw new EasyNetQTestException(string.Format("Test vhost: '{0}' has not been created", testVHost));
            }

            var permissionInfo = new PermissionInfo(user, vhost);
            await managementClient.CreatePermissionAsync(permissionInfo).ConfigureAwait(false);
        }
        /// <summary>
        ///     Create a permission
        /// </summary>
        /// <param name="source"></param>
        /// <param name="permissionInfo">The permission to create</param>
        /// <param name="cancellationToken"></param>
        public static void CreatePermission(
            [NotNull] this IManagementClient source,
            [NotNull] PermissionInfo permissionInfo,
            CancellationToken cancellationToken = default
            )
        {
            if (source == null)
            {
                throw new ArgumentNullException(nameof(source));
            }

            source.CreatePermissionAsync(permissionInfo, cancellationToken)
            .GetAwaiter()
            .GetResult();
        }
Exemplo n.º 4
0
        public async Task <bool> CreateUserAsync(string username, string password)
        {
            var vhost = await _managementClient.GetVhostAsync("/");

            if ((await _managementClient.GetUsersAsync()).Any(u => string.Equals(u.Name, username, StringComparison.InvariantCultureIgnoreCase)))
            {
                _logger.LogInformation($"User '{username}' already exists");
                return(false);
            }

            var userInfo   = new UserInfo(username, password);
            var rabbitUser = await _managementClient.CreateUserAsync(userInfo);

            _logger.LogInformation($"RabbitMQ user '{username}' created");

            var logExchangeName = $"logs.{username}";
            var exchangeInfo    = new ExchangeInfo(logExchangeName, ExchangeType.Fanout);
            await _managementClient.CreateExchangeAsync(exchangeInfo, vhost);

            _logger.LogInformation($"RabbitMQ exchange for user '{username}' created");

            var logQueueName = (await _bus.Advanced.QueueDeclareAsync("", maxLength: 1, maxLengthBytes: 4096)).Name;

            var logExchange = await _managementClient.GetExchangeAsync(logExchangeName, vhost);

            var logQueue = await _managementClient.GetQueueAsync(logQueueName, vhost);

            await _managementClient.CreateBindingAsync(logExchange, logQueue, new BindingInfo(""));

            var permissionInfo = new PermissionInfo(rabbitUser, vhost)
                                 .DenyAllConfigure()
                                 .SetRead("^amq\\.")
                                 .SetWrite("^logs\\.");
            await _managementClient.CreatePermissionAsync(permissionInfo);

            _logger.LogInformation($"RabbitMQ permissions for user '{username}' set");

            var errorExchange = await _managementClient.GetExchangeAsync("errors", vhost);

            var errorQueueName = (await _bus.Advanced.QueueDeclareAsync("")).Name;

            _logger.LogInformation($"RabbitMQ error queue for user '{username}' created");

            var errorQueue = await _managementClient.GetQueueAsync(errorQueueName, vhost);

            await _managementClient.CreateBindingAsync(errorExchange, errorQueue, new BindingInfo(username));

            _logger.LogInformation($"RabbitMQ error queue for user '{username}' bound to error exchange");

            await _elasticsearchClient.CreateUserAsync(username, password);

            _logger.LogInformation($"ElasticSearch user '{username}' created");

            await _elasticsearchClient.CreateIndexAsync(username);

            _logger.LogInformation($"ElasticSearch index for '{username}' created");

            var salt         = CryptoUtils.GenerateSalt();
            var passwordHash = CryptoUtils.ComputeHash(salt, password);

            var user = new Deer.Models.User
            {
                Username        = username,
                Salt            = salt,
                PasswordHash    = passwordHash,
                LogIndexName    = username,
                LogExchangeName = logExchangeName,
                LogQueueName    = logQueueName,
                ErrorQueueName  = errorQueueName
            };
            await _userRepository.CreateAsync(user);

            _logger.LogInformation($"UserInfo for user '{username}' saved to MongoDB");

            await _logConsumerService.AddConsumerForUserAsync(username);

            _logger.LogInformation($"Added log consumer for user '{username}'");

            return(true);
        }