Esempio n. 1
0
        public void CreateActionLog_Should_Create_Action_Log()
        {
            // Arrange
            var container = ContainerMockFactory.Create();

            var securityService = container.Get <ISecurityService>();

            securityService.LogInGuest();

            var actionLogService = container.Get <IActionLogService>();

            var createdActionLog =
                new DTO.ActionLog
            {
                Text          = "User Diana is changed",
                DocumentId    = UserMockFactory.Diana.Id,
                ActionLogType = actionLogService.UserChangedType
            };

            // Act
            actionLogService.CreateActionLog(createdActionLog);

            // Assert
            securityService.LogOut();
            container.Get <ISecurityService>().LogIn(UserMockFactory.Jenya.Login, EncryptServiceMockFactory.JenyaPasswordData.Password);

            var actionLog =
                actionLogService
                .GetActionLogs(TimeServiceMockFactory.UtcNow, TimeServiceMockFactory.UtcNow, null)
                .Single();

            Assert.AreEqual(createdActionLog, actionLog);
        }
Esempio n. 2
0
        public void ResetPassword(DTO.User user)
        {
            CheckHelper.ArgumentNotNull(user, "user");
            CheckHelper.ArgumentWithinCondition(!user.IsNew(), "!user.IsNew()");
            Container.Get <IValidateService>().CheckIsValid(user);

            CheckHelper.WithinCondition(IsLoggedIn, "User is not logged in.");
            CheckHelper.WithinCondition(IsCurrentUserAdministrator, "Only administrator can reset password.");

            var persistentService = Container.Get <IPersistentService>();
            var changedUser       = persistentService.GetEntityById <User>(user.Id);

            CheckHelper.NotNull(changedUser, "User does not exist.");

            if (!changedUser.Active)
            {
                throw new SecurityServiceException("Пользователь отключен администратором.");
            }

            if (changedUser.Id == _currentUser.Id)
            {
                throw new SecurityServiceException("Пользователь не может сбросить себе пароль.");
            }

            var passwordGeneratorService = Container.Get <IPasswordGeneratorService>();
            var password = passwordGeneratorService.GenerateTemporaryPassword(changedUser.Login);

            var encryptService = Container.Get <IEncryptService>();
            var passwordData   = encryptService.EncryptPassword(password);

            changedUser.UpdatePasswordData(passwordData);
            changedUser.UpdateTrackFields(Container);

            persistentService.SaveChanges();

            var actionLogService = Container.Get <IActionLogService>();
            var actionLog        =
                new DTO.ActionLog
            {
                Text          = string.Format("Для {0} был сброшен пароль.", changedUser.GetDataString()),
                DocumentId    = changedUser.Id,
                ActionLogType = actionLogService.PasswordWasResetedForUserType
            };

            actionLogService.CreateActionLog(actionLog);

            Container.Get <INotificationService>().NotifyPasswordReseted(user, passwordData.Password);
        }
Esempio n. 3
0
        public void CreateActionLog_Should_Throw_Exception_When_User_Is_Not_Logged_In()
        {
            // Arrange
            var container = ContainerMockFactory.Create();

            var actionLogService = container.Get <IActionLogService>();

            var createdActionLog =
                new DTO.ActionLog
            {
                Text          = "User Diana is changed",
                DocumentId    = UserMockFactory.Diana.Id,
                ActionLogType = actionLogService.UserChangedType
            };

            // Act
            // Assert
            ExceptionAssert.Throw <InvalidOperationException>(
                () => actionLogService.CreateActionLog(createdActionLog),
                "User is not logged in.");
        }
Esempio n. 4
0
        public void ChangePassword(string newPassword)
        {
            CheckHelper.ArgumentNotNullAndNotEmpty(newPassword, "newPassword");
            CheckHelper.ArgumentWithinCondition(
                StringValidator.ValidatePassword(newPassword),
                "Password has invalid format.");

            CheckHelper.WithinCondition(IsLoggedIn, "User is not logged in.");
            CheckHelper.WithinCondition(_currentUser.Login != DTO.User.GUEST_LOGIN, "Guest cannot change password.");

            var persistentService = Container.Get <IPersistentService>();
            var user = persistentService.GetEntityById <User>(_currentUser.Id);

            CheckHelper.NotNull(user, "Current user does not exist.");
            if (!user.Active)
            {
                throw new SecurityServiceException("Пользователь отключен администратором.");
            }

            var encryptService = Container.Get <IEncryptService>();
            var passwordData   = encryptService.EncryptPassword(newPassword);

            user.UpdatePasswordData(passwordData);
            user.UpdateTrackFields(Container);

            persistentService.SaveChanges();

            var actionLogService = Container.Get <IActionLogService>();
            var actionLog        =
                new DTO.ActionLog
            {
                Text          = string.Format("{0} сменил пароль.", user.GetDataString()),
                DocumentId    = user.Id,
                ActionLogType = actionLogService.UserChangedPasswordType
            };

            actionLogService.CreateActionLog(actionLog);
        }
Esempio n. 5
0
        public void CreateActionLog(DTO.ActionLog createdActionLog)
        {
            CheckHelper.ArgumentNotNull(createdActionLog, "createdActionLog");
            CheckHelper.ArgumentWithinCondition(createdActionLog.IsNew(), "Action Log is not new.");

            var securityService = Container.Get <ISecurityService>();

            CheckHelper.WithinCondition(securityService.IsLoggedIn, "User is not logged in.");

            Container.Get <IValidateService>().CheckIsValid(createdActionLog);

            var persistentService = Container.Get <IPersistentService>();
            var actionLogType     = persistentService.GetEntityById <ActionLogType>(createdActionLog.ActionLogType.Id);
            var currentUser       = persistentService.GetEntityById <User>(securityService.CurrentUser.Id);

            var utcNow = Container.Get <ITimeService>().UtcNow;

            var actionLog =
                new DataAccess.ActionLog
            {
                Text            = createdActionLog.Text,
                DocumentId      = createdActionLog.DocumentId,
                ActionLogType   = actionLogType,
                ActionLogTypeId = actionLogType.Id,
                CreateUser      = currentUser,
                CreateUserId    = currentUser.Id,
                CreateDate      = utcNow
            };

            persistentService.Add(actionLog);

            persistentService.SaveChanges();

            createdActionLog.Id         = actionLog.Id;
            createdActionLog.CreateDate = actionLog.CreateDate;
            createdActionLog.CreateUser = actionLog.CreateUser.GetFullName();
        }
Esempio n. 6
0
        public void CreateUser(DTO.User createdUser)
        {
            CheckHelper.ArgumentNotNull(createdUser, "createdUser");
            CheckHelper.ArgumentWithinCondition(createdUser.IsNew(), "User is not new.");
            CheckHelper.ArgumentNotNull(createdUser.Roles, "createdUser.Roles");
            CheckHelper.ArgumentWithinCondition(createdUser.Roles.All(r => !r.IsNew()), "One of the roles is new.");
            Container.Get <IValidateService>().CheckIsValid(createdUser);

            CheckHelper.WithinCondition(IsLoggedIn, "User is not logged in.");
            CheckHelper.WithinCondition(IsCurrentUserAdministrator, "Only administrator can create user.");

            if (!createdUser.Roles.Any())
            {
                throw new SecurityServiceException("Пользователь должен иметь хотя бы одну роль.");
            }

            var persistentService = Container.Get <IPersistentService>();

            var doesAnotherUserWithTheSameLoginExist =
                persistentService
                .GetEntitySet <User>()
                .Any(u => u.Login == createdUser.Login);

            if (doesAnotherUserWithTheSameLoginExist)
            {
                throw new SecurityServiceException("Пользователь с заданным логином уже существует.");
            }

            var passwordGeneratorService = Container.Get <IPasswordGeneratorService>();
            var password = passwordGeneratorService.GenerateTemporaryPassword(createdUser.Login);

            var encryptService = Container.Get <IEncryptService>();
            var passwordData   = encryptService.EncryptPassword(password);

            var user =
                new User
            {
                FirstName    = createdUser.FirstName,
                LastName     = createdUser.LastName,
                Login        = createdUser.Login,
                Active       = createdUser.Active,
                Email        = createdUser.Email,
                PasswordHash = passwordData.PasswordHash,
                PasswordSalt = passwordData.PasswordSalt
            };

            user.UpdateTrackFields(Container);
            persistentService.Add(user);

            var availableRoles = persistentService.GetEntitySet <Role>().ToArray();

            foreach (var availableRole in availableRoles)
            {
                var userRole =
                    new UserRole
                {
                    Active = createdUser.Roles.Any(r => r.Id == availableRole.Id),
                    Role   = availableRole,
                    RoleId = availableRole.Id,
                    User   = user,
                    UserId = user.Id
                };
                userRole.UpdateTrackFields(Container);
                persistentService.Add(userRole);
            }

            persistentService.SaveChanges();

            createdUser.Id         = user.Id;
            createdUser.CreateDate = user.CreateDate;
            createdUser.CreateUser = user.CreatedBy.GetFullName();
            createdUser.ChangeDate = user.ChangeDate;
            createdUser.ChangeUser = user.ChangedBy.GetFullName();

            var actionLogService = Container.Get <IActionLogService>();
            var actionLog        =
                new DTO.ActionLog
            {
                Text          = string.Format("{0} создан.", user.GetDataString()),
                DocumentId    = user.Id,
                ActionLogType = actionLogService.UserCreatedType
            };

            actionLogService.CreateActionLog(actionLog);

            Container.Get <INotificationService>().NotifyUserCreated(createdUser, passwordData.Password);
        }
Esempio n. 7
0
        public void UpdateUser(DTO.User updatedUser)
        {
            CheckHelper.ArgumentNotNull(updatedUser, "updatedUser");
            CheckHelper.ArgumentWithinCondition(!updatedUser.IsNew(), "User is new.");
            CheckHelper.ArgumentNotNull(updatedUser.Roles, "updatedUser.Roles");
            CheckHelper.ArgumentWithinCondition(updatedUser.Roles.All(r => !r.IsNew()), "One of the roles is new.");
            Container.Get <IValidateService>().CheckIsValid(updatedUser);
            CheckHelper.ArgumentWithinCondition(updatedUser.Login != DTO.User.GUEST_LOGIN, "Guest user cannot be updated.");

            CheckHelper.WithinCondition(IsLoggedIn, "User is not logged in.");
            CheckHelper.WithinCondition(IsCurrentUserAdministrator, "Only administrator can change user data.");

            if (updatedUser.Id == _currentUser.Id)
            {
                if (!updatedUser.Active)
                {
                    throw new SecurityServiceException("Пользователь не может отключить себя.");
                }

                if (updatedUser.Roles.All(r => r.Name != DTO.Role.ADMINISTRATOR_ROLE_NAME))
                {
                    throw new SecurityServiceException("Пользователь не может удалить роль администратора у себя.");
                }
            }

            var persistentService = Container.Get <IPersistentService>();
            var user = persistentService.GetEntityById <User>(updatedUser.Id);

            CheckHelper.NotNull(user, "User does not exist.");

            if (user.Login != updatedUser.Login)
            {
                var doesAnotherUserWithTheSameLoginExist =
                    persistentService
                    .GetEntitySet <User>()
                    .Any(u => u.Login == updatedUser.Login);

                if (doesAnotherUserWithTheSameLoginExist)
                {
                    throw new SecurityServiceException("Пользователь с заданным логином уже существует.");
                }
            }

            user.FirstName = updatedUser.FirstName;
            user.LastName  = updatedUser.LastName;
            user.Login     = updatedUser.Login;
            user.Active    = updatedUser.Active;
            user.Email     = updatedUser.Email;
            user.UpdateTrackFields(Container);

            foreach (var userRole in user.UserRoles)
            {
                // Role needs to be activated
                if (updatedUser.Roles.Any(r => r.Id == userRole.RoleId))
                {
                    // Role is not active
                    if (!userRole.Active)
                    {
                        // Activate role
                        userRole.Active = true;
                        userRole.UpdateTrackFields(Container);
                    }
                }
                // Role needs to be deactivated and it is active
                else if (userRole.Active)
                {
                    // Deactivate role
                    userRole.Active = false;
                    userRole.UpdateTrackFields(Container);
                }
            }

            persistentService.SaveChanges();

            // Refresh current user if it is updated
            if (updatedUser.Id == _currentUser.Id)
            {
                var currentUser = persistentService.GetEntityById <User>(_currentUser.Id);

                var dtoService = Container.Get <IDtoService>();
                _currentUser = dtoService.CreateUser(currentUser);
            }

            updatedUser.ChangeDate = user.ChangeDate;
            updatedUser.ChangeUser = user.ChangedBy.GetFullName();

            var actionLogService = Container.Get <IActionLogService>();
            var actionLog        =
                new DTO.ActionLog
            {
                Text          = string.Format("{0} изменен.", user.GetDataString()),
                DocumentId    = user.Id,
                ActionLogType = actionLogService.UserChangedType
            };

            actionLogService.CreateActionLog(actionLog);
        }