private void AuthenticateUser(AuthorizationContext filterContext)
 {
     if (!filterContext.HttpContext.Request.FilePath.Equals("/Account/Login"))
     {
         filterContext.Result = new RedirectToRouteResult("Default", new RouteValueDictionary { { "action", "Login" }, { "controller", "Account" } });
     }
     UserEntity = null;
 }
        public void GivenFirstNameSearchCriteria_AndUserNamePartiallyMatches_WhenInvokeFilterPredicate_ThenReturnTrue()
        {
            User user = new User { FirstName = "Alec" };
            MockRequest.Expect(m => m["firstName"]).Return("Ale");
            var target = new UserClientDataTable(MockRequest, SecurityConfiguration);

            Assert.IsTrue(target.FilterPredicate.Compile().Invoke(user));
        }
        public void GivenAUser_WhenAdd_ThenAddToContext()
        {
            var expected = new User { Id = 1 };

            Target.Add(expected);

            MockDbSet.AssertWasCalled(m => m.Add(expected));
        }
        public void GivenAUser_WhenUpdate_ThenContextSetsModified()
        {
            var expected = new User { Id = 1 };

            Target.Update(expected);

            MockContext.AssertWasCalled(m => m.SetModified(expected));
        }
        public void GivenLastNameSearchCriteria_AndUserNameDoesntPartiallyMatch_WhenInvokeFilterPredicate_ThenReturnFalse()
        {
            User user = new User { LastName = "Deitz" };
            MockRequest.Expect(m => m["lastName"]).Return("xyz");
            var target = new UserClientDataTable(MockRequest, SecurityConfiguration);

            Assert.IsFalse(target.FilterPredicate.Compile().Invoke(user));
        }
        public void GivenEmailSearchCriteria_AndUserEmailPartiallyMatches_WhenInvokeFilterPredicate_ThenReturnTrue()
        {
            User user = new User { EmailAddress = "*****@*****.**" };
            MockRequest.Expect(m => m["email"]).Return("Dei");
            var target = new UserClientDataTable(MockRequest, SecurityConfiguration);

            Assert.IsTrue(target.FilterPredicate.Compile().Invoke(user));
        }
        public void GivenUserAlreadyHasPendingEmail_AndUserAlreadyHasConfirmationGuid_AndViewModelPendingEmailIsEmpty_WhenICopyToDomainEntity_ThenPendingEmailIsNull_AndConfirmationGuidIsEmpty()
        {
            User destination = new User { PendingEmail = "*****@*****.**", ConfirmationGuid = Guid.NewGuid() };
            InitializeTargetState(string.Empty);

            Target.CopyTo(destination);

            Assert.IsNull(destination.PendingEmail);
            Assert.AreEqual(Guid.Empty, destination.ConfirmationGuid);
        }
        public void GivenAnAssociatedServiceOfferingAndUser_WhenAddLink_ThenTheyAreAssociated()
        {
            ServiceOffering serviceOffering = new ServiceOffering();
            User user = new User();

            Target.AddLink(serviceOffering, user);

            CollectionAssert.Contains(serviceOffering.UsersLinkingAsFavorite.ToList(), user);
            CollectionAssert.Contains(user.FavoriteServiceOfferings.ToList(), serviceOffering);
        }
 public void Process(User user)
 {
     if (user == null)
     {
         throw new ArgumentNullException("user");
     }
     user.EmailAddress = user.PendingEmail;
     user.PendingEmail = null;
     user.ConfirmationGuid = Guid.Empty;
 }
        public void GivenNullPendingEmail_WhenCopyFrom_ThenPendingEmailSetToCurrentEmail()
        {
            User source = new User
            {
                EmailAddress = "*****@*****.**"
            };

            Target.CopyFrom(source);

            Assert.AreEqual(source.EmailAddress, Target.PendingEmail);
        }
        public void GivenAnAssociatedUserAndServiceOffering_WhenDeleteLink_ThenTheyAreNoLongerAssociated()
        {
            ServiceOffering serviceOffering = new ServiceOffering();
            User user = new User { FavoriteServiceOfferings = new List<ServiceOffering> { serviceOffering } };
            serviceOffering.UsersLinkingAsFavorite.Add(user);

            Target.DeleteLink(serviceOffering, user);

            CollectionAssert.DoesNotContain(serviceOffering.UsersLinkingAsFavorite.ToList(), user);
            CollectionAssert.DoesNotContain(user.FavoriteServiceOfferings.ToList(), serviceOffering);
        }
        public void GivenUserAlreadyHasPendingEmail_AndUserAlreadyHasConfirmationGuid_AndViewModelPendingEmailDiffers_WhenICopyToDomainEntity_ThenPendingEmailAndConfirmationGuidUpdate()
        {
            Guid notExpectedConfirmationGuid = Guid.NewGuid();
            User destination = new User { PendingEmail = "*****@*****.**", ConfirmationGuid = notExpectedConfirmationGuid };
            InitializeTargetState("*****@*****.**");

            Target.CopyTo(destination);

            Assert.AreEqual("*****@*****.**", destination.PendingEmail);
            Assert.AreNotEqual(notExpectedConfirmationGuid, destination.ConfirmationGuid);
        }
        public void GivenAuditOnMapCalled_AndClaimsPrincipalMatches_WhenAuthorizing_ThenCallAuditLoginOnAccountManager()
        {
            User expectedUserEntity = new User { UserKey = "whatever" };
            AuthorizationContext filterContext = CreateAuthorizationContextWithExpectations(expectedUserEntity.UserKey, expectedUserEntity);
            UserIdentityMapAttribute.AuditOnMap(expectedUserEntity.UserKey);

            Target.OnAuthorization(filterContext);

            EducationSecurityPrincipal actual = MockHttpContext.User as EducationSecurityPrincipal;
            MockAccountManager.AssertWasCalled(m => m.AuditLogin(actual));
        }
        public void GivenActionInvokedIsAccountLogOff_AndUserIsNotAnEducationSecurityPrincipal_AndEulaNotAccepted_WhenAuthorizing_ThenSucceed()
        {
            User expectedUserEntity = new User { UserKey = "whatever" };
            MockHttpContext.User = CreateClaimsPrincipal(expectedUserEntity.UserKey);
            AuthorizationContext filterContext = ControllerContextFactory.CreateAuthorizationContext(MockHttpContextBase, typeof(AccountController), "LogOff");
            System.Security.Claims.ClaimsPrincipal claimsPrincipal = MockHttpContext.User as System.Security.Claims.ClaimsPrincipal;
            filterContext.HttpContext.User = claimsPrincipal;
            MockAccountManager.Expect(m => m.EnsureUserEntity((System.Security.Claims.ClaimsIdentity)claimsPrincipal.Identity)).Throw(new LicenseAgreementException());

            Target.OnAuthorization(filterContext);
        }
        public void GivenAValidUser_WhenIProcess_ThenUserEntityUpdated()
        {
            string expectedEmailAddress = "*****@*****.**";
            User user = new User { EmailAddress = "*****@*****.**", PendingEmail = expectedEmailAddress, ConfirmationGuid = Guid.NewGuid() };

            Target.Process(user);

            Assert.AreEqual(expectedEmailAddress, user.EmailAddress);
            Assert.IsNull(user.PendingEmail);
            Assert.AreEqual(Guid.Empty, user.ConfirmationGuid);
        }
 public LoginEvent CreateLoginEvent(User user)
 {
     if (user == null)
     {
         throw new ArgumentNullException("user");
     }
     return new LoginEvent
     {
         CreatingUser = user,
         CreatingUserId = user.Id
     };
 }
 public void CopyFrom(User model)
 {
     if (model == null)
     {
         throw new ArgumentNullException("model");
     }
     UserId = model.Id;
     Comments = model.Comments;
     SelectedSchoolIds = model.UserRoles.SelectMany(u => u.Schools).Select(s => s.Id);
     SelectedProviderIds = model.UserRoles.SelectMany(u => u.Providers).Select(p => p.Id);
     Name = string.Format(CultureInfo.CurrentCulture, "{0}, {1}", model.LastName, model.FirstName);
 }
 public static bool IsAdministrator(User userEntity, ISecurityConfiguration configuration)
 {
     if (userEntity == null)
     {
         throw new ArgumentNullException("userEntity");
     }
     if (configuration == null)
     {
         throw new ArgumentNullException("configuration");
     }
     return configuration.AdministratorEmailAddresses.Contains(userEntity.EmailAddress, StringComparer.OrdinalIgnoreCase);
 }
 public EducationSecurityIdentity(ClaimsIdentity baseIdentity, User userEntity)
 {
     if (baseIdentity == null)
     {
         throw new ArgumentNullException("baseIdentity");
     }
     if (userEntity == null)
     {
         throw new ArgumentNullException("userEntity");
     }
     BaseIdentity = baseIdentity;
     UserEntity = userEntity;
 }
        public void GivenUserAlreadyHasEmailAddress_AndViewModelEmailAddressDifferent_WhenICopyToDomainEntity_ThenDomainEntityContainsState_AndEmailAddressUnchanged()
        {
            string expectedEmailAddress = "*****@*****.**";
            User destination = new User { EmailAddress = expectedEmailAddress };
            InitializeTargetState("*****@*****.**");

            Target.CopyTo(destination);

            Assert.AreEqual(Target.DisplayName, destination.DisplayName);
            Assert.AreEqual(expectedEmailAddress, destination.EmailAddress); // NOTE: Email address is read-only from view model
            Assert.AreEqual(Target.PendingEmail, destination.PendingEmail);
            Assert.AreEqual(Target.UserKey, destination.UserKey);
        }
 public void DeleteLink(ServiceOffering serviceOffering, User user)
 {
     if (serviceOffering == null)
     {
         throw new ArgumentNullException("serviceOffering");
     }
     if (user == null)
     {
         throw new ArgumentNullException("user");
     }
     serviceOffering.UsersLinkingAsFavorite.Remove(user);
     user.FavoriteServiceOfferings.Remove(serviceOffering);
 }
 public EducationSecurityPrincipal(User userEntity)
 {
     if (userEntity == null)
     {
         throw new ArgumentNullException("userEntity");
     }
     if (userEntity.UserKey == null)
     {
         throw new ArgumentException("UserKey property cannot be null.", "userEntity");
     }
     Claim claim = new Claim(ClaimTypes.NameIdentifier, userEntity.UserKey);
     Identity = new EducationSecurityIdentity(new ClaimsIdentity(new List<Claim> { claim }, "Custom"), userEntity);
     Configuration = new DefaultSecurityConfiguration();
 }
        public void GivenAValidUser_WhenIRequest_ThenSentMessageContainsGuidBothHtmlAndPlainContentTypes()
        {
            User expectedState = new User { PendingEmail = "*****@*****.**", ConfirmationGuid = Guid.NewGuid() };
            bool wasCalled = false;
            MockMailer.Expect(m => m.Send(Arg<MailMessage>.Is.NotNull)).Do(new Action<MailMessage>(e =>
            {
                AssertMailMessage(expectedState, e);
                wasCalled = true;
            }));

            Target.Request(expectedState, new Uri("http://tempuri.org"));

            Assert.IsTrue(wasCalled);
        }
        public void GivenAuditOnMapCalled_AndClaimsPrincipalMatches_AndUserAuthorized_WhenAuthorizing_ThenDoNotRepeatCallToAuditLoginOnAccountManager()
        {
            User expectedUserEntity = new User { UserKey = "whatever" };
            AuthorizationContext filterContext = CreateAuthorizationContextWithExpectations(expectedUserEntity.UserKey, expectedUserEntity);
            System.Security.Claims.ClaimsPrincipal claimsPrincipal = MockHttpContext.User as System.Security.Claims.ClaimsPrincipal;
            UserIdentityMapAttribute.AuditOnMap(expectedUserEntity.UserKey);
            Target.OnAuthorization(filterContext);
            filterContext.HttpContext.User = claimsPrincipal;

            Target.OnAuthorization(filterContext);

            EducationSecurityPrincipal actual = MockHttpContext.User as EducationSecurityPrincipal;
            MockAccountManager.AssertWasCalled(m => m.AuditLogin(null), o => o.IgnoreArguments().Repeat.Once());
        }
        public void GivenLoginEvents_WhenGetLastLoginTime_ThenLatestTime()
        {
            DateTime? expected = DateTime.Now;
            User target = new User
            {
                LoginEvents = new List<LoginEvent>
                {
                    new LoginEvent { CreateTime = DateTime.Now.AddDays(-1) },
                    new LoginEvent { CreateTime = DateTime.Now.AddDays(-3) },
                    new LoginEvent { CreateTime = expected.Value },
                    new LoginEvent { CreateTime = DateTime.Now.AddDays(-2) }
                }
            };

            Assert.AreEqual(expected, target.LastLoginTime);
        }
 public PrivateHealthDataViewEvent CreatePrivateHealthInfoViewEvent(User user, List<CustomFieldValue> viewedValues)
 {
     if (user == null)
     {
         throw new ArgumentNullException("user");
     }
     if (viewedValues == null)
     {
         throw new ArgumentNullException("viewedValues");
     }
     return new PrivateHealthDataViewEvent
     {
         CreatingUser = user,
         CreatingUserId = user.Id,
         PhiValuesViewed = viewedValues
     };
 }
 public void Request(User user, Uri confirmationEndpoint)
 {
     if (user == null)
     {
         throw new ArgumentNullException("user");
     }
     if (confirmationEndpoint == null)
     {
         throw new ArgumentNullException("confirmationEndpoint");
     }
     MailAddress address = new MailAddress(user.PendingEmail, user.DisplayName);
     using (MailMessage message = CreateMessage(address))
     {
         SetupMessageBody(confirmationEndpoint, user.ConfirmationGuid, message);
         Mailer.Send(message);
     }
 }
 public EducationSecurityPrincipal CreateUser(bool isAdministrator, IEnumerable<int> associatedSchoolIds)
 {
     User userEntity = new User { Id = 1, UserKey = "1" };
     EducationSecurityPrincipal user = new EducationSecurityPrincipal(userEntity);
     if (isAdministrator)
     {
         userEntity.UserRoles.Add(new UserRole { User = userEntity, UserId = userEntity.Id, Role = new Role { Name = SecurityRoles.DataAdmin, Id = 1 }, RoleId = 1 });
     }
     if (associatedSchoolIds != null)
     {
         UserRole siteCoordinatorRole = new UserRole { User = userEntity, UserId = userEntity.Id, Role = new Role { Name = SecurityRoles.SiteCoordinator, Id = 1 }, RoleId = 1 };
         userEntity.UserRoles.Add(siteCoordinatorRole);
         foreach (int id in associatedSchoolIds)
         {
             siteCoordinatorRole.Schools.Add(new School { Id = id });
         }
     }
     return user;
 }
 private static XElement BuildAccessXml(User user)
 {
     IEnumerable<UserRole> userRoles = user.UserRoles;
     if (userRoles.Any())
     {
         return
             new XElement(UserAccessChangeEvent.AccessXmlRootElement,
                 new XElement("roles", user.UserRoles.Select(ur => ur.Role).Select(r =>
                     new XElement("role", new XAttribute("id", r.Id), new XAttribute("name", r.Name)))
                 ),
                 new XElement("providers", user.UserRoles.SelectMany(ur => ur.Providers).Select(p =>
                     new XElement("provider", new XAttribute("id", p.Id), new XAttribute("name", p.Name)))
                 ),
                 new XElement("schools", user.UserRoles.SelectMany(ur => ur.Schools).Select(s =>
                     new XElement("school", new XAttribute("id", s.Id), new XAttribute("name", s.Name)))
                 )
             );
     }
     return null;
 }
 public UserAccessChangeEvent CreateAccessChangeEvent(User user, User requestor)
 {
     if (user == null)
     {
         throw new ArgumentNullException("user");
     }
     if (requestor == null)
     {
         throw new ArgumentNullException("requestor");
     }
     UserAccessChangeEvent log = new UserAccessChangeEvent
     {
         User = user,
         UserId = user.Id,
         UserActive = user.Active,
         CreatingUser = requestor,
         CreatingUserId = requestor.Id
     };
     log.AccessXml = BuildAccessXml(user);
     return log;
 }