示例#1
0
        /// <summary>
        /// Change the specified user account password.
        /// </summary>
        /// <param name="jsonPasswordChangeRequest">The password change details.</param>
        /// <returns></returns>
        private HttpResponseMessage ChangePasswordSoftwarePlatform(JsonPasswordChangeRequest jsonPasswordChangeRequest)
        {
            using (new SecurityBypassContext())
            {
                try
                {
                    UserAccountValidator.Authenticate(jsonPasswordChangeRequest.Username, jsonPasswordChangeRequest.OldPassword,
                                                      jsonPasswordChangeRequest.Tenant, true, true);
                }
                catch (ArgumentException ex)
                {
                    throw new InvalidCredentialException("Invalid user name, password or tenant", ex);
                }

                RequestContext context = ReadiNow.IO.RequestContext.GetContext();
                UserAccount    account = ReadiNow.Model.Entity.Get <UserAccount>(context.Identity.Id, true);

                // Can only change the password via this method if the password is already expired.
                if (account == null || !UserAccountValidator.HasAccountPasswordExpired(account))
                {
                    throw new InvalidCredentialException("Invalid user name, password or tenant");
                }

                account.Password = jsonPasswordChangeRequest.NewPassword;
                account.Save();
            }

            return(new HttpResponseMessage(HttpStatusCode.OK));
        }
        public void Authenticate_LockoutActiveUserOnly(UserAccountStatusEnum_Enumeration status, bool expectLockedOut)
        {
            const string   password = "******";
            UserAccount    userAccount;
            PasswordPolicy passwordPolicy;

            passwordPolicy = Entity.Get <PasswordPolicy>("core:passwordPolicyInstance");

            userAccount      = new UserAccount();
            userAccount.Name = "Test user " + Guid.NewGuid();
            userAccount.AccountStatus_Enum = status;
            userAccount.Password           = password;
            userAccount.Save();

            for (int i = 0; i < passwordPolicy.AccountLockoutThreshold; i++)
            {
                try
                {
                    UserAccountValidator.Authenticate(
                        userAccount.Name,
                        userAccount.Password + "_foo", // Invalid password
                        RequestContext.GetContext().Tenant.Name,
                        false);
                }
                catch (Exception)
                {
                    // This will throw exceptions if the user is locked, disabled or expired. Ignore these exceptions in this test.
                }
            }

            userAccount = Entity.Get <UserAccount>(userAccount.Id);
            Assert.That(userAccount.AccountStatus_Enum,
                        expectLockedOut ? Is.EqualTo(UserAccountStatusEnum_Enumeration.Locked) : Is.EqualTo(status));
        }
        public void Authenticate_ExpiredPassword(bool skipExpiryCheck, bool neverExpires)
        {
            const string password = "******";
            UserAccount  userAccount;

            PasswordPolicy passwordPolicy     = Entity.Get <PasswordPolicy>("core:passwordPolicyInstance");
            int            maximumPasswordAge = passwordPolicy.MaximumPasswordAge ?? 0;

            Assert.AreNotEqual(0, maximumPasswordAge);

            userAccount      = new UserAccount();
            userAccount.Name = "Test user " + Guid.NewGuid();
            userAccount.AccountStatus_Enum   = UserAccountStatusEnum_Enumeration.Active;
            userAccount.PasswordNeverExpires = neverExpires;
            userAccount.Password             = password;
            userAccount.Save();

            // Set the password as being expired
            userAccount.PasswordLastChanged = DateTime.UtcNow.AddDays(-1 * (maximumPasswordAge + 1));
            userAccount.Save();

            if (skipExpiryCheck || neverExpires)
            {
                UserAccountValidator.Authenticate(userAccount.Name, password, RequestContext.GetContext().Tenant.Name, false, skipExpiryCheck);
            }
            else
            {
                Assert.That(
                    () => UserAccountValidator.Authenticate(userAccount.Name, password, RequestContext.GetContext().Tenant.Name, false, skipExpiryCheck),
                    Throws.TypeOf <PasswordExpiredException>());
            }
        }
        public void Authenticate_OK()
        {
            const string password    = "******";
            UserAccount  userAccount = null;

            userAccount = new UserAccount();

            userAccount.Name = "Test user " + Guid.NewGuid();
            userAccount.AccountStatus_Enum = UserAccountStatusEnum_Enumeration.Active;
            userAccount.Password           = password;
            userAccount.Save();

            Assert.That(
                () => UserAccountValidator.Authenticate(userAccount.Name, password, RequestContext.GetContext().Tenant.Name, false),
                Throws.Nothing);

            userAccount = Entity.Get <UserAccount>(userAccount.Id);

            // Not updating LastLogin for now
            //Assert.That(
            //    userAccount.LastLogon,
            //    Is.EqualTo(DateTime.UtcNow).Within(TimeSpan.FromSeconds(5)));
            Assert.That(
                userAccount.AccountStatus_Enum,
                Is.EqualTo(UserAccountStatusEnum_Enumeration.Active));
            Assert.That(
                userAccount.BadLogonCount,
                Is.Null.Or.EqualTo(0));
        }
 public void Authenticate_PasswordLength(int passwordLengthAdjustment, bool expectPasswordTooLongException)
 {
     Assert.That(
         () => UserAccountValidator.Authenticate("Administrator", "a".PadLeft(UserAccountValidator.MaxPasswordLength + passwordLengthAdjustment), "edc", false),
         expectPasswordTooLongException
             ? (Constraint)Throws.TypeOf <InvalidCredentialException>().And.Property("Message").StartsWith("Password cannot be longer than")
             : Throws.TypeOf <InvalidCredentialException>().And.Property("Message").EqualTo(UserAccountValidator.InvalidUserNameOrPasswordMessage));
 }
示例#6
0
 public UserManagementService(
     IUserContext applicationContext,
     IUserAccountRepository userAccountRepository,
     ICryptographicService cryptographicService,
     IQueueDispatcher <IMessage> dispatcher) : base(applicationContext, dispatcher)
 {
     Check.NotNull(userAccountRepository, "userAccountRepository cannot be null");
     _userAccountRepository = userAccountRepository;
     _cryptographicService  = cryptographicService;
     _userAccountValidator  = new UserAccountValidator(_userAccountRepository);
 }
        public void Authenticate_BadUsername()
        {
            const string username = "******";
            const string password = "******";

            Assert.That(Entity.GetByField <UserAccount>(username, new EntityRef("core:name")),
                        Is.Empty, "User name exists");

            Assert.That(
                () => UserAccountValidator.Authenticate(username, password, RequestContext.GetContext().Tenant.Name, false),
                Throws.TypeOf <InvalidCredentialException>());
        }
        public UserManagementService(
			IUserContext applicationContext,
			IRepositorySessionFactory repositorySessionFactory,
			IUserAccountRepository userAccountRepository,
			ICryptographicService cryptographicService,
			IQueueDispatcher<IMessage> dispatcher)
            : base(applicationContext, repositorySessionFactory, dispatcher)
        {
            Check.NotNull(userAccountRepository, "userAccountRepository cannot be null");
            _userAccountRepository = userAccountRepository;
            _cryptographicService = cryptographicService;
            _userAccountValidator = new UserAccountValidator(_userAccountRepository);
        }
        public void Should_FailValidation_When_UsernameContainsSpecialCharacters()
        {
            // Arrange
            var userAccountValidator = new UserAccountValidator();
            var userAccount          = new UserAccount(username: "******", password: "******", isActive: true, isFirstTimeUser: false, roleType: "public");

            // Act
            var result  = userAccountValidator.Validate(userAccount, ruleSet: "CreateUser");
            var isValid = result.IsValid;

            // Assert
            isValid.Should().Be(false);
        }
        public void Should_FailValidation_When_PasswordIsEmpty()
        {
            // Arrange
            var userAccountValidator = new UserAccountValidator();
            var userAccount          = new UserAccount(username: "******", password: "", isActive: true, isFirstTimeUser: false, roleType: "public");

            // Act
            var result  = userAccountValidator.Validate(userAccount, ruleSet: "CreateUser");
            var isValid = result.IsValid;

            // Assert
            isValid.Should().Be(false);
        }
        public void Should_FailSsoValidation_When_UsernameIsEmpty()
        {
            // Arrange
            var userAccountValidator = new UserAccountValidator();
            var userAccount          = new UserAccount(username: "", password: "******", isActive: false, isFirstTimeUser: false, roleType: "public");

            // Act
            var result  = userAccountValidator.Validate(userAccount, ruleSet: "SsoRegistration");
            var isValid = result.IsValid;

            // Assert
            result.IsValid.Should().BeFalse();
            isValid.Should().Be(false);
        }
示例#12
0
        static void Main(string[] args)
        {
            var userAccount = new UserAccount
            {
                FirstName         = "",
                Username          = "******",
                EmailAddress      = "hello_simongilbert.net",
                MobilePhoneNumber = "07890123456",
                DateOfBirth       = new DateTime(2019, 11, 24),
            };

            var validator = new UserAccountValidator();

            validator.ValidateAndThrow(userAccount);
        }
        public void Authenticate_BadPassword()
        {
            const string password = "******";
            UserAccount  userAccount;

            userAccount      = new UserAccount();
            userAccount.Name = "Test user " + Guid.NewGuid();
            userAccount.AccountStatus_Enum = UserAccountStatusEnum_Enumeration.Active;
            userAccount.Password           = password;
            userAccount.Save();

            Assert.That(
                () => UserAccountValidator.Authenticate(userAccount.Name, password + "_", RequestContext.GetContext().Tenant.Name, false),
                Throws.TypeOf <InvalidCredentialException>());
        }
    public static void ChangePassword(string oldPassword,
                                      string newPassword,
                                      int userId,
                                      Func <int, UserAccount> getUserAccountById,
                                      Action <string> setPasswordForUserId)
    {
        var userAccount = getUserAccountById(userId);

        // any validator can throw exception if validation fails
        UserAccountValidator.IsEnabled(userAccount);
        UserAccountValidator.PasswordMatches(userAccount, oldPassword);
        PasswordValidator.IsStrongEnough(newPassword);

        setPasswordForUserId(newPassword, userId);
    }
示例#15
0
        public IHttpActionResult Challenge([FromUri] string clientVersion = null)
        {
            try
            {
                UserAccountValidator.Challenge();

                return(Ok());
            }
            catch
            {
                EventLog.Application.WriteWarning("Failed Challenge.");
            }


            return(Unauthorized());
        }
        static void Main(string[] args)
        {
            UserAccount userAccount = UserAccountDataCapture.CaptureFirstName();

            userAccount = UserAccountDataCapture.CaptureLastName();

            bool isUserAccountValid = UserAccountValidator.Validate(userAccount);

            if (!isUserAccountValid)
            {
                StandardMessages.EndApplication();
                return;
            }

            AccountGenerator.CreateAccount(userAccount);
            StandardMessages.EndApplication();
        }
        public void User_Account_Is_Valid()
        {
            var expectedIsValid = true;

            var viewModel = new UserAccountViewModel
            {
                FirstName         = "Simon",
                Username          = "******",
                EmailAddress      = "*****@*****.**",
                MobilePhoneNumber = "+447890123456",
            };

            var validator = new UserAccountValidator();

            var validationResult = validator.Validate(viewModel);

            Assert.Equal(expectedIsValid, validationResult.IsValid);
        }
        public void User_Account_Is_Valid()
        {
            var expectedIsValid = true;

            var userAccount = new UserAccount
            {
                FirstName         = "Simon",
                Username          = "******",
                EmailAddress      = "*****@*****.**",
                MobilePhoneNumber = "+447890123456",
                DateOfBirth       = new DateTime(1987, 11, 24),
            };

            var validator = new UserAccountValidator();

            var validationResult = validator.Validate(userAccount);

            Assert.Equal(expectedIsValid, validationResult.IsValid);
        }
        public void User_Account_Is_Not_Valid()
        {
            var expectedIsValid = false;

            var userAccount = new UserAccount
            {
                FirstName         = "",
                Username          = "******",
                EmailAddress      = "hello_simongilbert.net",
                MobilePhoneNumber = "07890123456",
                DateOfBirth       = new DateTime(2019, 11, 24),
            };

            var validator = new UserAccountValidator();

            var validationResult = validator.Validate(userAccount);

            Assert.Equal(expectedIsValid, validationResult.IsValid);
        }
        public void ValidateAccountStatus(string accountStatus, Type exceptionType)
        {
            UserAccount userAccount;
            var         status = ( UserAccountStatusEnum_Enumeration )Enum.Parse(typeof(UserAccountStatusEnum_Enumeration), accountStatus);

            userAccount      = new UserAccount( );
            userAccount.Name = "Test user " + Guid.NewGuid( );
            userAccount.AccountStatus_Enum = status;
            userAccount.Password           = "******";
            userAccount.Save( );

            if (exceptionType == null)
            {
                UserAccountValidator.ValidateAccountStatus(userAccount, false);
            }
            else
            {
                Assert.Throws(exceptionType, () => UserAccountValidator.ValidateAccountStatus(userAccount, false));
            }
        }
示例#21
0
        /// <summary>
        /// Determine the user account associated with this API key.
        /// Return null if the user account is invalid.
        /// </summary>
        /// <param name="apiKey">The API key</param>
        /// <returns>The user account, or null if the user account is somehow unavailable or locked.</returns>
        private UserAccount GetValidUserAccount(ApiKey apiKey)
        {
            // Get the user account
            UserAccount userAccount = apiKey.ApiKeyUserAccount;

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

            // Validate the account status
            try
            {
                UserAccountValidator.ValidateAccountStatus(userAccount, true);
            }
            catch (AuthenticationException) // note: there are various types that derive from this
            {
                return(null);
            }

            return(userAccount);
        }
        public void Authenticate_DisabledTenant()
        {
            const string password = "******";
            UserAccount  userAccount;
            Tenant       tenant;
            long         tenantId;

            userAccount      = new UserAccount();
            userAccount.Name = "Test user " + Guid.NewGuid();
            userAccount.AccountStatus_Enum = UserAccountStatusEnum_Enumeration.Active;
            userAccount.Password           = password;
            userAccount.Save();

            tenantId = RequestContext.GetContext().Tenant.Id;
            try
            {
                RequestContext.SetSystemAdministratorContext();

                tenant = Entity.Get <Tenant>(tenantId, true);
                tenant.IsTenantDisabled = true;
                tenant.Save();

                RequestContext.SetTenantAdministratorContext("EDC");

                Assert.That(
                    () => UserAccountValidator.Authenticate(userAccount.Name, password, RequestContext.GetContext().Tenant.Name, false),
                    Throws.TypeOf <TenantDisabledException>());
            }
            finally
            {
                RequestContext.SetSystemAdministratorContext();

                tenant = Entity.Get <Tenant>(tenantId, true);
                tenant.IsTenantDisabled = false;
                tenant.Save();

                RequestContext.SetTenantAdministratorContext("EDC");
            }
        }
示例#23
0
        /// <summary>
        /// Validates the specified username and password.
        /// </summary>
        /// <param name="username">
        /// A string containing the username of the account to to validate.
        /// </param>
        /// <param name="password">
        /// A string containing the password of the account to validate.
        /// </param>
        public override void Validate(string username, string password)
        {
            if (String.IsNullOrEmpty(username))
            {
                throw new ArgumentException("The specified username parameter is invalid.");
            }

            string tenant = string.Empty;

            // Split the tenant and username fields
            string[] credentials = username.Split(new char[] { '\\' }, StringSplitOptions.RemoveEmptyEntries);
            if (credentials.Length > 1)
            {
                tenant   = credentials[0];
                username = credentials[1];
            }

            // Validate the credentials
            // Don't store the credentials in the thread context.
            // This is due to the fact that the validator may operate on a different
            // thread than the actual service code.
            UserAccountValidator.Validate(username, password, tenant, false);
        }
 public void Authenticate_EmptyTenant()
 {
     Assert.That(() => UserAccountValidator.Authenticate("username", "password", "", false),
                 Throws.TypeOf <ArgumentNullException>().And.Property("ParamName").EqualTo("tenant"));
 }
示例#25
0
        /// <summary>
        ///     Signs a software platform user into the system.
        /// </summary>
        /// <param name="jsonLoginCredential">The json login credential.</param>
        /// <returns></returns>
        private HttpResponseMessage <LoginResult> SigninSoftwarePlatform(JsonLoginCredential jsonLoginCredential)
        {
            var userAgent = Request?.Headers?.UserAgent?.ToString();

            try
            {
                using (new SecurityBypassContext( ))
                {
                    try
                    {
                        UserAccountValidator.Authenticate(jsonLoginCredential.Username, jsonLoginCredential.Password,
                                                          jsonLoginCredential.Tenant, true);
                    }
                    catch (ArgumentException ex)
                    {
                        throw new InvalidCredentialException("Invalid user name, password or tenant", ex);
                    }

                    RequestContext     context = ReadiNow.IO.RequestContext.GetContext( );
                    RequestContextData contextData;

                    UserAccount account = ReadiNow.Model.Entity.Get <UserAccount>(context.Identity.Id, true);

                    if (account != null)
                    {
                        /////
                        // If we are in integration test mode, update the test authorization info.
                        /////
                        if (TestAuthorization.IsEnabled)
                        {
                            TestAuthorization.Instance.SetTokenIdentifier(context.Tenant.Id, WellKnownAliases.CurrentTenant.ReadiNowIdentityProviderInstance, account.Name);
                        }

                        // Update cache
                        contextData = Factory.IdentityProviderRequestContextCache.GetRequestContextData(ReadiNow.IO.RequestContext.TenantId, WellKnownAliases.CurrentTenant.ReadiNowIdentityProviderInstance, jsonLoginCredential.Username, true);
                    }
                    else
                    {
                        throw new InvalidOperationException("No UserAccount found.");
                    }

                    ReadiNowIdentityProvider identityProvider = ReadiNow.Model.Entity.Get <ReadiNowIdentityProvider>(WellKnownAliases.CurrentTenant.ReadiNowIdentityProviderInstance);

                    if (!(identityProvider.IsProviderEnabled ?? true))
                    {
                        throw new AuthenticationException("The identity provider is not enabled.");
                    }

                    contextData.Identity.IdentityProviderTypeAlias = LoginConstants.ReadiNowIdentityProviderTypeAlias;

                    CookieHelper.CreateAuthenticationAndXsrfCookies(ReadiNow.IO.RequestContext.TenantId, WellKnownAliases.CurrentTenant.ReadiNowIdentityProviderInstance, jsonLoginCredential.Username, account.Id, jsonLoginCredential.Persistent);

                    AuditLogInstance.Get().OnLogon(true, jsonLoginCredential.Username, userAgent);

                    return(new HttpResponseMessage <LoginResult>(GetSuccessfulLoginResult(contextData, account.Id), HttpStatusCode.OK));
                }
            }
            catch (Exception exc)
            {
                if (ReadiNow.IO.RequestContext.IsSet)
                {
                    AuditLogInstance.Get().OnLogon(false, jsonLoginCredential.Username, userAgent);
                }

                EventLog.Application.WriteWarning("Software Platform login error. Username: {0}, Tenant: {1}. {2}", jsonLoginCredential.Username ?? "<null>", jsonLoginCredential.Tenant ?? "<null>", exc.Message);

                throw;  // rely on the ExceptionFilter to handle it.
            }
        }
 public void Validate_NullPassword()
 {
     Assert.That(() => UserAccountValidator.Validate("username", null, "tenant", false),
                 Throws.TypeOf <ArgumentNullException>().And.Property("ParamName").EqualTo("password"));
 }