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_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>());
            }
        }
示例#4
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_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));
 }
        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 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 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");
            }
        }
 public void Authenticate_EmptyTenant()
 {
     Assert.That(() => UserAccountValidator.Authenticate("username", "password", "", false),
                 Throws.TypeOf <ArgumentNullException>().And.Property("ParamName").EqualTo("tenant"));
 }
示例#10
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.
            }
        }