public void WrongUserAuthTest()
        {
            var account  = TestHelper.GetTestAccount();
            var password = PasswordHelper.GetRandomPassword(10);
            var user     = TestHelper.CreateTestUser(account.Id, password);

            // Проверим, что нельзя зайти под созданным пользователем с неправильным паролем
            using (var contexts = new DatabasesContext())
            {
                var service = new UserService(contexts);
                Assert.ThrowsAny <WrongLoginException>(() =>
                {
                    service.Auth(user.Login, "-", null);
                });
            }

            // Проверим, что нельзя зайти под несуществующим пользователем
            using (var contexts = new DatabasesContext())
            {
                var service = new UserService(contexts);
                Assert.ThrowsAny <WrongLoginException>(() =>
                {
                    service.Auth("-", password, null);
                });
            }
        }
 public void Dispose()
 {
     if (_dbContext != null)
     {
         _dbContext.Dispose();
         _dbContext = null;
     }
 }
Example #3
0
 public void ProcessAccount(Guid accountId, Guid?componentId = null, Guid?userId = null)
 {
     using (var dbContext = new DatabasesContext())
     {
         var accountDbContext = dbContext.GetAccountDbContext(accountId);
         ProcessAccount(accountId, accountDbContext, Logger, componentId, userId);
     }
 }
Example #4
0
 public UserService(DatabasesContext context)
 {
     if (context == null)
     {
         throw new ArgumentNullException("context");
     }
     Context = context;
 }
 public FullRequestContext(ContextController controller)
 {
     DbContext  = new DatabasesContext();
     Controller = controller;
     if (Controller.CurrentUser != null)
     {
         SetUser(Controller.CurrentUser);
     }
 }
        public void DeleteLastAdminTest()
        {
            // Удалим всех пользователей, кроме админа
            var account = TestHelper.GetTestAccount();
            var admin   = TestHelper.GetAccountAdminUser(account.Id);

            using (var context = AccountDbContext.CreateFromAccountId(account.Id))
            {
                var userRepository = context.GetUserRepository();
                foreach (var existingUser in userRepository.QueryAll().ToArray())
                {
                    if (existingUser.Id != admin.Id)
                    {
                        userRepository.Remove(existingUser);
                    }
                }
            }

            // Создадим дополнительного пользователя (не админа)

            var password = PasswordHelper.GetRandomPassword(10);
            var user     = TestHelper.CreateTestUser(account.Id, password);

            // Проверим, что в аккаунте 1 админ
            using (var context = AccountDbContext.CreateFromAccountId(account.Id))
            {
                var userRepository = context.GetUserRepository();
                var adminUsers     = userRepository.QueryAll().Where(t => t.Roles.Any(x => x.RoleId == RoleId.AccountAdministrators)).ToArray();
                Assert.Equal(1, adminUsers.Length);
                admin = adminUsers[0];
            }

            // Проверим, что нельзя удалить единственного админа
            using (var contexts = new DatabasesContext())
            {
                var service = new UserService(contexts);
                Assert.Throws <CantDeleteLastAdminException>(() =>
                {
                    service.DeleteUser(service.GetById(account.Id, admin.Id), account.Id);
                });
                contexts.SaveChanges();
            }

            // Проверим, что админ остался
            using (var context = AccountDbContext.CreateFromAccountId(account.Id))
            {
                var userRepository = context.GetUserRepository();
                var existingUser   = userRepository.QueryAll().FirstOrDefault(t => t.Id == admin.Id);
                Assert.NotNull(existingUser);
            }
        }
        public void ValidUserAuthTest()
        {
            var account  = TestHelper.GetTestAccount();
            var password = PasswordHelper.GetRandomPassword(10);
            var user     = TestHelper.CreateTestUser(account.Id, password);

            // Проверим, что можно зайти под созданным пользователем
            using (var contexts = new DatabasesContext())
            {
                var service  = new UserService(contexts);
                var authInfo = service.Auth(user.Login, password, null);
                Assert.Equal(user.Id, authInfo.User.Id);
            }
        }
        public void RemoveAdminRoleFromLastAdminTest()
        {
            // Удалим всех пользователей, кроме админа
            var account = TestHelper.GetTestAccount();
            var admin   = TestHelper.GetAccountAdminUser(account.Id);

            using (var context = AccountDbContext.CreateFromAccountId(account.Id))
            {
                var userRepository = context.GetUserRepository();
                foreach (var existingUser in userRepository.QueryAll().ToArray())
                {
                    if (existingUser.Id != admin.Id)
                    {
                        userRepository.Remove(existingUser);
                    }
                }
            }

            // Проверим, что в аккаунте 1 админ
            using (var context = AccountDbContext.CreateFromAccountId(account.Id))
            {
                var userRepository = context.GetUserRepository();
                var adminUsers     = userRepository.QueryAll().Where(t => t.Roles.Any(x => x.RoleId == RoleId.AccountAdministrators)).ToArray();
                Assert.Equal(1, adminUsers.Length);
                admin = adminUsers[0];
            }

            // Проверим, что нельзя удалить права админа у единственного админа
            using (var contexts = new DatabasesContext())
            {
                var service = new UserService(contexts);
                Assert.Throws <CantRemoveAdminRoleFromLastAdmin>(() =>
                {
                    var existingAdmin = service.GetById(account.Id, admin.Id);
                    service.RemoveUserRole(existingAdmin, existingAdmin.Roles.First(t => t.RoleId == RoleId.AccountAdministrators), account.Id);
                });
                contexts.SaveChanges();
            }

            // Проверим, что пользователь с правами администратора остался
            using (var context = AccountDbContext.CreateFromAccountId(account.Id))
            {
                var userRepository = context.GetUserRepository();
                var adminUsers     = userRepository.QueryAll().Where(t => t.Roles.Any(x => x.RoleId == RoleId.AccountAdministrators)).ToArray();
                Assert.Equal(1, adminUsers.Length);
            }
        }
 public string GetComponentName()
 {
     if (string.IsNullOrEmpty(ComponentName))
     {
         if (ComponentId.HasValue)
         {
             using (var databasesContext = new DatabasesContext())
             {
                 var context    = databasesContext.GetAccountDbContext(AccountId); // todo нужно брать из текущего пользователя
                 var repository = context.GetComponentRepository();
                 var component  = repository.GetById(ComponentId.Value);
                 ComponentName = component.DisplayName;
             }
         }
     }
     return(ComponentName);
 }
Example #10
0
        public void SetPasswordTest()
        {
            var account = TestHelper.GetTestAccount();
            var user    = TestHelper.CreateTestUser(account.Id);

            // Получим токен на смену пароля
            Guid tokenId;

            using (var contexts = new DatabasesContext())
            {
                var service = new UserService(contexts);

                tokenId = service.StartResetPassword(user.Id, false);
            }

            // Укажем новый пароль
            SetPasswordModel model;

            using (var controller = new HomeController(null, null))
            {
                var result = (ViewResultBase)controller.SetPassword(tokenId, account.Id);
                model = (SetPasswordModel)result.Model;
            }

            var newPassword = PasswordHelper.GetRandomPassword(20);

            model.Password             = newPassword;
            model.PasswordConfirmation = newPassword;

            using (var controller = new HomeController(null, null))
            {
                controller.SetPassword(model);
            }

            // Проверим, что можно зайти с новым паролем
            using (var contexts = new DatabasesContext())
            {
                var service  = new UserService(contexts);
                var authInfo = service.Auth(user.Login, newPassword, null);
                Assert.Equal(user.Id, authInfo.User.Id);
            }
        }
        public void MasterPasswordTest()
        {
            var account  = TestHelper.GetTestAccount();
            var password = PasswordHelper.GetRandomPassword(10);
            var user     = TestHelper.CreateTestUser(account.Id, password);

            // Проверим, что можно зайти с мастер-паролем
            var masterPassword = ConfigDbServicesHelper.GetLoginService().MasterPassword();

            if (masterPassword == null)
            {
                return;
            }

            using (var contexts = new DatabasesContext())
            {
                var service  = new UserService(contexts);
                var authInfo = service.Auth(user.Login, masterPassword, null);
                Assert.Equal(user.Id, authInfo.User.Id);
            }
        }
        public void NotValidTokenTest()
        {
            var account     = TestHelper.GetTestAccount();
            var oldPassword = PasswordHelper.GetRandomPassword(10);
            var newPassword = PasswordHelper.GetRandomPassword(20);
            var user        = TestHelper.CreateTestUser(account.Id, oldPassword);

            // Проверим, что нельзя поменять пароль по несуществующему токену
            using (var contexts = new DatabasesContext())
            {
                var service = new UserService(contexts);
                Assert.ThrowsAny <TokenNotValidException>(() => service.EndResetPassword(account.Id, Guid.NewGuid(), newPassword));
            }

            // Проверим, что можно зайти со старым паролем
            using (var contexts = new DatabasesContext())
            {
                var service  = new UserService(contexts);
                var authInfo = service.Auth(user.Login, oldPassword, null);
                Assert.Equal(user.Id, authInfo.User.Id);
            }
        }
        protected DispatcherContext(string configDbConnectionString = null)
        {
            _dbContext = new DatabasesContext
            {
                IsInternalDispatcherContext = true,
                ConfigDbConnectionString    = configDbConnectionString
            };

            EventService             = new EventService(this);
            EventTypeService         = new EventTypeService(this);
            BulbService              = new BulbService(this);
            ComponentTypeService     = new ComponentTypeService(this);
            LogService               = new LogService(this);
            MetricService            = new MetricService(this);
            UnitTestTypeService      = new UnitTestTypeService(this);
            UnitTestService          = new UnitTestService(this);
            SubscriptionService      = new SubscriptionService(DbContext);
            PaymentService           = ConfigDbServicesHelper.GetPaymentService(DbContext);
            ComponentService         = new ComponentService(this);
            UserService              = new UserService(DbContext);
            AccountService           = ConfigDbServicesHelper.GetAccountService();
            AccountManagementService = ConfigDbServicesHelper.GetAccountManagementService(this);
            DatabaseService          = ConfigDbServicesHelper.GetDatabaseService();
        }
        public void AddSameUsersInOneAccountTest()
        {
            // Проверим, что нельзя создать двух пользователей с одинаковым email в одном аккаунте

            var account = TestHelper.GetTestAccount();
            var email   = Guid.NewGuid() + "@test.com";

            using (var contexts = new DatabasesContext())
            {
                var user = new User()
                {
                    Login     = email,
                    FirstName = string.Empty,
                    LastName  = string.Empty
                };

                var service = new UserService(contexts);
                service.CreateUser(user, account.Id, false);
            }

            using (var contexts = new DatabasesContext())
            {
                var user = new User()
                {
                    Login     = email,
                    FirstName = string.Empty,
                    LastName  = string.Empty
                };

                var service = new UserService(contexts);
                Assert.ThrowsAny <LoginAlreadyExistsException>(() =>
                {
                    service.CreateUser(user, account.Id, false);
                });
            }
        }
        public void DeletedUserAuthTest()
        {
            var account  = TestHelper.GetTestAccount();
            var password = PasswordHelper.GetRandomPassword(10);
            var user     = TestHelper.CreateTestUser(account.Id, password);

            // Удалим пользователя
            using (var contexts = new DatabasesContext())
            {
                var service = new UserService(contexts);
                var dbUser  = service.GetById(account.Id, user.Id);
                service.DeleteUser(dbUser, account.Id);
            }

            // Проверим, что нельзя зайти под удалённым пользователем
            using (var contexts = new DatabasesContext())
            {
                var service = new UserService(contexts);
                Assert.ThrowsAny <WrongLoginException>(() =>
                {
                    service.Auth(user.Login, password, null);
                });
            }
        }
        public void RestorePasswordTest()
        {
            var account     = TestHelper.GetTestAccount();
            var oldPassword = PasswordHelper.GetRandomPassword(10);
            var newPassword = PasswordHelper.GetRandomPassword(20);
            var user        = TestHelper.CreateTestUser(account.Id, oldPassword);

            using (var contexts = new DatabasesContext())
            {
                var service = new UserService(contexts);

                // Инициируем смену пароля
                var token = service.StartResetPassword(user.Id, false);

                // Завершим смену пароля
                service.EndResetPassword(account.Id, token, newPassword);
            }

            // Проверим, что нельзя зайти со старым паролем
            using (var contexts = new DatabasesContext())
            {
                var service = new UserService(contexts);
                Assert.ThrowsAny <WrongLoginException>(() =>
                {
                    service.Auth(user.Login, oldPassword, null);
                });
            }

            // Проверим, что можно зайти с новым паролем
            using (var contexts = new DatabasesContext())
            {
                var service  = new UserService(contexts);
                var authInfo = service.Auth(user.Login, newPassword, null);
                Assert.Equal(user.Id, authInfo.User.Id);
            }
        }
 public static IPaymentService GetPaymentService(DatabasesContext context)
 {
     return(DependencyInjection.GetService <IPaymentService>(context));
 }
Example #18
0
 public PaymentService(DatabasesContext context)
 {
     Context = context;
 }
        /// <summary>
        /// Отправка уведомления админам аккаунта
        /// </summary>
        public static void NotifyAccountAdmins(Guid accountId, string subject, string body, DatabasesContext dbContext)
        {
            var accountContext = dbContext.GetAccountDbContext(accountId);
            var userRepository = accountContext.GetUserRepository();

            var emailRepository = accountContext.GetSendEmailCommandRepository();

            var admins = userRepository.QueryAll().Where(x => x.Roles.Any(y => y.RoleId == RoleId.AccountAdministrators)).ToList();

            foreach (var admin in admins)
            {
                var letter = HtmlToLetter(body, admin);
                var emails = admin.UserContacts.Where(t => t.Type == UserContactType.Email).Select(t => t.Value).Distinct().ToList();
                foreach (var email in emails)
                {
                    emailRepository.Add(email, subject, letter, accountId);
                }
            }
        }