public async Task Execute(string accountId, PasswordChangeModel model, IValidator validator)
        {
            try
            {
                //Validate input
                _validationStrategy.Validate(model, validator);
                if (validator.HasErrors)
                {
                    return;
                }

                //Validate old password and find account
                Account account = await _accountRepo.Find(x => x.AccountId == accountId && x.AccountStatus != AccountStatus.Inactive).SingleOrDefaultAsync();

                if (account == null ||
                    account.PasswordStatus == PasswordStatus.Empty ||
                    !_secretHashHelper.ValidateSecret(account.Salt + model.OldPassword, account.Password))
                {
                    validator.AddError("Wrong old password", "OldPassword");
                    return;
                }

                //Generate new salt
                string newSalt = _passwordSaltGenerator.Generate();

                //Generate new hashed password
                string newHashedPass = _secretHashHelper.GenerateHash(newSalt + model.NewPassword);

                //Save in db
                _accountRepo.UpdateOne(x => x.AccountId == accountId, CreateUpdateDef(newHashedPass, newSalt));

                //Raise a PasswordChanged event
                PasswordChangedEvent passwordChangedEvent = CreatePasswordChangedEvent(account);
                await Publish(passwordChangedEvent);

                return;
            }
            catch (Exception ex)
            {
                await _logger.LogErrorAsync("ChangeAccountPasswordCommand.Execute", "Exception occurred", new
                {
                    Exception = ex
                });

                throw;
            }
        }
        public async Task <string> Execute(RoleCreateModel roleModel, IValidator validator)
        {
            try
            {
                // Validate fields.
                _validationStrategy.Validate(roleModel, validator);
                if (validator.HasErrors)
                {
                    return(null);
                }

                // Check if role with this name and consumer already exists.
                long count = await _roleRepo.CountDocumentsAsync(x => x.Name == roleModel.Name && x.Consumer == roleModel.Consumer);

                if (count != 0)
                {
                    validator.AddError("A role with this name already exists");
                    return(null);
                }

                // Create role entity.
                Role role = new Role()
                {
                    Id          = roleModel.Id,
                    Name        = roleModel.Name,
                    Description = roleModel.Description,
                    Consumer    = roleModel.Consumer,
                    Status      = roleModel.Status
                };

                // Persist created role.
                await _roleRepo.InsertOneAsync(role);

                // Issue an event describing the created role.
                await Publish(new RoleCreatedOrEditedEvent()
                {
                    CorrelationId = Guid.NewGuid().ToString("N"),
                    IssuerSystem  = "AuthServer.UserSystem",
                    Issuer        = "AuthServer.UserSystem.Services.Commands.CreateRoleCommand",
                    EventDate     = DateTime.Now,

                    Id           = role.Id,
                    Name         = role.Name,
                    Description  = role.Description,
                    Consumer     = role.Consumer,
                    RoleIsActive = (role.Status == RoleStatus.Active)
                });

                // Return role id.
                return(role.Id);
            }
            catch (Exception ex)
            {
                //Log error
                await _logger.LogErrorAsync("CreateRoleCommand.Execute", "Exception was thrown", new
                {
                    RoleModel = roleModel,
                    Exception = ex
                });

                throw;
            }
        }
        public async Task <string> Execute(string accountId, CreateUserModel model, IValidator validator)
        {
            try
            {
                //Validate incoming model
                _newUserValidationStrategy.Validate(model, validator);
                if (validator.HasErrors)
                {
                    return(null);
                }

                //Check if user with such account id already exists
                long count = await _userRepo.CountDocumentsAsync(u => u.AccountId == accountId);

                if (count != 0)
                {
                    validator.AddError("User already exists");
                    return(null);
                }

                //Check account
                long accountCount = await _accountRepo.CountDocumentsAsync(x => x.AccountId == accountId && x.AccountDataStatus == AccountDataStatus.Completed);

                if (accountCount != 1)
                {
                    validator.AddError("Account is not completed");
                    return(null);
                }

                //Check roles
                if (model.RoleIds != null && model.RoleIds.Count != 0)
                {
                    long rolesCount = await _roleRepo.CountDocumentsAsync(Builders <Role> .Filter.In(x => x.Id, model.RoleIds));

                    if (rolesCount != model.RoleIds.Count)
                    {
                        validator.AddError("Invalid roles");
                        return(null);
                    }
                }

                //Create user enity
                User user = CreateUserFromModel(model, accountId);

                //Save in db
                await _userRepo.InsertOneAsync(user);

                //Log user creation
                await _logger.LogEventAsync("UserManager.CreateUser", "User created", new
                {
                    AccountId = user.AccountId,
                    FullName  = $"{user.FirstName} {user.LastName}"
                });

                // Issue an event.
                await Publish(new UserCreatedEvent()
                {
                    CorrelationId = Guid.NewGuid().ToString("N"),
                    IssuerSystem  = "AuthServer.UserSystem",
                    Issuer        = "AuthServer.UserSystem.Services.Commands.CreateUserCommand",
                    EventDate     = DateTime.Now,

                    AccountId = user.AccountId,
                    FirstName = user.FirstName,
                    LastName  = user.LastName,
                    RoleIds   = user.RoleIds
                });

                return(accountId);
            }
            catch (Exception ex)
            {
                //Log exception
                await _logger.LogErrorAsync("CreateUserFromModel.Execute", "Exception occurred", new
                {
                    AccountId = accountId,
                    UserModel = model,
                    Exception = ex
                });

                //rethrow
                throw;
            }
        }
        public async Task Execute(string accountId, ChangeEmailModel model, IValidator validator)
        {
            try
            {
                //Validation
                _validationStrategy.Validate(model, validator);
                if (validator.HasErrors)
                {
                    return;
                }

                //Check email existence
                if (await _accountRepo.CountDocumentsAsync(x => x.Email == model.NewEmail) != 0)
                {
                    validator.AddError("Email already exists");
                    return;
                }

                //Get account from db
                var     accountFilter = AccountFilterDefinition(accountId);
                Account account       = await _accountRepo.Find(accountFilter).SingleOrDefaultAsync();

                if (account == null)
                {
                    validator.AddError("Account not found");
                    return;
                }

                //string oldEmail = account.Email;

                //Update account in db
                _accountRepo.UpdateOne(accountFilter, AccountUpdateDefinition(model.NewEmail));

                //Create and save EmailChangeRecord
                EmailChangeRecord emailChangeRecord = new EmailChangeRecord()
                {
                    RecordId   = Guid.NewGuid().ToString("n"),
                    AccountId  = account.AccountId,
                    OldEmail   = account.Email,
                    NewEmail   = model.NewEmail,
                    Status     = EmailChangeRecordSatus.Changed,
                    CreateDate = DateTime.Now
                };
                _emailChangeRecordRepo.InsertOne(emailChangeRecord);

                //Publish AccountEmailChangedEvent
                await Publish(CreateEvent(model.NewEmail, account, emailChangeRecord.RecordId));

                //Execute confirmation strategy for new email
                await _emailConfirmationStrategy.ImplementConfirmation(account.AccountId);

                return;
            }
            catch (Exception ex)
            {
                //Log exception
                await _logger.LogErrorAsync("ChangeAccountEmailCommand.Execute", "Exception occurred", new
                {
                    ChangeEmailModel = model,
                    Exception        = ex
                });

                //rethrow
                throw;
            }
        }
        public async Task Execute(CreateUserModel userModel, IValidator validator)
        {
            try
            {
                // Validate.
                if (userModel.RoleIds.Count != 0)
                {
                    long count = await _roleRepo.CountDocumentsAsync(Builders <Role> .Filter.In(r => r.Id, userModel.RoleIds));

                    if (count != userModel.RoleIds.Count)
                    {
                        validator.AddError("Invalid role or roles.");
                    }
                }
                if (validator.HasErrors)
                {
                    return;
                }

                // Retrieve account.
                Account account = await _accountRepo.Find(x => x.AccountId == userModel.AccountId && x.AccountStatus != AccountStatus.Inactive)
                                  .SingleOrDefaultAsync();

                if (account == null)
                {
                    throw new ObjectNotFoundException("Account not found");
                }

                // Retrieve user.
                User user = await _userRepo.Find(x => x.AccountId == userModel.AccountId).SingleOrDefaultAsync();

                if (user == null)
                {
                    throw new ObjectNotFoundException("User not found");
                }

                // Set update definition.
                var updateDef = Builders <User> .Update.Set(x => x.RoleIds, userModel.RoleIds);

                // Update.
                await _userRepo.UpdateOneAsync(x => x.AccountId == userModel.AccountId, updateDef);

                // Publish an event.
                await Publish(new UserRolesChangedEvent()
                {
                    CorrelationId = Guid.NewGuid().ToString("N"),
                    Issuer        = "AuthServer.UserSystem.Services.Commands.EditUserRolesCommand",
                    IssuerSystem  = "AuthServer.UserSystem",
                    EventDate     = DateTime.Now,

                    AccountId = user.AccountId,
                    FirstName = user.FirstName,
                    LastName  = user.LastName,
                    RoleIds   = user.RoleIds
                });

                return;
            }
            catch (Exception ex)
            {
                // Log.
                await _logger.LogErrorAsync("EditUserRolesCommand.Execute", "Exception occurred", new
                {
                    UserModel = userModel,
                    Exception = ex
                });

                throw;
            }
        }
Esempio n. 6
0
        public async Task Execute(string roleId, RoleCreateModel changes, IValidator validator)
        {
            try
            {
                //Validate fields
                _validationStrategy.Validate(changes, validator);
                if (validator.HasErrors)
                {
                    return;
                }

                //Check if role with this name and consumer already exists
                long count = await _roleRepo.CountDocumentsAsync(x => x.Name == changes.Name && x.Consumer == changes.Consumer && x.Id != roleId);

                if (count != 0)
                {
                    validator.AddError("A role with this name already exists");
                    return;
                }

                IAsyncCursor <Role> cursor = await _roleRepo.FindAsync(x => x.Id == roleId);

                Role role = await cursor.SingleOrDefaultAsync();

                if (role == null)
                {
                    throw new Exception("Role not found");
                }

                var updateDef = Builders <Role> .Update.Set(r => r.Name, changes.Name)
                                .Set(r => r.Description, changes.Description)
                                .Set(r => r.Consumer, changes.Consumer)
                                .Set(r => r.Status, changes.Status);

                //Persist created role
                await _roleRepo.UpdateOneAsync(r => r.Id == roleId, updateDef);

                await Publish(new RoleCreatedOrEditedEvent()
                {
                    CorrelationId = Guid.NewGuid().ToString("N"),
                    IssuerSystem  = "AuthServer.UserSystem",
                    Issuer        = "AuthServer.UserSystem.Services.Commands.EditRoleCommand",
                    EventDate     = DateTime.Now,

                    Id           = role.Id,
                    Name         = role.Name,
                    Description  = role.Description,
                    Consumer     = role.Consumer,
                    RoleIsActive = (role.Status == RoleStatus.Active)
                });

                return;
            }
            catch (Exception ex)
            {
                //Log error
                await _logger.LogErrorAsync("EditRoleCommand.Execute", "Exception was thrown", new
                {
                    RoleId    = roleId,
                    Changes   = changes,
                    Exception = ex
                });

                throw;
            }
        }