public async Task <IActionResult> AddUserAccountAsync([FromBody] CreateUserAccountResource createUserAccountResource)
        {
            // How does this validate against the UserAccount model?
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            // Verify email address has valid structure
            string normalizedAddress;

            if (!EmailExtension.TryNormalizeEmail(createUserAccountResource.Email, out normalizedAddress))
            {
                return(BadRequest("Not a valid email address!"));
            }

            // Salt and hash password
            var salt           = BCrypt.Net.BCrypt.GenerateSalt();
            var saltedPassword = createUserAccountResource.Password + salt;
            var hashedPassword = BCrypt.Net.BCrypt.HashPassword(saltedPassword);

            var existingAccount = await unitOfWork.UserAccountRepository
                                  .GetUserAccountAsync(createUserAccountResource.Email);

            if (existingAccount != null && existingAccount.IsDeleted)
            {
                // Overwrite existing account information and undelete it.
                existingAccount.FirstName = createUserAccountResource.FirstName;
                existingAccount.LastName  = createUserAccountResource.LastName;
                existingAccount.Password  = hashedPassword;
                existingAccount.Salt      = salt;
                existingAccount.Deleted   = null;
            }
            else if (existingAccount == null)
            {
                // Map account resource to model
                createUserAccountResource.Email = normalizedAddress;
                var account = _mapper.Map <UserAccount>(createUserAccountResource);

                account.Password = hashedPassword;
                account.Salt     = salt;
                account.Email    = account.Email.Trim().ToLower();

                // Add model to database and save changes
                await unitOfWork.UserAccountRepository.AddAsync(account);
            }
            else
            {
                return(BadRequest("Account already exists"));
            }

            Task.WaitAll(unitOfWork.CompleteAsync());

            // Retrieve account from database
            var createdAccount = await unitOfWork.UserAccountRepository
                                 .GetUserAccountAsync(normalizedAddress);

            // Return mapped account resource
            return(Ok(_mapper.Map <UserAccountResource>(createdAccount)));
        }
Exemplo n.º 2
0
        public async void GetUserMetricsTestAsync()
        {
            // In-memory database only exists while the connection is open
            var connection = new SqliteConnection("DataSource=:memory:");

            connection.Open();

            try
            {
                IUnitOfWork        unitOfWork;
                TasksController    taskController;
                AccountsController accountController;
                DateTime           startDate;

                var options = new DbContextOptionsBuilder <SynchroLeanDbContext>()
                              .UseSqlite(connection)
                              .Options;

                // Create the schema in the database
                using (var context = new SynchroLeanDbContext(options))
                {
                    context.Database.EnsureCreated();
                }

                // Create a newUserTask to send to HTTPPost method (without dates)
                var newUserTask1 = new UserTaskResource {
                    Name         = "User metrics",
                    Description  = "Modify metrics endpoints to accept DateTimes",
                    Weekdays     = 40,
                    CreationDate = DateTime.Now,
                    IsCompleted  = false,
                    IsDeleted    = false,
                    OwnerEmail   = "*****@*****.**"
                };

                // Create a newUserTask to send to HTTPPost method (without dates)
                var newUserTask2 = new UserTaskResource {
                    Name         = "User metrics",
                    Description  = "complete this to have 50% completion rate",
                    Weekdays     = 0,
                    CreationDate = DateTime.Now,
                    IsCompleted  = false,
                    IsDeleted    = false,
                    OwnerEmail   = "*****@*****.**"
                };

                var account = new UserAccountResource {
                    FirstName = "Cole",
                    LastName  = "Phares",
                    Email     = "*****@*****.**",
                    IsDeleted = false
                };

                // Run the test against one instance of the context
                using (var context = new SynchroLeanDbContext(options))
                {
                    // Bind the context to the UnitOfWork object
                    unitOfWork = new UnitOfWork(context);

                    // Create an instance of TasksController
                    taskController = new TasksController(unitOfWork, mapper);

                    // Create an instance of AccountsController
                    accountController = new AccountsController(unitOfWork, mapper);

                    var newAccount = new CreateUserAccountResource
                    {
                        Email     = account.Email,
                        FirstName = account.FirstName,
                        LastName  = account.LastName,
                        Password  = "******",
                        IsDeleted = false
                    };

                    await accountController.AddUserAccountAsync(newAccount);

                    // Add newUserTask to UserTasks table in Db asynchronously
                    await taskController.AddUserTaskAsync(newUserTask1);

                    await taskController.AddUserTaskAsync(newUserTask2);

                    startDate = DateTime.Now;

                    await taskController.EditUserTaskAsync(2,
                                                           new UserTaskResource {
                        Name        = "User metrics",
                        Description = "complete this to have 50% completion rate",
                        Weekdays    = 0,
                        IsCompleted = true,
                        IsDeleted   = false,
                    }
                                                           );
                }

                // Use a separate instance of the context to verify correct data was saved to database
                using (var context = new SynchroLeanDbContext(options))
                {
                    // Bind the Db context to the UnitOfWork object
                    unitOfWork = new UnitOfWork(context);

                    // Create new instance of task controller
                    taskController = new TasksController(unitOfWork, mapper);

                    DateTime endDate = DateTime.Now;

                    // Retrieve the task from the Db asynchronously
                    var completionRateResult = taskController.GetUserCompletionRate("*****@*****.**", startDate, endDate);
                    var actionResult         = completionRateResult.Result;
                    var okObjectResult       = actionResult as OkObjectResult;
                    var completionRate       = okObjectResult.Value as double?;

                    Assert.True(completionRate.Equals(.5));
                }
            }
            finally
            {
                connection.Close();
            }
        }