public async Task ChangeFontStyleAsync_UserFontStyleChange_UsersFontStyleChanges(int userId, string fontStyle)
        {
            IDataGateway                   dataGateway                   = new SQLServerGateway();
            IConnectionStringData          connectionString              = new ConnectionStringData();
            IUserAccountRepository         userAccountRepository         = new UserAccountRepository(dataGateway, connectionString);
            IUserAccountSettingsRepository userAccountSettingsRepository = new UserAccountSettingRepository(dataGateway, connectionString);
            ICryptographyService           cryptographyService           = new CryptographyService(userAccountRepository);
            IAuthenticationService         authenticationService         = new AuthenticationService(userAccountRepository);
            IAccountSettingsService        userAccountSettingsManager    = new AccountSettingsService(userAccountRepository, userAccountSettingsRepository, cryptographyService, authenticationService);

            bool result = await userAccountSettingsManager.ChangeFontStyleAsync(userId, fontStyle);

            if (!result)
            {
                Assert.IsTrue(false);
            }
            string newFontStyle = await userAccountSettingsRepository.GetFontStyleByID(userId);

            if (fontStyle == newFontStyle)
            {
                Assert.IsTrue(true);
            }
            else
            {
                Assert.IsTrue(false);
            }
        }
コード例 #2
0
        public virtual async Task GeneratePasswordResetToken(User user, int expirationInMinutes)
        {
            if (user == null)
            {
                throw new ArgumentNullException("user");
            }
            if (expirationInMinutes < 1)
            {
                throw new ArgumentException(
                          "Token expiration should give the user at least a minute to change their password", "expirationInMinutes");
            }

            if (!user.Confirmed)
            {
                throw new InvalidOperationException(Strings.UserIsNotYetConfirmed);
            }

            if (!String.IsNullOrEmpty(user.PasswordResetToken) && !user.PasswordResetTokenExpirationDate.IsInThePast())
            {
                return;
            }

            user.PasswordResetToken = CryptographyService.GenerateToken();
            user.PasswordResetTokenExpirationDate = DateTime.UtcNow.AddMinutes(expirationInMinutes);

            await Auditing.SaveAuditRecord(new UserAuditRecord(user, UserAuditAction.RequestedPasswordReset));

            Entities.SaveChanges();
            return;
        }
コード例 #3
0
        public async Task <bool> SaveAppUser(Entities.User user, string newPasswordToHash = null)
        {
            bool success = true;

            if (!String.IsNullOrEmpty(newPasswordToHash))
            {
                user.PasswordSalt = CryptographyService.PasswordSaltInBase64();
                user.PasswordHash = CryptographyService.PasswordToHashBase64(newPasswordToHash, user.PasswordSalt);
            }
            try
            {
                var entity = await _entityRepository
                             .AsReadOnly()
                             .SingleOrDefaultAsync(s => s.Id == user.Id);

                if (entity == null)
                {
                    entity = user;
                    _entityRepository.Insert(entity);
                }

                await _database.SaveAsync();
            }
            catch
            {
                success = false;
            }
            return(success);
        }
        public async Task ChangePasswordTest_UserPasswordChanges_PasswordChangeCompletes(int userId, string password, string newPassword)
        {
            IDataGateway                   dataGateway                   = new SQLServerGateway();
            IConnectionStringData          connectionString              = new ConnectionStringData();
            IUserAccountRepository         userAccountRepository         = new UserAccountRepository(dataGateway, connectionString);
            IUserAccountSettingsRepository userAccountSettingsRepository = new UserAccountSettingRepository(dataGateway, connectionString);
            ICryptographyService           cryptographyService           = new CryptographyService(userAccountRepository);
            IAuthenticationService         authenticationService         = new AuthenticationService(userAccountRepository);
            IAccountSettingsService        userAccountSettingsManager    = new AccountSettingsService(userAccountRepository, userAccountSettingsRepository, cryptographyService, authenticationService);

            bool result = await userAccountSettingsManager.ChangePasswordAsync(password, newPassword, userId);

            if (!result)
            {
                Assert.IsTrue(false);
            }

            UserAccountModel model = await userAccountRepository.GetAccountById(userId);

            UserAccountRepository userAccountRepo = new UserAccountRepository(new SQLServerGateway(), new ConnectionStringData());

            string encryptedNewPassword = await cryptographyService.EncryptPasswordAsync(newPassword, userId);

            if (model.Password == encryptedNewPassword)
            {
                Assert.IsTrue(true);
            }
            else
            {
                Assert.IsTrue(false);
            }
        }
コード例 #5
0
        public async Task Authenticate()
        {
            // Arrange
            _appSettings.Secret = "atleast32bitsizedsecretstring";
            var authUserDto = new AuthUserDto()
            {
                Password = ""
            };
            var password = CryptographyService.HashPassword("");

            _userRepository.Setup(x => x.Select(It.IsAny <Expression <Func <UserEntity, bool> > >()))
            .ReturnsAsync(new List <UserEntity> {
                new UserEntity {
                    UserName = "******", Password = password, PasswordSalt = ""
                }
            });

            // Act
            var service = new AccountService(_appSettings, _logger.Object, _refreshTokenRepository.Object,
                                             _userRepository.Object);
            var result = await service.Authenticate(authUserDto);

            // Assert
            Assert.NotNull(result);
        }
        public async Task ChangeThemeColor_UsersThemeColorChanges_UsersThemeColorIsChangedSuccessfully(int userId, string ThemeColor)
        {
            IDataGateway                   dataGateway                   = new SQLServerGateway();
            IConnectionStringData          connectionString              = new ConnectionStringData();
            IUserAccountRepository         userAccountRepository         = new UserAccountRepository(dataGateway, connectionString);
            IUserAccountSettingsRepository userAccountSettingsRepository = new UserAccountSettingRepository(dataGateway, connectionString);
            ICryptographyService           cryptographyService           = new CryptographyService(userAccountRepository);
            IAuthenticationService         authenticationService         = new AuthenticationService(userAccountRepository);
            IAccountSettingsService        userAccountSettingsManager    = new AccountSettingsService(userAccountRepository, userAccountSettingsRepository, cryptographyService, authenticationService);

            bool result = await userAccountSettingsManager.ChangeThemeColorAsync(userId, ThemeColor);

            if (!result)
            {
                Assert.IsTrue(false);
            }
            await userAccountSettingsManager.ChangeThemeColorAsync(userId, ThemeColor);

            string newThemeColor = await userAccountSettingsRepository.GetThemeColorByID(userId);

            if (ThemeColor == newThemeColor)
            {
                Assert.IsTrue(true);
            }
            else
            {
                Assert.IsTrue(false);
            }
        }
        public async Task ChangeEmail_UserEmailChanges_EmailChangeCompletes(int userId, string password, string email)
        {
            IDataGateway                   dataGateway                   = new SQLServerGateway();
            IConnectionStringData          connectionString              = new ConnectionStringData();
            IUserAccountRepository         userAccountRepository         = new UserAccountRepository(dataGateway, connectionString);
            IUserAccountSettingsRepository userAccountSettingsRepository = new UserAccountSettingRepository(dataGateway, connectionString);
            ICryptographyService           cryptographyService           = new CryptographyService(userAccountRepository);
            IAuthenticationService         authenticationService         = new AuthenticationService(userAccountRepository);
            IAccountSettingsService        userAccountSettingsManager    = new AccountSettingsService(userAccountRepository, userAccountSettingsRepository, cryptographyService, authenticationService);

            bool result = await userAccountSettingsManager.ChangeEmailAsync(password, email, userId);

            if (!result)
            {
                Assert.IsTrue(false);
            }

            UserAccountModel model = await userAccountRepository.GetAccountById(userId);

            if (model.EmailAddress == email)
            {
                Assert.IsTrue(true);
            }
            else
            {
                Assert.IsTrue(false);
            }
        }
コード例 #8
0
        public virtual Task <AuthenticatedUser> Register(string username, string password, string emailAddress)
        {
            var hashedPassword = CryptographyService.GenerateSaltedHash(password, Constants.PBKDF2HashAlgorithmId);
            var passCred       = new Credential(CredentialTypes.Password.Pbkdf2, hashedPassword);

            return(Register(username, emailAddress, passCred));
        }
コード例 #9
0
        public virtual User GeneratePasswordResetToken(string usernameOrEmail, int expirationInMinutes)
        {
            if (String.IsNullOrEmpty(usernameOrEmail))
            {
                throw new ArgumentNullException("usernameOrEmail");
            }
            if (expirationInMinutes < 1)
            {
                throw new ArgumentException(
                          "Token expiration should give the user at least a minute to change their password", "expirationInMinutes");
            }

            var user = FindByUserNameOrEmail(usernameOrEmail);

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

            if (!user.Confirmed)
            {
                throw new InvalidOperationException(Strings.UserIsNotYetConfirmed);
            }

            if (!String.IsNullOrEmpty(user.PasswordResetToken) && !user.PasswordResetTokenExpirationDate.IsInThePast())
            {
                return(user);
            }

            user.PasswordResetToken = CryptographyService.GenerateToken();
            user.PasswordResetTokenExpirationDate = DateTime.UtcNow.AddMinutes(expirationInMinutes);

            Entities.SaveChanges();
            return(user);
        }
        public async Task ChangeFontSize_UsersFontSizeIsChanged_FontSizeSuccessfullyChanges(int userId, int FontSize)
        {
            IDataGateway                   dataGateway                   = new SQLServerGateway();
            IConnectionStringData          connectionString              = new ConnectionStringData();
            IUserAccountRepository         userAccountRepository         = new UserAccountRepository(dataGateway, connectionString);
            IUserAccountSettingsRepository userAccountSettingsRepository = new UserAccountSettingRepository(dataGateway, connectionString);
            ICryptographyService           cryptographyService           = new CryptographyService(userAccountRepository);
            IAuthenticationService         authenticationService         = new AuthenticationService(userAccountRepository);
            IAccountSettingsService        userAccountSettingsManager    = new AccountSettingsService(userAccountRepository, userAccountSettingsRepository, cryptographyService, authenticationService);

            bool result = await userAccountSettingsManager.ChangeFontSizeAsync(userId, FontSize);

            if (!result)
            {
                Assert.IsTrue(false);
            }
            await userAccountSettingsManager.ChangeFontSizeAsync(userId, FontSize);

            string newFontSize = await userAccountSettingsRepository.GetFontSizeByID(userId);

            if (FontSize.ToString() == newFontSize)
            {
                Assert.IsTrue(true);
            }
            else
            {
                Assert.IsTrue(false);
            }
        }
コード例 #11
0
        public void AuthenticateUserTest_Given_Email_And_Password_Then_True_Should_Be_Returned_If_Password_Match(
            string inputPassword, bool expectedResult)
        {
            //Arrange
            const string passwordSalt = "passwordSalt";

            var    cryptographyService = new CryptographyService();
            string password            = cryptographyService.CreatePasswordHash("password", passwordSalt);

            _cryptographyServiceMock.Setup(service => service.CreatePasswordHash("password", passwordSalt))
            .Returns(password);

            RecipeManagementContext.PrepareTestData(context =>
            {
                context.Users.Add(new User
                {
                    EmailAddress = "*****@*****.**",
                    Password     = password,
                    PasswordSalt = passwordSalt
                });
            });

            //Act
            bool isAuthenticated = _userService.AuthenticateUser("*****@*****.**", inputPassword);

            //Assert
            Assert.That(isAuthenticated, Is.EqualTo(expectedResult));
        }
コード例 #12
0
        public async Task <User> RegisterAsync(UserBase model)
        {
            model.ValidateIsNotNull(nameof(model));
            var userExists = await UserExistsAsync(model.Username);

            var emailInUse = await EmailInUseAsync(model.Email);

            if (userExists || emailInUse)
            {
                return(null);
            }

            var passwordSalt = CryptographyService.CreateSalt();
            var passwordHash = CryptographyService.CreateHash(model.Password, passwordSalt);

            var entity = new Entities.User();

            entity.PasswordHash = passwordHash;
            entity.PasswordSalt = passwordSalt;
            entity.FirstName    = model.FirstName;
            entity.LastName     = model.LastName;
            entity.Username     = model.Username;

            entity.DateOfBirth = model.DateOfBirth;
            entity.Email       = model.Email;

            await _genericRepository.InsertAsync(entity);

            await _databaseScope.SaveChangesAsync();

            return(_mapper.Map <User>(entity));
        }
コード例 #13
0
        public virtual async Task GeneratePasswordResetToken(User user, int expirationInMinutes)
        {
            if (user == null)
            {
                throw new ArgumentNullException(nameof(user));
            }
            if (expirationInMinutes < 1)
            {
                throw new ArgumentException(
                          Strings.TokenExpirationShouldGiveUser1MinuteToChangePassword, nameof(expirationInMinutes));
            }

            if (!user.Confirmed)
            {
                throw new InvalidOperationException(Strings.UserIsNotYetConfirmed);
            }

            if (!string.IsNullOrEmpty(user.PasswordResetToken) && !user.PasswordResetTokenExpirationDate.IsInThePast())
            {
                return;
            }

            user.PasswordResetToken = CryptographyService.GenerateToken();
            user.PasswordResetTokenExpirationDate = _dateTimeProvider.UtcNow.AddMinutes(expirationInMinutes);

            await Auditing.SaveAuditRecord(new UserAuditRecord(user, AuditedUserAction.RequestPasswordReset));

            await Entities.SaveChangesAsync();
        }
        public async Task DeleteAccountByUserIDAsync_UserAccountIsDelted_UserAccountSuccessfulyDeletes(int userId, string password)
        {
            IDataGateway                   dataGateway                   = new SQLServerGateway();
            IConnectionStringData          connectionString              = new ConnectionStringData();
            IUserAccountRepository         userAccountRepository         = new UserAccountRepository(dataGateway, connectionString);
            IUserAccountSettingsRepository userAccountSettingsRepository = new UserAccountSettingRepository(dataGateway, connectionString);
            ICryptographyService           cryptographyService           = new CryptographyService(userAccountRepository);
            IAuthenticationService         authenticationService         = new AuthenticationService(userAccountRepository);
            IAccountSettingsService        userAccountSettingsManager    = new AccountSettingsService(userAccountRepository, userAccountSettingsRepository, cryptographyService, authenticationService);

            bool result = await userAccountSettingsManager.DeleteAccountByUserIDAsync(userId, password);

            if (!result)
            {
                Assert.IsTrue(false);
            }
            UserAccountModel model = await userAccountRepository.GetAccountById(userId);

            if (model.AccountStatus == "Deleted")
            {
                Assert.IsTrue(true);
            }
            else
            {
                Assert.IsTrue(false);
            }
        }
コード例 #15
0
        public void EncryptTextTest()
        {
            string f = "COMMON";
            CryptographyService cryptographyService = new CryptographyService();
            string result = cryptographyService.EncryptText(f);

            Assert.IsNotNull(result);
        }
コード例 #16
0
            public void WhenCheckPasswordGetsCalled()
            {
                Setup();

                _hashedAndSaltedPassword = BCrypt.Net.BCrypt.HashPassword("somethingelse", BCrypt.Net.BCrypt.GenerateSalt());

                _isPasswordCorrect = CryptographyService.CheckPassword(Password, _hashedAndSaltedPassword);
            }
コード例 #17
0
        public void EncryptClearTest_AutoGeneratedSalt_ReturnsEncodedStringContainingSalt()
        {
            const string clear = "TooManySecrets";
            var          srv   = new CryptographyService();
            var          enc   = srv.Encrypt(clear);

            Assert.IsTrue(enc.Contains("#-#"));
        }
コード例 #18
0
 public LineEventMessageHandler(
     HandleRepository handleRepository,
     CryptographyService cryptographyService,
     IHttpClientFactory httpClientFactory)
 {
     this.handleRepository    = handleRepository;
     this.cryptographyService = cryptographyService;
     this.httpClientFactory   = httpClientFactory;
 }
コード例 #19
0
 public DocumentApiController(
     ILogger <DocumentApiController> logger,
     DocumentRepository documentRepository,
     CryptographyService cryptographyService)
 {
     this.logger              = logger;
     this.documentRepository  = documentRepository;
     this.cryptographyService = cryptographyService;
 }
コード例 #20
0
        public void CreateHash_EmptyData_ThrowsArgumentNullException()
        {
            var factory = Substitute.For <ICryptographyProcessorFactory>();
            var svc     = new CryptographyService(factory);

            var e = Assert.Throws <ArgumentNullException>(() => svc.CreateHash(string.Empty, out var x, out var y));

            Assert.That(e.Message, Does.Contain("data"));
        }
コード例 #21
0
        public void RequiresStringToDecrypt()
        {
            //Arrange
            string stringToDecrypt = null;
            var    cryptoService   = new CryptographyService <string>(provider);

            //Act && Assert
            Assert.Throws <ArgumentNullException>(() => cryptoService.Decrypt(stringToDecrypt));
        }
コード例 #22
0
        public void Encrypt_DataListNull_ThrowsArgumentNullException()
        {
            var factory = Substitute.For <ICryptographyProcessorFactory>();
            var svc     = new CryptographyService(factory);

            var e = Assert.Throws <ArgumentNullException>(() => svc.Encrypt((List <string>)null));

            Assert.That(e.Message, Does.Contain("data"));
        }
コード例 #23
0
 public void CreateEncryptedFile(string login, string password)
 {
     passwordManager = new PasswordProvider(
         new Passwords(login, password,
                       Encoding.UTF8.GetString(CryptographyService.GenerateKey()),
                       Encoding.UTF8.GetString(CryptographyService.GenerateKey())));
     passwordManager.Encrypt();
     passwordManager.Save(PswFileName);
 }
コード例 #24
0
        public IActionResult Register(User user)
        {
            user.Password = CryptographyService.Hash(user.Password);
            //user.Username = _protector.Protect(user.Username);
            //user.Username = _protector.Protect(user.Username);
            _context.User.Add(user);
            _context.SaveChanges();

            return(Redirect("/"));
        }
コード例 #25
0
        public void SameInputEncryptedTwiceComparison()
        {
            var service = new CryptographyService();
            var input   = "test";

            var encryptOne = service.Encrypt(input);
            var encryptTwo = service.Encrypt(input);

            Assert.AreEqual(encryptOne, encryptTwo);
        }
コード例 #26
0
        public void Crypto_Hash_String_test()
        {
            var cryptographyService = new CryptographyService(WinRTCrypto.CryptographicEngine, WinRTCrypto.SymmetricKeyAlgorithmProvider, WinRTCrypto.HashAlgorithmProvider, new Logger());

            var valueString            = "3nNkJ5EcI7yyi56ifLSAA";
            var hashedString           = cryptographyService.GetHashString(valueString);
            var hashedStringWithoutPcl = CryptographyHelperWithoutPcl.GetHashString(valueString);

            Assert.AreEqual(hashedString, hashedStringWithoutPcl);
        }
コード例 #27
0
        public void Encrypt_Settings_test()
        {
            var cryptographyService = new CryptographyService(WinRTCrypto.CryptographicEngine, WinRTCrypto.SymmetricKeyAlgorithmProvider, WinRTCrypto.HashAlgorithmProvider, new Logger());

            var valueString         = "3nNkJ5EcI7yyi56ifLSAA";
            var encrypted           = cryptographyService.Encrypt(valueString);
            var encryptedWithoutPcl = SettingsEncryptorWithoutPcl.Encrypt(valueString);

            Assert.AreEqual(encrypted, encryptedWithoutPcl);
        }
コード例 #28
0
        public void Decrypt_Settings_test()
        {
            var cryptographyService = new CryptographyService(WinRTCrypto.CryptographicEngine, WinRTCrypto.SymmetricKeyAlgorithmProvider, WinRTCrypto.HashAlgorithmProvider, new Logger());

            var valueByte           = new byte[] { 56, 99, 56, 132, 151, 253, 216, 41, 121, 141, 13, 158, 180, 215, 74, 5 };
            var decrypted           = cryptographyService.Decrypt(valueByte);
            var decryptedWithoutPcl = SettingsEncryptorWithoutPcl.Decrypt(valueByte);

            Assert.AreEqual(decrypted, decryptedWithoutPcl);
        }
        public async Task CreateDefaultUserAccountSettings_DefaultUserIsCreated_DefaultUserIsSuccessfulyCreated(int UserId, int FontSize, string ThemeColor, string FontStyle)
        {
            IDataGateway           dataGateway           = new SQLServerGateway();
            IConnectionStringData  connectionString      = new ConnectionStringData();
            IUserAccountRepository userAccountRepository = new UserAccountRepository(dataGateway, connectionString);

            int i = 2;

            UserAccountModel userAccountModel = new UserAccountModel();

            userAccountModel.Id            = i;
            userAccountModel.Username      = "******" + i;
            userAccountModel.Password      = "" + i;
            userAccountModel.Salt          = "" + i;
            userAccountModel.EmailAddress  = "TestEmailAddress" + i;
            userAccountModel.AccountType   = "TestAccountType" + i;
            userAccountModel.AccountStatus = "TestAccountStatus" + i;
            userAccountModel.CreationDate  = DateTimeOffset.UtcNow;
            userAccountModel.UpdationDate  = DateTimeOffset.UtcNow;
            await userAccountRepository.CreateAccount(userAccountModel);

            UserAccountSettingsModel userAccountSettingsModel = new UserAccountSettingsModel();

            IUserAccountSettingsRepository userAccountSettingsRepository = new UserAccountSettingRepository(dataGateway, connectionString);
            ICryptographyService           cryptographyService           = new CryptographyService(userAccountRepository);
            IAuthenticationService         authenticationService         = new AuthenticationService(userAccountRepository);
            IAccountSettingsService        userAccountSettingsManager    = new AccountSettingsService(userAccountRepository, userAccountSettingsRepository, cryptographyService, authenticationService);
            UserAccountSettingsModel       model = new UserAccountSettingsModel();

            userAccountSettingsModel.Id         = 0;
            userAccountSettingsModel.UserId     = UserId;
            userAccountSettingsModel.FontSize   = FontSize;
            userAccountSettingsModel.FontStyle  = FontStyle;
            userAccountSettingsModel.ThemeColor = ThemeColor;

            bool result = await userAccountSettingsManager.CreateDefaultUserAccountSettingsAsync(userAccountSettingsModel);

            if (!result)
            {
                Assert.IsTrue(false);
            }

            await userAccountSettingsManager.CreateDefaultUserAccountSettingsAsync(userAccountSettingsModel);

            model = await userAccountSettingsRepository.GetUserAccountSettingsByUserId(UserId);

            if (model.UserId == UserId && model.FontSize == 12 && model.FontStyle == "Defualt Font Style" && model.ThemeColor == "Default Theme Color")
            {
                Assert.IsTrue(true);
            }
            else
            {
                Assert.IsTrue(false);
            }
        }
コード例 #30
0
            public async Task WhenVerifyUserGetsCalled()
            {
                Setup();

                UserRepository.Setup(repo => repo.GetUserByEmail(It.IsAny <string>())).Returns(Task.FromResult(new User {
                    Password = "******"
                }));

                CryptographyService.Setup(service => service.CheckPassword(It.IsAny <string>(), It.IsAny <string>())).Returns(false);
                _verifyUserResult = await AuthService.VerifyUser(_email, _password);
            }