private async Task UpdateEmailAsync(
            UpdateCurrentUserAccountCommand command,
            int userId,
            User user,
            IExecutionContext executionContext
            )
        {
            var userArea = _userAreaRepository.GetByCode(user.UserAreaCode);
            var newEmail = command.Email?.Trim();

            if (userArea.UseEmailAsUsername && user.Username != newEmail)
            {
                var uniqueQuery = new IsUsernameUniqueQuery()
                {
                    Username     = newEmail,
                    UserId       = userId,
                    UserAreaCode = CofoundryAdminUserArea.AreaCode
                };

                if (!await _queryExecutor.ExecuteAsync(uniqueQuery, executionContext))
                {
                    throw new PropertyValidationException("This email is already registered", "Email");
                }

                user.Username = newEmail;
            }

            user.Email = newEmail;
        }
        public async Task ExecuteAsync(UpdateUserCommand command, IExecutionContext executionContext)
        {
            // Get User
            var user = await _dbContext
                       .Users
                       .FilterCanLogIn()
                       .FilterById(command.UserId)
                       .SingleOrDefaultAsync();

            EntityNotFoundException.ThrowIfNull(user, command.UserId);

            // Validate
            var userArea = _userAreaRepository.GetByCode(user.UserAreaCode);

            ValidatePermissions(userArea, executionContext);
            ValidateCommand(command, userArea);
            await ValidateIsUniqueAsync(command, userArea, executionContext);

            // Role
            if (command.RoleId != user.RoleId)
            {
                user.Role = await _userCommandPermissionsHelper.GetAndValidateNewRoleAsync(
                    command.RoleId,
                    user.RoleId,
                    user.UserAreaCode,
                    executionContext
                    );
            }

            // Map
            Map(command, user, userArea);

            // Save
            await _dbContext.SaveChangesAsync();
        }
        /// <summary>
        /// Maps an EF user record from the db into a UserMicroSummary object. If the
        /// db record is null then null is returned.
        /// </summary>
        /// <param name="dbUser">User record from the database.</param>
        public virtual UserMicroSummary Map(User dbUser)
        {
            if (dbUser == null)
            {
                return(null);
            }

            var user = new UserMicroSummary()
            {
                Email     = dbUser.Email,
                FirstName = dbUser.FirstName,
                LastName  = dbUser.LastName,
                UserId    = dbUser.UserId,
                Username  = dbUser.Username
            };

            var userArea = _userAreaRepository.GetByCode(dbUser.UserAreaCode);

            EntityNotFoundException.ThrowIfNull(userArea, dbUser.UserAreaCode);

            user.UserArea = new UserAreaMicroSummary()
            {
                UserAreaCode = dbUser.UserAreaCode,
                Name         = userArea.Name
            };

            return(user);
        }
Example #4
0
        public async Task ExecuteAsync(UpdateUnauthenticatedUserPasswordCommand command, IExecutionContext executionContext)
        {
            if (IsLoggedInAlready(command, executionContext))
            {
                throw new Exception("UpdateUnauthenticatedUserPasswordCommand cannot be used when the user is already logged in.");
            }

            await ValidateMaxLoginAttemptsNotExceeded(command, executionContext);

            var userArea = _userAreaRepository.GetByCode(command.UserAreaCode);

            var userLoginInfo = await GetUserLoginInfoAsync(command, executionContext);

            if (userLoginInfo == null)
            {
                var failedLoginLogCommand = new LogFailedLoginAttemptCommand(command.UserAreaCode, command.Username);
                await _commandExecutor.ExecuteAsync(failedLoginLogCommand);

                throw new InvalidCredentialsAuthenticationException(nameof(command.OldPassword));
            }

            var updatePasswordCommand = new UpdateUserPasswordByUserIdCommand()
            {
                UserId      = userLoginInfo.UserId,
                NewPassword = command.NewPassword
            };

            // User is not logged in, so will need to elevate permissions here to change the password.
            var systemExecutionContext = await _executionContextFactory.CreateSystemUserExecutionContextAsync(executionContext);

            await _commandExecutor.ExecuteAsync(updatePasswordCommand, systemExecutionContext);

            // We pass out the userid since we do the auth inside the command and it might be useful to the callee
            command.OutputUserId = userLoginInfo.UserId;
        }
        private void ValidateUserArea(string userAreaCode)
        {
            var userArea = _userAreaRepository.GetByCode(userAreaCode);

            if (!userArea.AllowPasswordLogin)
            {
                throw new InvalidOperationException("Cannot reset the password because the " + userArea.Name + " user area does not allow password logins.");
            }
        }
        public void ValidatePermissions(User user, IExecutionContext executionContext)
        {
            var userArea = _userAreaRepository.GetByCode(user.UserAreaCode);

            if (userArea is CofoundryAdminUserArea)
            {
                _permissionValidationService.EnforcePermission(new CofoundryUserUpdatePermission(), executionContext.UserContext);
            }
            else
            {
                _permissionValidationService.EnforcePermission(new NonCofoundryUserUpdatePermission(), executionContext.UserContext);
            }
        }
Example #7
0
        private void UpdatePassword(UpdateCurrentUserPasswordCommand command, IExecutionContext executionContext, User user)
        {
            EntityNotFoundException.ThrowIfNull(user, executionContext.UserContext.UserId);
            var userArea = _userAreaRepository.GetByCode(user.UserAreaCode);

            _passwordUpdateCommandHelper.ValidateUserArea(userArea);

            if (!_userAuthenticationHelper.IsPasswordCorrect(user, command.OldPassword))
            {
                throw new PropertyValidationException("Incorrect password", "OldPassword");
            }

            _passwordUpdateCommandHelper.UpdatePassword(command.NewPassword, user, executionContext);
        }
Example #8
0
        public async Task ExecuteAsync(UpdateUserPasswordByUserIdCommand command, IExecutionContext executionContext)
        {
            var user = await GetUser(command.UserId);

            EntityNotFoundException.ThrowIfNull(user, command.UserId);

            var userArea = _userAreaRepository.GetByCode(user.UserAreaCode);

            _passwordUpdateCommandHelper.ValidateUserArea(userArea);
            _passwordUpdateCommandHelper.ValidatePermissions(userArea, executionContext);

            _passwordUpdateCommandHelper.UpdatePassword(command.NewPassword, user, executionContext);

            await _dbContext.SaveChangesAsync();
        }
        /// <summary>
        /// Maps an EF user record from the db into a UserDetails object. If the
        /// db record is null then null is returned.
        /// </summary>
        /// <param name="dbUser">User record from the database.</param>
        public UserDetails Map(User dbUser)
        {
            if (dbUser == null)
            {
                return(null);
            }

            if (dbUser.Role == null)
            {
                throw new ArgumentException("dbUser.Role must be included in the query to map to use the UserDetailsMapper");
            }

            var user = new UserDetails()
            {
                Email                  = dbUser.Email,
                FirstName              = dbUser.FirstName,
                LastName               = dbUser.LastName,
                UserId                 = dbUser.UserId,
                Username               = dbUser.Username,
                LastLoginDate          = DbDateTimeMapper.AsUtc(dbUser.LastLoginDate),
                LastPasswordChangeDate = DbDateTimeMapper.AsUtc(dbUser.LastPasswordChangeDate),
                RequirePasswordChange  = dbUser.RequirePasswordChange
            };

            user.AuditData = new CreateAuditData()
            {
                CreateDate = DbDateTimeMapper.AsUtc(dbUser.CreateDate)
            };

            if (dbUser.Creator != null)
            {
                user.AuditData.Creator = _userMicroSummaryMapper.Map(dbUser.Creator);
            }

            var userArea = _userAreaRepository.GetByCode(dbUser.UserAreaCode);

            EntityNotFoundException.ThrowIfNull(userArea, dbUser.UserAreaCode);

            user.UserArea = new UserAreaMicroSummary()
            {
                UserAreaCode = dbUser.UserAreaCode,
                Name         = userArea.Name
            };

            user.Role = _roleDetailsMapper.Map(dbUser.Role);

            return(user);
        }
        public Task <UserAreaMicroSummary> ExecuteAsync(GetUserAreaMicroSummaryByCodeQuery query, IExecutionContext executionContext)
        {
            var areaDefinition          = _userAreaRepository.GetByCode(query.UserAreaCode);
            UserAreaMicroSummary result = null;

            if (areaDefinition != null)
            {
                result = new UserAreaMicroSummary()
                {
                    Name         = areaDefinition.Name,
                    UserAreaCode = areaDefinition.UserAreaCode
                };
            }

            return(Task.FromResult(result));
        }
Example #11
0
        /// <summary>
        /// Maps an EF Role record from the db into an RoleDetails
        /// object. If the db record is null then null is returned.
        /// </summary>
        /// <param name="dbRole">Role record from the database.</param>
        public virtual RoleDetails Map(Role dbRole)
        {
            if (dbRole == null)
            {
                return(null);
            }

            var role = new RoleDetails()
            {
                IsAnonymousRole      = dbRole.RoleCode == AnonymousRole.AnonymousRoleCode,
                IsSuperAdministrator = dbRole.RoleCode == SuperAdminRole.SuperAdminRoleCode,
                RoleId   = dbRole.RoleId,
                RoleCode = dbRole.RoleCode,
                Title    = dbRole.Title
            };

            var userArea = _userAreaRepository.GetByCode(dbRole.UserAreaCode);

            role.UserArea = new UserAreaMicroSummary()
            {
                UserAreaCode = dbRole.UserAreaCode,
                Name         = userArea.Name
            };

            if (role.IsSuperAdministrator)
            {
                // Grant super users all permissions
                role.Permissions = _permissionRepository.GetAll().ToArray();
            }
            else
            {
                var permissions = new List <IPermission>(dbRole.RolePermissions.Count);

                foreach (var dbPermission in dbRole.RolePermissions.Select(rp => rp.Permission))
                {
                    var permission = _permissionRepository.GetByCode(dbPermission.PermissionCode, dbPermission.EntityDefinitionCode);
                    if (permission != null)
                    {
                        permissions.Add(permission);
                    }
                }

                role.Permissions = permissions.ToArray();
            }

            return(role);
        }
Example #12
0
        public async Task <UpdateUserCommand> ExecuteAsync(GetPatchableCommandByIdQuery <UpdateUserCommand> query, IExecutionContext executionContext)
        {
            var dbUser = await _dbContext
                         .Users
                         .AsNoTracking()
                         .FilterNotDeleted()
                         .FilterNotSystemAccount()
                         .FilterById(query.Id)
                         .SingleOrDefaultAsync();

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

            if (dbUser.UserAreaCode == CofoundryAdminUserArea.Code)
            {
                _permissionValidationService.EnforceCurrentUserOrHasPermission <CofoundryUserReadPermission>(query.Id, executionContext.UserContext);
            }
            else
            {
                _permissionValidationService.EnforceCurrentUserOrHasPermission <NonCofoundryUserReadPermission>(query.Id, executionContext.UserContext);
            }

            var userArea = _userAreaDefinitionRepository.GetByCode(dbUser.UserAreaCode);

            var user = new UpdateUserCommand()
            {
                Email                 = dbUser.Email,
                FirstName             = dbUser.FirstName,
                LastName              = dbUser.LastName,
                RequirePasswordChange = dbUser.RequirePasswordChange,
                RoleId                = dbUser.RoleId,
                UserId                = dbUser.UserId,
                IsAccountVerified     = dbUser.AccountVerifiedDate.HasValue,
                IsActive              = !dbUser.DeactivatedDate.HasValue
            };

            if (!userArea.UseEmailAsUsername)
            {
                user.Username = dbUser.Username;
            }

            return(user);
        }
Example #13
0
        public async Task ExecuteAsync(AddUserCommand command, IExecutionContext executionContext)
        {
            var userArea   = _userAreaRepository.GetByCode(command.UserAreaCode);
            var dbUserArea = await QueryUserArea(userArea).SingleOrDefaultAsync();

            dbUserArea = AddUserAreaIfNotExists(userArea, dbUserArea);

            ValidateCommand(command, userArea);
            var isUnique = await _queryExecutor.ExecuteAsync(GetUniqueQuery(command, userArea), executionContext);

            ValidateIsUnique(isUnique, userArea);

            var newRole = await _userCommandPermissionsHelper.GetAndValidateNewRoleAsync(command.RoleId, null, command.UserAreaCode, executionContext);

            var user = MapAndAddUser(command, executionContext, newRole, userArea, dbUserArea);
            await _dbContext.SaveChangesAsync();

            command.OutputUserId = user.UserId;
        }
        public async Task ExecuteAsync(EnsureUserAreaExistsCommand command, IExecutionContext executionContext)
        {
            var userArea = _userAreaRepository.GetByCode(command.UserAreaCode);

            EntityNotFoundException.ThrowIfNull(userArea, command.UserAreaCode);

            var dbUserArea = await _dbContext
                             .UserAreas
                             .SingleOrDefaultAsync(a => a.UserAreaCode == userArea.UserAreaCode);

            if (dbUserArea == null)
            {
                dbUserArea = new UserArea();
                dbUserArea.UserAreaCode = userArea.UserAreaCode;
                dbUserArea.Name         = userArea.Name;

                _dbContext.UserAreas.Add(dbUserArea);
            }
        }
Example #15
0
        private PasswordResetRequestAuthenticationResult ValidatePasswordRequest(UserPasswordResetRequest request, ValidatePasswordResetRequestQuery query, IExecutionContext executionContext)
        {
            if (request == null || request.Token != query.Token)
            {
                throw new InvalidPasswordResetRequestException(query, "Invalid password request - Id: " + query.UserPasswordResetRequestId + " Token: " + query.Token);
            }

            if (request.User.UserAreaCode != query.UserAreaCode)
            {
                throw new InvalidPasswordResetRequestException(query, "Request received through an invalid route (incorrect user area)");
            }

            if (request.User.IsDeleted || request.User.IsSystemAccount)
            {
                throw new InvalidPasswordResetRequestException(query, "User not permitted to change password");
            }

            var userArea = _userAreaRepository.GetByCode(request.User.UserAreaCode);

            if (!userArea.AllowPasswordLogin)
            {
                throw new InvalidPasswordResetRequestException(query, "Cannot update the password to account in a user area that does not allow password logins.");
            }

            var result = new PasswordResetRequestAuthenticationResult();

            result.IsValid = true;

            if (request.IsComplete)
            {
                result.IsValid = false;
                result.ValidationErrorMessage = "The password recovery request is no longer valid.";
            }

            if (!IsPasswordRecoveryDateValid(request.CreateDate, executionContext))
            {
                result.IsValid = false;
                result.ValidationErrorMessage = "The password recovery request has expired.";
            }

            return(result);
        }
Example #16
0
        /// <summary>
        /// Maps an EF user record from the db into a UserAccountDetails object. If the
        /// db record is null then null is returned.
        /// </summary>
        /// <param name="dbUser">User record from the database.</param>
        public UserAccountDetails Map(User dbUser)
        {
            if (dbUser == null)
            {
                return(null);
            }

            var user = new UserAccountDetails()
            {
                Email                  = dbUser.Email,
                FirstName              = dbUser.FirstName,
                LastName               = dbUser.LastName,
                UserId                 = dbUser.UserId,
                Username               = dbUser.Username,
                LastLoginDate          = dbUser.LastLoginDate,
                LastPasswordChangeDate = dbUser.LastPasswordChangeDate,
                PreviousLoginDate      = dbUser.PreviousLoginDate,
                RequirePasswordChange  = dbUser.RequirePasswordChange
            };

            user.AuditData = new CreateAuditData()
            {
                CreateDate = dbUser.CreateDate
            };

            if (dbUser.Creator != null)
            {
                user.AuditData.Creator = _userMicroSummaryMapper.Map(dbUser.Creator);
            }

            var userArea = _userAreaRepository.GetByCode(dbUser.UserAreaCode);

            EntityNotFoundException.ThrowIfNull(userArea, dbUser.UserAreaCode);

            user.UserArea = new UserAreaMicroSummary()
            {
                UserAreaCode = dbUser.UserAreaCode,
                Name         = userArea.Name
            };

            return(user);
        }
Example #17
0
        public UserContext Map(User dbUser)
        {
            if (dbUser == null)
            {
                return(null);
            }

            if (dbUser.Role == null)
            {
                throw new ArgumentException("User role is null. Ensure this has been included in the query.", nameof(dbUser));
            }

            var cx = new UserContext();

            cx.IsPasswordChangeRequired = dbUser.RequirePasswordChange;
            cx.RoleId   = dbUser.RoleId;
            cx.RoleCode = dbUser.Role.RoleCode;
            cx.UserId   = dbUser.UserId;
            cx.UserArea = _userAreaRepository.GetByCode(dbUser.UserAreaCode);

            return(cx);
        }
        public bool IsPasswordCorrect(User user, string password)
        {
            if (user == null)
            {
                return(false);
            }

            var userArea = _userAreaRepository.GetByCode(user.UserAreaCode);

            if (!userArea.AllowPasswordLogin)
            {
                throw new InvalidOperationException("This user is not permitted to log in with a password.");
            }

            if (String.IsNullOrWhiteSpace(user.Password) || !user.PasswordHashVersion.HasValue)
            {
                throw new InvalidOperationException("Cannot authenticate via password because the specified account does not have a password set.");
            }

            bool result = _cryptographyService.Verify(password, user.Password, user.PasswordHashVersion.Value);

            return(result);
        }
        /// <summary>
        /// Maps an EF Role record from the db into an RoleDetails
        /// object. If the db record is null then null is returned.
        /// </summary>
        /// <param name="dbRole">Role record from the database.</param>
        public RoleMicroSummary Map(Role dbRole)
        {
            if (dbRole == null)
            {
                return(null);
            }

            var role = new RoleMicroSummary()
            {
                RoleId = dbRole.RoleId,
                Title  = dbRole.Title
            };

            var userArea = _userAreaRepository.GetByCode(dbRole.UserAreaCode);

            role.UserArea = new UserAreaMicroSummary()
            {
                UserAreaCode = dbRole.UserAreaCode,
                Name         = userArea.Name
            };

            return(role);
        }
Example #20
0
 /// <summary>
 /// Determins if a user area exists with the specified code.
 /// </summary>
 /// <param name="userAreaCode">The unique 3 character code that identifies the user area definition.</param>
 /// <returns><see langword="true"/> if the user area exists; otherwise <see langword="false"/>.</returns>
 public static bool Exists(this IUserAreaDefinitionRepository userAreaDefinitionRepository, string userAreaCode)
 {
     return(!string.IsNullOrEmpty(userAreaCode) && userAreaDefinitionRepository.GetByCode(userAreaCode) != null);
 }