Пример #1
0
        public async Task UserIsActive_AccountStatusIsNotActive_ReturnsFalse(int id, AccountStatus expectedAccountStatus)
        {
            // Arrange
            // Setting up each dependency of ValidationService as a Mock
            Mock <IUserProfileService> mockProfileService = new Mock <IUserProfileService>();
            Mock <IUserAccountService> mockAccountService = new Mock <IUserAccountService>();

            // Instantiate WebUserAccountModel and set AccountStatus to active
            WebUserAccountModel webUserAccountModel = new WebUserAccountModel();

            webUserAccountModel.Id            = id;
            webUserAccountModel.AccountStatus = expectedAccountStatus.ToString();

            // This function reads as: If GetUserAccount is called, then return webUserAccountModel
            mockAccountService.Setup(x => x.GetUserAccount(id)).Returns(Task.FromResult(webUserAccountModel));

            // Finally, instantiate the actual class being tested and pass in the mock objects
            IValidationService validationService = new ValidationService(mockAccountService.Object, mockProfileService.Object);

            // Act
            // Call the function that is being tested
            var actualResult = await validationService.UserIsActive(id);

            // Assert
            // This unit test will pass if it returns false
            Assert.IsFalse(actualResult);
        }
Пример #2
0
        public void ConvertTo_WebAccountToUserAccount_ConvertedObjectHasAccurateData(int expectedId, string expectedUsername, string expectedEmailAddress,
                                                                                     AccountType expectedAccountType, AccountStatus expectedAccountStatus)
        {
            // Arrange
            DateTimeOffset      expectedDate        = DateTimeOffset.UtcNow;
            WebUserAccountModel webUserAccountModel = new WebUserAccountModel();

            webUserAccountModel.Id            = expectedId;
            webUserAccountModel.Username      = expectedUsername;
            webUserAccountModel.EmailAddress  = expectedEmailAddress;
            webUserAccountModel.AccountType   = expectedAccountType.ToString();
            webUserAccountModel.AccountStatus = expectedAccountStatus.ToString();
            webUserAccountModel.CreationDate  = expectedDate;
            webUserAccountModel.UpdationDate  = expectedDate;

            UserAccountModel userAccountModel = new UserAccountModel();

            // Act
            var convertedUserAccountModel = ModelConverterService.ConvertTo(webUserAccountModel, userAccountModel);

            // Assert
            Assert.IsTrue
            (
                convertedUserAccountModel.Id == expectedId &&
                convertedUserAccountModel.Username == expectedUsername &&
                convertedUserAccountModel.Password == null &&
                convertedUserAccountModel.Salt == null &&
                convertedUserAccountModel.EmailAddress == expectedEmailAddress &&
                convertedUserAccountModel.AccountType == expectedAccountType.ToString() &&
                convertedUserAccountModel.AccountStatus == expectedAccountStatus.ToString() &&
                convertedUserAccountModel.CreationDate == expectedDate &&
                convertedUserAccountModel.UpdationDate == expectedDate
            );
        }
        public async Task Login_GotWebUserAccountModel_ReturnWebUserAccountModel(int accountId,
                                                                                 string username, string password, string emailAddress, string accountType,
                                                                                 string accountStatus, string creationDate, string updationDate, string ipAddress)
        {
            // Arrange
            // Setting up each dependency of LoginController as a Mock
            Mock <ILoginManager> mockLoginManager = new Mock <ILoginManager>();

            var webUserAccountModel = new WebUserAccountModel();

            webUserAccountModel.Id            = accountId;
            webUserAccountModel.Username      = username;
            webUserAccountModel.EmailAddress  = emailAddress;
            webUserAccountModel.AccountType   = accountType;
            webUserAccountModel.AccountStatus = accountStatus;
            webUserAccountModel.CreationDate  = DateTimeOffset.Parse(creationDate);
            webUserAccountModel.UpdationDate  = DateTimeOffset.Parse(updationDate);

            var expectedResult = new Result <WebUserAccountModel>();

            expectedResult.Success      = true;
            expectedResult.SuccessValue = webUserAccountModel;

            mockLoginManager.Setup(x => x.Login(username, password, ipAddress)).Returns(Task.FromResult(expectedResult));
        }
        public async Task <Result <int> > CreateUser(WebUserAccountModel webUserAccountModel, WebUserProfileModel webUserProfileModel)
        {
            var result = new Result <int>();

            result.WasSuccessful = false;
            if (_validationService.IsNull(webUserAccountModel))
            {
                result.ErrorMessage = ErrorMessage.Null;
                return(result);
            }
            if (await _validationService.UsernameExists(webUserAccountModel.Username))
            {
                result.ErrorMessage = ErrorMessage.UsernameExists;
                return(result);
            }
            if (await _validationService.EmailExists(webUserAccountModel.EmailAddress))
            {
                result.ErrorMessage = ErrorMessage.EmailExists;
                return(result);
            }

            var userAccountID = await _userAccountService.CreateAccount(webUserAccountModel);

            webUserProfileModel.UserAccountId = userAccountID;
            await _userProfileService.CreateUserProfile(webUserProfileModel);

            result.WasSuccessful = true;
            result.SuccessValue  = userAccountID;
            return(result);
        }
        public async Task GetUserAccountByUsername_CorrectUsername_ReturnsWebUserAccountModel(int accountId,
                                                                                              string username, string emailAddress, string accountType, string accountStatus, string creationDate,
                                                                                              string updationDate)
        {
            // Arrange
            // Setting up each dependency of UserAccountService and dependencies of dependencies
            IDataGateway           dataGateway           = new SQLServerGateway();
            IConnectionStringData  connectionString      = new ConnectionStringData();
            IUserAccountRepository userAccountRepository = new UserAccountRepository(dataGateway, connectionString);

            var expectedResult = new WebUserAccountModel();

            expectedResult.Id            = accountId;
            expectedResult.Username      = username;
            expectedResult.EmailAddress  = emailAddress;
            expectedResult.AccountType   = accountType;
            expectedResult.AccountStatus = accountStatus;
            expectedResult.CreationDate  = DateTimeOffset.Parse(creationDate);
            expectedResult.UpdationDate  = DateTimeOffset.Parse(updationDate);

            // Finally, instantiate the actual class being tested and pass in the dependencies
            IUserAccountService userAccountService = new UserAccountService(userAccountRepository);

            // Arrange
            var actualResult = await userAccountService.GetUserAccountByUsername(username);

            // Act
            Assert.IsTrue(
                actualResult.Id == expectedResult.Id &&
                actualResult.Username == expectedResult.Username
                );
        }
Пример #6
0
        public async Task GetUserAccountByUsername_UserAccountFound_ReturnsWebUserAccountModel(int accountId,
                                                                                               string username, string password, string salt, string emailAddress, string accountType,
                                                                                               string accountStatus, string creationDate, string updationDate)
        {
            // Arrange
            // Setting up each dependency of UserAccountService as a Mock
            Mock <IUserAccountRepository> mockUserAccountRepository = new Mock <IUserAccountRepository>();

            var userAccount    = new UserAccountModel();
            var expectedResult = new WebUserAccountModel();

            userAccount.Id            = accountId;
            userAccount.Username      = username;
            userAccount.Password      = password;
            userAccount.Salt          = salt;
            userAccount.EmailAddress  = emailAddress;
            userAccount.AccountType   = accountType;
            userAccount.AccountStatus = accountStatus;
            userAccount.CreationDate  = DateTimeOffset.Parse(creationDate);
            userAccount.UpdationDate  = DateTimeOffset.Parse(updationDate);

            expectedResult.Id            = accountId;
            expectedResult.Username      = username;
            expectedResult.EmailAddress  = emailAddress;
            expectedResult.AccountType   = accountType;
            expectedResult.AccountStatus = accountStatus;
            expectedResult.CreationDate  = DateTimeOffset.Parse(creationDate);
            expectedResult.UpdationDate  = DateTimeOffset.Parse(updationDate);

            // This function reads as: If GetAccountByUsername is called, then return a UserAccountModel
            mockUserAccountRepository.Setup(x => x.GetAccountByUsername(username)).Returns(Task.FromResult(userAccount));

            // Finally, instantiate the actual class being tested and pass in the mock objects
            IUserAccountService userAccountService = new UserAccountService(mockUserAccountRepository.Object);

            // Arrange
            var actualResult = await userAccountService.GetUserAccountByUsername(username);

            // Act
            Assert.IsTrue
            (
                actualResult.Id == expectedResult.Id &&
                actualResult.Username == expectedResult.Username &&
                actualResult.EmailAddress == expectedResult.EmailAddress &&
                actualResult.AccountType == expectedResult.AccountType &&
                actualResult.AccountStatus == expectedResult.AccountStatus &&
                actualResult.CreationDate == expectedResult.CreationDate &&
                actualResult.UpdationDate == expectedResult.UpdationDate
            );
        }
Пример #7
0
        public async Task <int> CreateAccount(WebUserAccountModel webUserAccountModel)
        {
            try
            {
                var userAccountModel = ModelConverterService.ConvertTo(webUserAccountModel, new UserAccountModel());
                var userAccountId    = await _userAccountRepository.CreateAccount(userAccountModel);

                return(userAccountId);
            }
            catch (SqlCustomException e)
            {
                throw new SqlCustomException(e.Message, e.InnerException);
            }
        }
        public async Task DeleteIfNotActive(int userId)
        {
            try
            {
                WebUserAccountModel model = await _userAccountService.GetUserAccount(userId);

                if (model.AccountStatus != "Active")
                {
                    await _userAccountService.DeleteAccount(userId);
                }
            }
            catch (SqlCustomException e)
            {
                throw new SqlCustomException(e.Message, e.InnerException);
            }
            catch (NullReferenceException e)
            {
                throw new NullReferenceException(e.Message, e.InnerException);
            }
        }
Пример #9
0
        public void ConvertTo_WebToUser_ConversionSuccessful(int expectedId, string expectedUsername, string expectedEmailAddress,
                                                             AccountType expectedAccountType, AccountStatus expectedAccountStatus)
        {
            // Arrange
            WebUserAccountModel webUserAccountModel = new WebUserAccountModel();

            webUserAccountModel.Id            = expectedId;
            webUserAccountModel.Username      = expectedUsername;
            webUserAccountModel.EmailAddress  = expectedEmailAddress;
            webUserAccountModel.AccountType   = expectedAccountType.ToString();
            webUserAccountModel.AccountStatus = expectedAccountStatus.ToString();
            webUserAccountModel.CreationDate  = DateTimeOffset.UtcNow;
            webUserAccountModel.UpdationDate  = DateTimeOffset.UtcNow;

            UserAccountModel userAccountModel = new UserAccountModel();

            // Act
            var convertedUserAccountModel = ModelConverterService.ConvertTo <WebUserAccountModel, UserAccountModel>(webUserAccountModel, userAccountModel);

            // Assert
            Assert.IsTrue(convertedUserAccountModel.GetType().Equals(typeof(UserAccountModel)));
        }
        public List <WebUserAccountModel> PopulateListOfAccountModels(int numAccounts, string namePrefix,
                                                                      int startingId, int idIncrementFactor)
        {
            List <WebUserAccountModel> accounts = new List <WebUserAccountModel>();
            DateTimeOffset             testDate = DateTimeOffset.UtcNow;

            for (int i = startingId; i < numAccounts; i += idIncrementFactor)
            {
                WebUserAccountModel webUserAccountModel = new WebUserAccountModel();
                webUserAccountModel.Id            = i;
                webUserAccountModel.Username      = $"{namePrefix}Username{i}";
                webUserAccountModel.EmailAddress  = $"{namePrefix}EmailAddress{i}";
                webUserAccountModel.AccountType   = $"{namePrefix}{AccountType.User}{i}";
                webUserAccountModel.AccountStatus = $"{namePrefix}{AccountStatus.Active}{i}";
                webUserAccountModel.CreationDate  = testDate;
                webUserAccountModel.UpdationDate  = testDate;


                accounts.Add(webUserAccountModel);
            }

            return(accounts);
        }
        public async Task <ActionResult <RegistrationResultModel> > RegisterUser([FromBody] RegistrationModel registrationModel)
        {
            try
            {
                var registrationResultModel = new RegistrationResultModel();

                if (registrationModel.username == null || registrationModel.password == null || registrationModel.emailAddress == null ||
                    registrationModel.firstName == null || registrationModel.surname == null || registrationModel.dateOfBirth == null)
                {
                    registrationResultModel.Success      = false;
                    registrationResultModel.ErrorMessage = ErrorMessage.Null.ToString();

                    Console.WriteLine("Register user failed: " + registrationResultModel.ErrorMessage.ToString());
                    return(StatusCode(404, registrationResultModel));
                }

                var userAccount = new WebUserAccountModel();

                userAccount.Username      = registrationModel.username;
                userAccount.EmailAddress  = registrationModel.emailAddress;
                userAccount.AccountType   = AccountType.User.ToString();
                userAccount.AccountStatus = AccountStatus.Inactive.ToString();
                userAccount.CreationDate  = DateTimeOffset.UtcNow;
                userAccount.UpdationDate  = DateTimeOffset.UtcNow;

                var userProfile = new WebUserProfileModel();

                userProfile.FirstName   = registrationModel.firstName;
                userProfile.Surname     = registrationModel.surname;
                userProfile.DateOfBirth = DateTimeOffset.Parse(registrationModel.dateOfBirth);

                var registrationResult = await _registrationManager.RegisterAccount(userAccount, userProfile,
                                                                                    registrationModel.password, registrationModel.ipAddress);

                registrationResultModel.Success = registrationResult.WasSuccessful;
                Console.WriteLine("Registration successful");
                if (registrationResult.WasSuccessful)
                {
                    registrationResultModel.AccountId    = registrationResult.SuccessValue;
                    registrationResultModel.ErrorMessage = ErrorMessage.None.ToString();

                    Console.WriteLine("register user succeeded: " + registrationResultModel.ErrorMessage.ToString());

                    return(Ok(registrationResultModel));
                }
                else
                {
                    registrationResultModel.ErrorMessage = registrationResult.ErrorMessage.ToString();
                    Console.WriteLine("register user failed: " + registrationResultModel.ErrorMessage.ToString());
                    return(StatusCode(404, registrationResultModel));
                }
            }
            catch (SqlCustomException e)
            {
                var registrationResultModel = new RegistrationResultModel();
                Console.WriteLine("Register user failed" + e.Message);
                registrationResultModel.Success      = false;
                registrationResultModel.ErrorMessage = "You could not be registered. Try again.";

                return(StatusCode(404, registrationResultModel));
            }
            catch (NullReferenceException e)
            {
                var registrationResultModel = new RegistrationResultModel();
                Console.WriteLine("Register user failed" + e.Message);
                registrationResultModel.Success      = false;
                registrationResultModel.ErrorMessage = "A null was returned when registering";

                return(StatusCode(404, registrationResultModel));
            }
        }
        public async Task <Result <int> > RegisterAccount(WebUserAccountModel accountModel,
                                                          WebUserProfileModel userModel, string password, string ipAddress)
        {
            try
            {
                // Create Result to determine the result and message the UI will present
                var resultModel = new Result <int>();
                if (accountModel.Username == null || accountModel.EmailAddress == null || userModel.FirstName == null ||
                    userModel.Surname == null || userModel.DateOfBirth == null || password == null)
                {
                    resultModel.WasSuccessful = false;
                    resultModel.ErrorMessage  = ErrorMessage.Null;
                    Console.WriteLine("Register user failed: " + resultModel.ErrorMessage.ToString());
                    return(resultModel);
                }
                else if (password.Length >= 8 && password.Any(char.IsDigit) &&
                         password.Any(char.IsUpper) && password.Any(char.IsLower))
                {
                    var usernameAlreadyExists = await _validationService.UsernameExists(accountModel.Username);

                    if (usernameAlreadyExists)
                    {
                        // Log and return Username existing result
                        _logger.Log(ErrorMessage.UsernameExists.ToString(), LogTarget.All, LogLevel.error, this.ToString(), "User_Logging");
                        resultModel.WasSuccessful = false;
                        resultModel.ErrorMessage  = ErrorMessage.UsernameExists;
                        Console.WriteLine("Register user failed: " + resultModel.ErrorMessage.ToString());
                        return(resultModel);
                    }

                    var emailAlreadyExists = await _validationService.EmailExists(accountModel.EmailAddress);

                    if (emailAlreadyExists)
                    {
                        // Log and return Email existing result
                        _logger.Log(ErrorMessage.EmailExists.ToString(), LogTarget.All, LogLevel.error, this.ToString(), "User_Logging");
                        resultModel.WasSuccessful = false;
                        resultModel.ErrorMessage  = ErrorMessage.EmailExists;
                        Console.WriteLine("Register user failed: " + resultModel.ErrorMessage.ToString());
                        return(resultModel);
                    }

                    // Creates User Account and gets Account ID to pass along
                    var accountID = await _userAccountService.CreateAccount(accountModel);

                    // Sets the password for the new Account
                    await _cryptographyService.newPasswordEncryptAsync(password, accountID);

                    await _publicUserProfileService.CeatePublicUserProfileAsync(new PublicUserProfileModel()
                    {
                        UserId = accountID
                    });

                    // Passes on the Account ID to the User Profile Model
                    userModel.UserAccountId = accountID;

                    // Create User Profile with the Passed on Account ID
                    var userProfileId = await _userProfileService.CreateUserProfile(userModel);

                    UserAccountSettingsModel userAccountSettingsModel = new UserAccountSettingsModel();
                    userAccountSettingsModel.FontSize   = 12;
                    userAccountSettingsModel.FontStyle  = "Default";
                    userAccountSettingsModel.ThemeColor = "Light";
                    userAccountSettingsModel.UserId     = accountID;
                    await _accountSettingsService.CreateUserAccountSettingsAsync(userAccountSettingsModel);

                    var assignmentPolicy = await _assignmentPolicyService.GetAssignmentPolicyByRole(accountModel.AccountType, 1);

                    var scopes     = assignmentPolicy.SuccessValue.AssignedScopes;
                    var userScopes = new List <UserScopeModel>();
                    var userClaims = new List <UserClaimModel>();

                    foreach (var scope in scopes)
                    {
                        var userScope = new UserScopeModel()
                        {
                            Type          = scope.Type,
                            UserAccountId = accountID
                        };

                        userScopes.Add(userScope);
                        foreach (var claim in scope.Claims)
                        {
                            var repeat = false;
                            foreach (var userClaim in userClaims)
                            {
                                if (userClaim.Type == claim.Type)
                                {
                                    repeat = true;
                                }
                            }
                            if (repeat)
                            {
                                continue;
                            }

                            var userClaimModel = new UserClaimModel()
                            {
                                Type          = claim.Type,
                                Value         = claim.Value,
                                UserAccountId = accountID
                            };

                            userClaims.Add(userClaimModel);
                        }
                    }

                    // Create a new claims principal
                    await _claimsPrincipalService.CreateClaimsPrincipal(new ClaimsPrincipal()
                    {
                        Scopes        = userScopes,
                        Claims        = userClaims,
                        Role          = accountModel.AccountType,
                        UserAccountId = accountID
                    });

                    //Log and Return result
                    _logger.Log("User: "******" was registered", LogTarget.All, LogLevel.info, this.ToString(), "User_Logging");
                    resultModel.WasSuccessful = true;
                    resultModel.SuccessValue  = accountID;

                    await _emailService.CreateVerificationToken(accountID);

                    var emailResult = await SendVerificationEmail(accountID);

                    //Log Email Result
                    if (emailResult == true)
                    {
                        _logger.Log("Verification email sent to " + accountModel.Username, LogTarget.All, LogLevel.info, this.ToString(), "User_Logging");
                    }
                    else
                    {
                        _logger.Log("Verification email failed to send to " + accountModel.Username, LogTarget.All, LogLevel.error, this.ToString(), "User_Logging");
                    }

                    return(resultModel);
                }

                resultModel.WasSuccessful = false;
                resultModel.ErrorMessage  = ErrorMessage.InvalidPassword;
                Console.WriteLine("Register user failed: " + resultModel.ErrorMessage.ToString());
                return(resultModel);
            }
            catch (SqlCustomException e)
            {
                Console.WriteLine("Register user failed" + e.Message);
                throw new SqlCustomException(e.Message, e.InnerException);
            }
            catch (NullReferenceException e)
            {
                Console.WriteLine("Register user failed" + e.InnerException.Message);
                throw new NullReferenceException(e.Message, e.InnerException);
            }
        }