Пример #1
0
        public async Task <IActionResult> ActivateAsync([FromQuery, Required] string email)
        {
            var command = new ActivateUserCommand(email);
            await _commandProcessor.SendAsync(command);

            return(Ok(SuccessCodes.UserActivated));
        }
Пример #2
0
        public async Task <IActionResult> ActivateUser(Guid id, ActivateUserCommand input)
        {
            input.Id = id;
            await _mediator.Publish(input);

            return(Ok());
        }
Пример #3
0
        public async Task ThenResultContainsInvalidCodeMessageIfTheAccessCodeDoesntMatchTheAnyOnTheUser()
        {
            //Act
            var command = new ActivateUserCommand
            {
                AccessCode = "AccessCode",
                UserId     = Guid.NewGuid().ToString(),
                User       = new User
                {
                    SecurityCodes = new[]
                    {
                        new SecurityCode
                        {
                            Code       = "Edocssecca",
                            CodeType   = SecurityCodeType.AccessCode,
                            ExpiryTime = DateTime.MaxValue
                        }
                    }
                }
            };
            var result = await _activateUserCommandValidator.ValidateAsync(command);

            Assert.IsTrue(
                result
                .ValidationDictionary.Values.Any(message => message.Equals(InvalidCodeMessage, StringComparison.Ordinal))
                );
        }
Пример #4
0
        public async Task ThenFalseIsReturnedIfTheAccessCodeMatchAnyOnTheUserButItHasExpired()
        {
            //Act
            var command = new ActivateUserCommand
            {
                AccessCode = "AccessCode",
                UserId     = Guid.NewGuid().ToString(),
                User       = new User
                {
                    SecurityCodes = new[]
                    {
                        new SecurityCode
                        {
                            Code       = "AccessCode",
                            CodeType   = SecurityCodeType.AccessCode,
                            ExpiryTime = DateTime.MinValue
                        }
                    }
                }
            };
            var actual = await _activateUserCommandValidator.ValidateAsync(command);

            //Assert
            Assert.IsFalse(actual.IsValid());
        }
Пример #5
0
        public async Task ThenTrueIsReturnedIfAllFieldsAreProvidedAndTheAccessCodeMatchesCaseInsensitive()
        {
            //Act
            var command = new ActivateUserCommand
            {
                AccessCode = "AccessCode",
                UserId     = Guid.NewGuid().ToString(),
                User       = new User
                {
                    SecurityCodes = new[]
                    {
                        new SecurityCode
                        {
                            Code       = "ACCESSCODE",
                            CodeType   = SecurityCodeType.AccessCode,
                            ExpiryTime = DateTime.MaxValue
                        }
                    }
                }
            };
            var actual = await _activateUserCommandValidator.ValidateAsync(command);

            //Assert
            Assert.IsTrue(actual.IsValid());
        }
        public async Task ThenThenUserIsUpdatedWithTheCorrectDetails()
        {
            //Arrange
            var userId     = Guid.NewGuid().ToString();
            var accessCode = "123ADF&^%";
            var user       = new User
            {
                Email     = "*****@*****.**",
                LastName  = "Tester",
                FirstName = "Test",
                Password  = "******",
                IsActive  = false,
                Id        = userId
            };
            var activateUserCommand = new ActivateUserCommand
            {
                UserId     = userId,
                AccessCode = accessCode
            };

            _userRepository.Setup(x => x.GetById(userId)).ReturnsAsync(user);
            _activateUserCommandValidator.Setup(x => x.ValidateAsync(It.Is <ActivateUserCommand>(p => p.AccessCode == accessCode && p.UserId == userId))).ReturnsAsync(new ValidationResult {
                ValidationDictionary = new Dictionary <string, string>()
            });

            //Act
            await _handler.Handle(activateUserCommand);

            //Assert
            _userRepository.Verify(x => x.Update(It.Is <User>(p => p.IsActive && p.Id == userId)), Times.Once);
        }
Пример #7
0
 private void AccountActiveStateChanged()
 {
     OnPropertyChanged("IsAccountActivated");
     OnPropertyChanged("IsAccountDectivated");
     ActivateUserCommand.UpdateCanExecuteState();
     DeactivateUserCommand.UpdateCanExecuteState();
 }
Пример #8
0
        public void Handle(ActivateUserCommand command)
        {
            User user = repo.GetById <User>(new Guid(command.Key));

            user.Activate();
            repo.Save(user, Guid.NewGuid());
        }
Пример #9
0
        private static void SeedAdminUser(this IApplicationBuilder app)
        {
            var createUserCommand = new RegisterUserCommand(
                "admin",
                "admin",
                "admin",
                "*****@*****.**",
                Gender.Other,
                DateTime.Now,
                "zaq1@WSX",
                "zaq1@WSX");
            var activateUserCommand = new ActivateUserCommand(createUserCommand.Id);

            try
            {
                var commandDispatcher = app.ApplicationServices.GetService <ICommandDispatcher>();
                commandDispatcher.DispatchAsync(createUserCommand).GetAwaiter().GetResult();
                commandDispatcher.DispatchAsync(activateUserCommand).GetAwaiter().GetResult();
            }
            catch (Exception ex)
            {
                if (!(ex is BusinessLogicException))
                {
                    throw;
                }
            }
        }
        public CommandResult ActivateFirstAccess(ActivateUserCommand command, string userIdentity)
        {
            var user = _repository.GetById(command.Id);

            if (user == null)
            {
                return(new CommandResult(false, "Usuário não encontrado. ", command));
            }

            user.ActivateFirstAccess(command.Role);

            _repository.UpdateRoleActive(user);

            var log = new AccessLog(
                "PrimeiroAcesso",
                DateTime.Now,
                userIdentity,
                "UserAuth",
                $"acesso liberado: {command.Id}");

            _log.Register(log);

            user.HidePassword();

            return(new CommandResult(true, "Usuário Ativo. ", user));
        }
Пример #11
0
        public async Task <IActionResult> Activate([FromBody] ActivateUserViewModel viewModel)
        {
            var command = new ActivateUserCommand(new AggregateId(viewModel.Id));
            await _commandQueryDispatcherDecorator.DispatchAsync(command);

            return(Ok());
        }
Пример #12
0
        public async Task Handle(ActivateUserCommand message, CancellationToken token = default)
        {
            var user = await _session.Get <User>(message.Id);

            await user.ActivateAccount();

            await _session.Commit(token);
        }
Пример #13
0
        public async Task <IActionResult> CreateUser([FromBody] ActivateUserCommand command)
        {
            command.UserId = UserId;

            var result = await Mediator.Send(command);

            return(Ok(result));
        }
        public async Task <CommandResult <bool> > Handle(ActivateUserCommand request, CancellationToken cancellationToken)
        {
            var res = await _repo.ActivateUser(request.UserId).ConfigureAwait(false);

            return(new CommandResult <bool>()
            {
                Message = res ? "User Activated Successfully." : "Error occurred. Please try again", ResponseObj = true, Status = true
            });
        }
Пример #15
0
        public async Task <DomainUser?> ActivateNewUser(ActivateUserCommand cmd)
        {
            //TODO: collect Ldap user info
            if (cmd.Email == null)
            {
                throw new NotImplementedException("Automatically fetching emails is currently nor supported");
            }

            return(_mapper.Map <User, DomainUser>(await _users.CreateNewUser(cmd.Uid, UserDefaultRole, cmd.Email)));
        }
        public async Task <IActionResult> Activate(int id)
        {
            var command = new ActivateUserCommand(id);
            var result  = await _mediator.Send(command);

            if (result == null)
            {
                return(NotFound());
            }

            return(Ok());
        }
        public async Task Then_The_Command_Is_Handled_And_Endpoint_Called(
            ActivateUserCommand command,
            [Frozen] Mock <IApimDeveloperApiClient <ApimDeveloperApiConfiguration> > apimDeveloperApiClient,
            ActivateUserCommandHandler handler)
        {
            await handler.Handle(command, CancellationToken.None);

            apimDeveloperApiClient.Verify(x => x.Put(It.Is <PutUpdateUserRequest>(c =>
                                                                                  c.PutUrl.Contains(command.Id.ToString()) &&
                                                                                  ((UserRequestData)c.Data).State.Equals(1)
                                                                                  )), Times.Once);
        }
        public void UserAuthHandler_Activate_Valid()
        {
            var repository    = new FakeUserAuthRepository();
            var logRepository = new FakeAccessLogRepository();
            var handler       = new UserAuthHandler(repository, logRepository);
            var command       = new ActivateUserCommand();

            command.Id   = repository.GetInactivesFirstAccess().FirstOrDefault().Id;
            command.Role = "user";
            var result = handler.ActivateFirstAccess(command, "userIdentity");

            Assert.IsTrue(result.Success);
        }
Пример #19
0
        public async Task <IResult> Execute(ActivateUserCommand request)
        {
            var user = await _userService.Get(request.Id);

            if (user.IsActive())
            {
                return(await Result.FailAsync("User already actived!"));
            }

            user.Activate();

            await _userService.Update(user);

            return(await _unitOfWork.Commit() ? Result.Success() : Result.Fail("Internal error, please try again."));
        }
        public async Task <Unit> Handle(ActivateUserCommand request, CancellationToken cancellationToken)
        {
            var email          = new Email(request.UserId);
            var userToActivate = await _repository.GetByEmail(email);

            if (userToActivate == null)
            {
                throw new UserNotFoundForDeleteException();
            }

            userToActivate.UpdateIsActive(request.Active);

            await _repository.Update(userToActivate);

            return(new Unit());
        }
Пример #21
0
        public async Task ThenTrueIsReturnedIfOnlyTheEmailHasBeenSuppliedAndTheUserIdIsNull()
        {
            //Act
            var command = new ActivateUserCommand
            {
                UserId = null,
                Email  = "User@Email",
                User   = new User
                {
                    Email = "user@email"
                }
            };
            var actual = await _activateUserCommandValidator.ValidateAsync(command);

            //Assert
            Assert.IsTrue(actual.IsValid());
        }
Пример #22
0
        public void ActivateUserCommandHandler_Succeeds()
        {
            var handler = new ActivateUserCommandHandler(_repository);
            var command = new ActivateUserCommand("*****@*****.**", "999999");
            var user    = Substitute.For <User>();

            user.Email.Returns("*****@*****.**");
            user.ActivationCode.Returns(999999);
            user.Status.Returns(UserStatus.New);

            _context.Users.Add(user);

            var result = handler.Execute(command);

            result.Errors.Should().BeEmpty();
            user.Received().Activate();
            user.DidNotReceive().ActivationFailed();
        }
        public async Task ThenTheUserIsNotUpdatedIfTheUserIsAlreadyActive()
        {
            //Arrange
            var userId     = Guid.NewGuid().ToString();
            var accessCode = "123ADF&^%";
            var user       = new User
            {
                Email         = "*****@*****.**",
                LastName      = "Tester",
                FirstName     = "Test",
                Password      = "******",
                IsActive      = true,
                Id            = userId,
                SecurityCodes = new[]
                {
                    new SecurityCode
                    {
                        Code       = accessCode,
                        CodeType   = SecurityCodeType.AccessCode,
                        ExpiryTime = DateTime.MaxValue
                    }
                }
            };
            var activateUserCommand = new ActivateUserCommand
            {
                UserId     = userId,
                AccessCode = accessCode
            };

            _userRepository.Setup(x => x.GetById(userId)).ReturnsAsync(user);
            _activateUserCommandValidator.Setup(x => x.ValidateAsync(It.Is <ActivateUserCommand>(p => p.AccessCode == accessCode &&
                                                                                                 p.UserId == userId &&
                                                                                                 p.User.SecurityCodes.Any(sc => sc.Code == accessCode &&
                                                                                                                          sc.CodeType == SecurityCodeType.AccessCode))))
            .ReturnsAsync(new ValidationResult {
                ValidationDictionary = new Dictionary <string, string>()
            });

            //Act
            await _handler.Handle(activateUserCommand);

            //Assert
            _userRepository.Verify(x => x.Update(It.Is <User>(p => p.IsActive && p.Id == userId)), Times.Never);
        }
Пример #24
0
        public async Task <IActionResult> Activate(Guid id)
        {
            if (id == Guid.Empty)
            {
                return(BadRequest("Please provide userid"));
            }

            var userModel = await _queryProcessor.Query(new GetUser(id));

            if (userModel == null)
            {
                return(NotFound());
            }

            var activateUserCommand = new ActivateUserCommand(id);
            await _commandSender.Send(activateUserCommand);

            return(NoContent());
        }
Пример #25
0
        public void ActivateUserCommandHandler_Fails_For_Inactive_User()
        {
            var handler = new ActivateUserCommandHandler(_repository);
            var command = new ActivateUserCommand("*****@*****.**", "999999");
            var user    = Substitute.For <User>();

            user.Email.Returns("*****@*****.**");
            user.ActivationCode.Returns(999999);
            user.Status.Returns(UserStatus.Inactive);

            _context.Users.Add(user);

            var result = handler.Execute(command);

            result.Errors.Should().HaveCount(1);
            result.Errors[0].Expression.ToString().Should().Be("p => p.ActivationCode");
            result.Errors[0].Message.Should().Be("This activation code is invalid");
            user.DidNotReceive().Activate();
            user.Received().ActivationFailed();
        }
        public async Task <IActionResult> ActivateUser(int id)
        {
            if (!ModelState.IsValid)
            {
                LogEndOfRequest("Failed Bad request", 400);
                return(BadRequest(ModelState));
            }
            try
            {
                var command = new ActivateUserCommand(id);
                await userService.ActivateUserCommand.HandleAsync(command);

                LogEndOfRequest("Success", 200);
                return(Ok());
            }
            catch (KeyNotFoundException)
            {
                LogEndOfRequest($"Failed User with id {id} not found", 404);
                return(NotFound());
            }
        }
        public void Arrange()
        {
            _activateUserCommandValidator = new Mock <IValidator <ActivateUserCommand> >();
            _activateUserCommandValidator.Setup(x => x.ValidateAsync(It.IsAny <ActivateUserCommand>()))
            .ReturnsAsync(new ValidationResult {
                ValidationDictionary = new Dictionary <string, string>()
            });

            _user = new User
            {
                SecurityCodes = new[]
                {
                    new SecurityCode
                    {
                        Code      = AccessCode,
                        CodeType  = SecurityCodeType.AccessCode,
                        ReturnUrl = ReturnUrl
                    }
                }
            };
            _userRepository = new Mock <IUserRepository>();
            _userRepository.Setup(x => x.GetById(It.IsAny <string>())).ReturnsAsync(_user);
            _userRepository.Setup(x => x.GetByEmailAddress(It.IsAny <string>())).ReturnsAsync(_user);

            _auditService = new Mock <IAuditService>();

            _logger = new Mock <ILogger>();

            _handler = new ActivateUserCommandHandler(_activateUserCommandValidator.Object, _userRepository.Object, _auditService.Object, _logger.Object);

            _command = new ActivateUserCommand
            {
                AccessCode = AccessCode,
                UserId     = UserId
            };
        }
Пример #28
0
        public CommandResult ActivateFirstAccess(ActivateUserCommand command)
        {
            CommandResult result = _handler.ActivateFirstAccess(command, User.Identity.Name);

            return(result);
        }
Пример #29
0
        public JsonResult Activate(ActivateUserCommand command)
        {
            var result = _commandBus.Send(command);

            return(Json(result.Message));
        }
 public async Task Activate(ActivateUserCommand activateUserCommand)
 {
     await _mediator.Send(activateUserCommand);
 }