public void Create(EulaModel viewModel, EducationSecurityPrincipal user)
 {
     if (viewModel == null)
     {
         throw new ArgumentNullException("viewModel");
     }
     if (user == null)
     {
         throw new ArgumentNullException("user");
     }
     if (!user.IsInRole(SecurityRoles.DataAdmin))
     {
         throw new EntityAccessUnauthorizedException("user");
     }
     EulaAgreement agreement = new EulaAgreement
     {
         CreateTime = DateTime.Now,
         CreatingUser = user.Identity.User
     };
     viewModel.CopyTo(agreement);
     EulaAgreementRepository.Add(agreement);
     EulaAcceptance acceptance = new EulaAcceptance
     {
         EulaAgreement = agreement,
         CreatingUserId = user.Identity.User.Id,
         CreateTime = DateTime.Now
     };
     if (user.Identity.User.EulaAcceptances == null)
     {
         user.Identity.User.EulaAcceptances = new List<EulaAcceptance>();
     }
     user.Identity.User.EulaAcceptances.Add(acceptance);
     UserRepository.Update(user.Identity.User);
     RepositoryContainer.Save();
 }
 public void GivenIdentity_WhenIGetIdentity_ThenIdentityMatchesOriginal()
 {
     EducationSecurityIdentity expected = new EducationSecurityIdentity(new ClaimsIdentity(), new User());
     EducationSecurityPrincipal target = new EducationSecurityPrincipal(expected);
     Assert.AreEqual(expected, target.Identity);
     Assert.AreEqual(expected, ((IPrincipal)target).Identity);
 }
 public void Create(EducationSecurityPrincipal user, ServiceRequestModel viewModel)
 {
     if (user == null)
     {
         throw new ArgumentNullException("user");
     }
     if (viewModel == null)
     {
         throw new ArgumentNullException("viewModel");
     }
     IPermission permission = PermissionFactory.Current.Create("CreateServiceRequest", StudentRepository.Items.Include(s => s.School.UserRoles).Where(s => viewModel.StudentIds.Contains(s.Id)));
     permission.GrantAccess(user);
     List<int> studentIds = viewModel.StudentIds.ToList();
     foreach (int studentId in studentIds)
     {
         ServiceRequest request = new ServiceRequest();
         viewModel.CopyTo(request);
         request.StudentId = studentId;
         request.CreatingUser = user.Identity.User;
         request.CreatingUserId = user.Identity.User.Id;
         CreateFulfillmentDetail(request, user, viewModel);
         ServiceRequestRepository.Add(request);
     }
     RepositoryContainer.Save();
 }
 public void Create(EducationSecurityPrincipal user, ServiceOfferingScheduleModel viewModel)
 {
     if (user == null)
     {
         throw new ArgumentNullException("user");
     }
     if (viewModel == null)
     {
         throw new ArgumentNullException("viewModel");
     }
     if (!ServiceOfferingRepository.Items.Any(s => s.Id == viewModel.ServiceOfferingId && s.IsActive))
     {
         throw new EntityNotFoundException("Selected Service Offering was not found.");
     }
     ServiceOffering offering = ServiceOfferingRepository.Items.Single(s => s.Id == viewModel.ServiceOfferingId && s.IsActive);
     IEnumerable<Student> students = StudentRepository.Items.Include(s => s.School).Where(s => viewModel.SelectedStudents.Contains(s.Id));
     IPermission permission = PermissionFactory.Current.Create("ScheduleOffering", students, offering);
     permission.GrantAccess(user);
     User userEntity = user.Identity.User;
     List<int> studentIds = viewModel.SelectedStudents.ToList();
     foreach (int studentId in studentIds)
     {
         var studentAssignedOffering = new StudentAssignedOffering
         {
             StudentId = studentId,
             CreatingUserId = userEntity.Id,
             IsActive = true
         };
         viewModel.CopyTo(studentAssignedOffering);
         StudentAssignedOfferingRepository.Add(studentAssignedOffering);
     }
     RepositoryContainer.Save();
 }
 private bool IsValidServiceOffering(EducationSecurityPrincipal user, int index, string studentSISId, Student student, DataTable dataTable, out DateTime? startDate, out DateTime? endDate, ServiceUploadModel model)
 {
     startDate = endDate = null;
     if (studentSISId == null || student == null)
     {
         ProcessError(dataTable.Rows[index], string.Format(CultureInfo.CurrentCulture, "Malformed Student Id on row {0}", index + 1), model);
         return false;
     }
     else if (!GrantUserAccessToSchedulingAnOffering(user, student))
     {
         ProcessError(dataTable.Rows[index], string.Format(CultureInfo.CurrentCulture, "You do not have permission to interact with the referenced student on row {0}", index + 1), model);
         return false;
     }
     else if (!ExcelUtility.TryGetOADate(dataTable.Rows[index][2].ToString(), out startDate))
     {
         ProcessError(dataTable.Rows[index], string.Format(CultureInfo.CurrentCulture, "Malformed Start Date on row {0}", index + 1), model);
         return false;
     }
     else if (!ExcelUtility.TryGetOADate(dataTable.Rows[index][3].ToString(), out endDate))
     {
         ProcessError(dataTable.Rows[index], string.Format(CultureInfo.CurrentCulture, "Malformed End Date on row {0}", index + 1), model);
         return false;
     }
     return true;
 }
        protected override void ProcessDataTable(EducationSecurityPrincipal user, DataTable dataTable, ServiceUploadModel model)
        {
            string studentSISId, subjectName;
            Subject subject = new Subject();
            int duration;
            DateTime? dateAttended;
            Student student;

            for (int i = StartRow; i < dataTable.Rows.Count; i++)
            {
                studentSISId = dataTable.Rows[i][1].ToString();
                subjectName = dataTable.Rows[i][3].ToString();
                student = StudentRepository.Items.Where(s => s.StudentSISId == studentSISId).SingleOrDefault();
                subject = RetrieveSubject(subjectName);
                if (IsValidServiceOffering(user, i, studentSISId, student, dataTable, out dateAttended, out duration, model, subject))
                {
                    string notes = dataTable.Rows[i][5].ToString();
                    var studentAssignedOffering = StudentAssignedOfferingRepository.Items.Where(s => s.StudentId == student.Id && s.ServiceOfferingId == model.ServiceOfferingId).FirstOrDefault();
                    if (studentAssignedOffering == null)
                    {
                        studentAssignedOffering = CreateNewStudentAssignedOffering(student, model, user);
                    }
                    Create(studentAssignedOffering, (DateTime)dateAttended, subject, duration, notes, user);
                    model.SuccessfulRowsCount++;
                }
                model.ProcessedRowCount++;
            }
        }
        public void GivenUserEntityWhenConstructed_WhenIGetIdentityUserEntity_ThenIdentityIsAuthenticated()
        {
            EducationSecurityPrincipal target = new EducationSecurityPrincipal(new User {
                UserKey = "2r2j289fj"
            });

            Assert.IsTrue(target.Identity.IsAuthenticated);
        }
        public void GivenUserEntityWhenConstructed_WhenIGetIdentityUserEntity_ThenIdentityHasCustomAuthenticationType()
        {
            EducationSecurityPrincipal target = new EducationSecurityPrincipal(new User {
                UserKey = "2r2j289fj"
            });

            Assert.AreEqual("Custom", target.Identity.AuthenticationType);
        }
        public void GivenIdentity_WhenIGetIdentity_ThenIdentityMatchesOriginal()
        {
            EducationSecurityIdentity  expected = new EducationSecurityIdentity(new ClaimsIdentity(), new User());
            EducationSecurityPrincipal target   = new EducationSecurityPrincipal(expected);

            Assert.AreEqual(expected, target.Identity);
            Assert.AreEqual(expected, ((IPrincipal)target).Identity);
        }
 public void GivenHttpWithCorrectPrincipalType_WhenIGetContextPrincipal_ThenPrincipalIsReturned()
 {
     EducationSecurityPrincipal expected = new EducationSecurityPrincipal(new User { UserKey = "sdklfjsw" });
     HttpContext.Current = new HttpContext(new HttpRequest("", "http://tempuri.org", ""), new HttpResponse(new StringWriter()));
     HttpContext.Current.User = expected;
     EducationSecurityPrincipal actual = AuthenticationUtility.GetHttpContextPrincipal();
     Assert.AreEqual(expected, actual);
 }
        public void GivenValidViewModel_AndUserIsNotAdministrator_AndUserIsNotCreator_WhenDelete_ThenThrowEntityAccessUnauthorizedException()
        {
            User nonAdminUserEntity = EducationContext.Users.Where(u => u.UserKey == "Fred").Include("UserRoles.Role").Single();
            EducationSecurityPrincipal nonAdminUser = new EducationSecurityPrincipal(nonAdminUserEntity);
            EducationContext.StudentAssignedOfferings.Single(a => a.Id == 4).IsActive = true;

            Target.ExpectException<EntityAccessUnauthorizedException>(() => Target.Delete(nonAdminUser, 4));
        }
 public void TestInitialize()
 {
     EducationContext = new EducationDataContext();
     Container = AssemblySetup.CreateWindsorContainer(EducationContext);
     RepositoryContainer repositoryContainer = new RepositoryContainer(Container, EducationContext);
     Target = new ServiceOfferingManager(repositoryContainer, new DataTableBinder());
     User = new EducationSecurityPrincipal(new UserRepository(EducationContext).Items.Where(s => s.UserKey == "Bob").Include("UserRoles.Role").Single());
 }
        public void GivenUserIsAdministrator_WhenGetAllowedList_ThenListIsReturned()
        {
            User currentUser = Context.Users.Where(u => u.Id == 2).Single();
            EducationSecurityPrincipal user = new EducationSecurityPrincipal(currentUser);

            var students = Target.GetAllowedList(user);

            Assert.IsNotNull(students);
        }
        public void GivenUserEntity_WhenIGetIdentity_ThenIdentityUserEntityMatches()
        {
            User expected = new User {
                UserKey = "2r2j289fj"
            };
            EducationSecurityPrincipal target = new EducationSecurityPrincipal(expected);

            Assert.AreEqual(expected, target.Identity.User);
        }
 public static IList<ServiceOffering> LoadFavorites(IServiceOfferingRepository repository, EducationSecurityPrincipal user)
 {
     var materializedServiceOfferings = repository.Items.
                                        Include(s => s.Provider).
                                        Include(s => s.ServiceType).
                                        Include(s => s.Program).
                                        Include(s => s.UsersLinkingAsFavorite);
     return materializedServiceOfferings.Where(s => s.UsersLinkingAsFavorite.Select(u => u.Id).Contains(user.Identity.User.Id) && s.IsActive).ToList();
 }
        public void GivenValidViewModel_AndUserIsNotAdministrator_AndUserIsNotCreator_WhenDelete_ThenThrowEntityAccessUnauthorizedException()
        {
            User nonAdminUserEntity = EducationContext.Users.Where(u => u.UserKey == "Fred").Include("UserRoles.Role").Single();
            EducationSecurityPrincipal nonAdminUser = new EducationSecurityPrincipal(nonAdminUserEntity);
            ServiceRequest newRequestToDelete = CreateServiceRequestInDatabase(2, 3);
            var viewModel = new ServiceRequestModel { Id = newRequestToDelete.Id, SelectedPriorityId = newRequestToDelete.PriorityId, SelectedServiceTypeId = newRequestToDelete.ServiceTypeId, SelectedSubjectId = newRequestToDelete.SubjectId, StudentIds = new int[] { newRequestToDelete.StudentId } };

            Target.ExpectException<EntityAccessUnauthorizedException>(() => Target.Delete(nonAdminUser, viewModel.Id));
        }
 public void BaseInitializeTest()
 {
     User = new EducationSecurityPrincipal(new User { UserKey = "whatever" });
     Data = new TestData();
     Repositories = new TestRepositories(Data);
     MockHttpContext = MockHttpContextFactory.Create();
     MockDataTableBinder = MockRepository.GenerateMock<IDataTableBinder>();
     PermissionFactory.SetCurrent(MockRepository.GenerateMock<IPermissionFactory>());
 }
        private static EducationSecurityPrincipal CreateTarget(string adminEmailAddress, User user)
        {
            ISecurityConfiguration config = MockRepository.GenerateMock <ISecurityConfiguration>();

            config.Expect(m => m.AdministratorEmailAddresses).Return(new string[] { adminEmailAddress });
            EducationSecurityPrincipal target = new EducationSecurityPrincipal(user);

            target.Configuration = config;
            return(target);
        }
 public IQueryable<Student> GetAllowedList(EducationSecurityPrincipal user)
 {
     if (user == null)
     {
         throw new ArgumentNullException("user");
     }
     var associatedSchoolsIds = user.Identity.User.UserRoles.SelectMany(ur => ur.Schools).Select(s => s.Id);
     var isAdministrator = user.IsInRole(SecurityRoles.DataAdmin);
     return Items.Where(s => isAdministrator || !s.HasParentalOptOut || associatedSchoolsIds.Contains(s.SchoolId));
 }
 private void Create(StudentAssignedOffering studentAssignedOffering, DateTime dateAttended, Subject subject, decimal duration, string notes, EducationSecurityPrincipal user)
 {
     var newAttendance = new ServiceAttendance();
     newAttendance.StudentAssignedOffering = studentAssignedOffering;
     newAttendance.DateAttended = dateAttended;
     newAttendance.Subject = subject;
     newAttendance.Duration = duration;
     newAttendance.Notes = notes;
     newAttendance.CreatingUser = user.Identity.User;
     ServiceAttendanceRepository.Add(newAttendance);
 }
        public void GivenClaimsPrincipal_AndIdentityHasNameIdentifierClaim_WhenGetUserKey_ThenGetNameIdentifierClaimValue()
        {
            string           expected  = "this is the user key";
            GenericIdentity  identity  = new GenericIdentity("whatever");
            GenericPrincipal principal = new GenericPrincipal(identity, null);

            identity.AddClaim(new Claim(ClaimTypes.NameIdentifier, expected));

            string actual = EducationSecurityPrincipal.FindUserKey(principal);

            Assert.AreEqual(expected, actual);
        }
        public void GivenSortOnFirstColumn_WhenGenerateDataTableResultViewModel_ThenSucceed()
        {
            DataTableRequestModel model = new DataTableRequestModel { iDisplayLength = 10 };
            User userEntity = EducationContext.Users.First(u => u.UserRoles.Select(ur => ur.Role).Any(r => r.Name == SecurityRoles.DataAdmin));
            EducationSecurityPrincipal user = new EducationSecurityPrincipal(userEntity);
            HttpRequestBase mockRequest = MockHttpContextFactory.CreateRequest();
            mockRequest.Expect(m => m["iSortCol_0"]).Return("0");
            mockRequest.Expect(m => m["sSortDir_0"]).Return("asc");
            ServiceTypeClientDataTable dataTable = new ServiceTypeClientDataTable(mockRequest, user);

            Target.GenerateDataTableResultViewModel(model, dataTable);
        }
        public void GivenHttpWithCorrectPrincipalType_WhenIGetContextPrincipal_ThenPrincipalIsReturned()
        {
            EducationSecurityPrincipal expected = new EducationSecurityPrincipal(new User {
                UserKey = "sdklfjsw"
            });

            HttpContext.Current      = new HttpContext(new HttpRequest("", "http://tempuri.org", ""), new HttpResponse(new StringWriter()));
            HttpContext.Current.User = expected;
            EducationSecurityPrincipal actual = AuthenticationUtility.GetHttpContextPrincipal();

            Assert.AreEqual(expected, actual);
        }
        public void GivenNameCriteria_AndProviderNameMatches_WhenExecuteFilterPredicate_ThenReturnTrue()
        {
            EducationSecurityPrincipal user = new EducationSecurityPrincipal(new User { UserKey = "whatever" });
            Provider provider = new Provider
            {
                Name = "provider",
                IsActive = true
            };
            MockRequest.Expect(m => m["PartnerName"]).Return("pro");
            ProviderClientDataTable target = new ProviderClientDataTable(MockRequest, user);

            Assert.IsTrue(target.FilterPredicate.Compile().Invoke(provider));
        }
        public void GivenServiceTypeAssociationsWereMade_WhenEdit_ThenServiceTypeHasSelectedPrograms()
        {
            EducationSecurityPrincipal user = new EducationSecurityPrincipal(new UserRepository(EducationContext).Items.Where(s => s.UserKey == "Bob").Include("UserRoles.Role").Single());
            var selectedPrograms = new int[] { 1, 2 };
            var serviceType = EducationContext.ServiceTypes.Single(s => s.Id == 2);
            var expected = EducationContext.Programs.Where(s => selectedPrograms.Contains(s.Id)).ToList();
            var viewModel = new ServiceTypeModel { Id = serviceType.Id, Name = serviceType.Name, Description = serviceType.Description, SelectedPrograms = selectedPrograms };

            Target.Edit(viewModel);

            var actual = EducationContext.ServiceTypes.Single(s => s.Id == viewModel.Id).ServiceOfferings.Where(s => s.IsActive).Select(s => s.Program).Distinct();

            CollectionAssert.AreEquivalent(expected, actual.ToList());
        }
 private void CreateNewStudentAssignedOffering(Student student, ServiceUploadModel model, DateTime? startDate, DateTime? endDate, string notes, EducationSecurityPrincipal user)
 {
     var newOffering = new StudentAssignedOffering()
     {
         StudentId = student.Id,
         CreatingUser = user.Identity.User,
         ServiceOfferingId = model.ServiceOfferingId,
         StartDate = startDate,
         EndDate = endDate,
         Notes = notes,
         IsActive = true
     };
     StudentAssignedOfferingRepository.Add(newOffering);
 }
 private static EducationSecurityPrincipal CreateEducationSecurityPrincipal(AuthorizationContext filterContext, System.Security.Claims.ClaimsPrincipal claimsPrincipal)
 {
     System.Security.Claims.ClaimsIdentity claimsIdentity = (System.Security.Claims.ClaimsIdentity)claimsPrincipal.Identity;
     IAccountManager manager = DependencyResolver.Current.GetService<IAccountManager>();
     User userEntity = manager.EnsureUserEntity(claimsIdentity);
     EducationSecurityIdentity identity = new EducationSecurityIdentity(claimsIdentity, userEntity);
     EducationSecurityPrincipal principal = new EducationSecurityPrincipal(identity);
     if (_AuditOnMapCollection.Contains(userEntity.UserKey))
     {
         _AuditOnMapCollection.Remove(userEntity.UserKey);
         manager.AuditLogin(principal);
     }
     if (!(filterContext.RequestContext.RouteData.Values["action"].ToString() == "Index" && filterContext.RequestContext.RouteData.Values["controller"].ToString() == "Agreement"))
     {
         manager.ValidateEulaAccepted(principal.Identity.User);
     }
     return principal;
 }
 protected override void ProcessDataTable(EducationSecurityPrincipal user, DataTable dataTable, ServiceUploadModel model)
 {
     string studentSISId, notes;
     DateTime? startDate, endDate;
     Student student;
     for (int i = StartRow; i < dataTable.Rows.Count; i++)
     {
         studentSISId = dataTable.Rows[i][1].ToString();
         student = StudentRepository.Items.Where(s => s.StudentSISId == studentSISId).SingleOrDefault();
         if (IsValidServiceOffering(user, i, studentSISId, student, dataTable, out startDate, out endDate, model))
         {
             notes = dataTable.Rows[i][4].ToString();
             CreateNewStudentAssignedOffering(student, model, startDate, endDate, notes, user);
             model.SuccessfulRowsCount++;
         }
         model.ProcessedRowCount++;
     }
 }
 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;
 }
        public void GivenNameCriteria_AndProviderAssociatedWithProgramWithMatchingName_WhenExecuteFilterPredicate_ThenReturnTrue()
        {
            EducationSecurityPrincipal user = new EducationSecurityPrincipal(new User { UserKey = "whatever" });
            Provider provider = new Provider
            {
                Name = "not the search criteria",
                IsActive = true,
                ServiceOfferings = new List<ServiceOffering>
                {
                    new ServiceOffering
                    {
                        Program = new Program { Name = "contains bLah criteria" }
                    }
                }
            };
            MockRequest.Expect(m => m["PartnerName"]).Return("blah");
            ProviderClientDataTable target = new ProviderClientDataTable(MockRequest, user);

            Assert.IsTrue(target.FilterPredicate.Compile().Invoke(provider));
        }
 public void Create(ServiceAttendanceModel viewModel, EducationSecurityPrincipal user)
 {
     if (viewModel == null)
     {
         throw new ArgumentNullException("viewModel");
     }
     if (user == null)
     {
         throw new ArgumentNullException("user");
     }
     var studentAssignedOffering = StudentAssignedOfferingRepository.Items.Single(s => s.Id == viewModel.StudentAssignedOfferingId);
     IPermission permission = PermissionFactory.Current.Create("CreateServiceAttendance", studentAssignedOffering);
     permission.GrantAccess(user);
     ServiceAttendance serviceAttendance = new ServiceAttendance
     {
         CreatingUser = user.Identity.User
     };
     viewModel.CopyTo(serviceAttendance);
     ServiceAttendanceRepository.Add(serviceAttendance);
     RepositoryContainer.Save();
 }
        public void GivenProviderProgramAssociationsWereMade_WhenEdit_ThenProviderHasSelectedPrograms()
        {
            try
            {
                EducationSecurityPrincipal user = new EducationSecurityPrincipal(new UserRepository(EducationContext).Items.Where(s => s.UserKey == "Bob").Include("UserRoles.Role").Single());
                var expected = new int[] { 1, 2 };
                var provider = EducationContext.Providers.First();
                var viewModel = new ProviderModel { Id = provider.Id, Name = provider.Name, SelectedPrograms = expected, Address = provider.Address, Contact = provider.Contact, Website = provider.Website };

                Target.Edit(user, viewModel);

                using (EducationDataContext verificationContext = new EducationDataContext())
                {
                    var actual = verificationContext.Providers.Include(p => p.ServiceOfferings).Single(p => p.Id == viewModel.Id).ServiceOfferings.Where(s => s.IsActive).Select(s => s.ProgramId).Distinct();
                    CollectionAssert.AreEquivalent(expected, actual.ToList());
                }
            }
            finally
            {
                AssemblySetup.ForceDeleteEducationDatabase("SSD");
            }
        }
 public IEnumerable<object> MapData(StudentProfileExportFieldDescriptor fieldConfiguration, Student data, EducationSecurityPrincipal user, IUserAuditor auditor)
 {
     if (data == null)
     {
         throw new ArgumentNullException("data");
     }
     if (user == null)
     {
         throw new ArgumentNullException("user");
     }
     if (auditor == null)
     {
         throw new ArgumentNullException("auditor");
     }
     List<object> dataList = new List<object> { data.School.Name, data.Grade, data.FullName };
     IViewStudentDetailPermission permission = (IViewStudentDetailPermission)PermissionFactory.Current.Create("StudentProfileExportMapData", data);
     if(permission.TryGrantAccess(user))
     {
         if (!permission.CustomFieldOnly)
         {
             dataList.Add(data.StudentSISId);
         }
         MapStandardData(fieldConfiguration, data, dataList, permission.CustomFieldOnly);
         dataList.AddRange(fieldConfiguration.SelectedCustomFields.Select(f => FindLatestValue(data, f)).Select(v => v == null ? string.Empty : v.Value));
         var fields = fieldConfiguration.SelectedCustomFields.Select(f => FindLatestValue(data, f));
         if (fields.Where(f => f != null).ToList().Count() > 0)
         {
             user.Identity.User.PrivateHealthDataViewEvents.Add(auditor.CreatePrivateHealthInfoViewEvent(user.Identity.User, fields.Where(f => f != null).ToList()));
         }
         if (!permission.CustomFieldOnly)
         {
             dataList.AddRange(fieldConfiguration.SelectedServiceTypes.Select(serviceType => FindServicesOfferingNames(data, serviceType)));
         }
     }
     return dataList;
 }
 public void BaseInitializeTest()
 {
     User = new EducationSecurityPrincipal(new User { UserKey = "whatever" });
     MockHttpContext = MockHttpContextFactory.Create();
 }
        public void GivenUserEntityIsNotConfiguredAsAdministorator_WhenIQueryForIsInRole_ThenReturnFalse()
        {
            EducationSecurityPrincipal target = CreateTarget("Admin", "*****@*****.**", "*****@*****.**");

            Assert.IsFalse(target.IsInRole(SecurityRoles.Administrator));
        }
 public void GivenNullUserEntity_WhenCheckIsAdministrator_ThenThrowException()
 {
     TestExtensions.ExpectException <ArgumentNullException>(() => EducationSecurityPrincipal.IsAdministrator(null, MockRepository.GenerateMock <ISecurityConfiguration>()));
 }
        public void GivenHttpContextUserIsAlreadySet_WhenIAuthorize_ThenHttpContextUserReused()
        {
            string userKey = "whatever";
            EducationSecurityPrincipal expected = new EducationSecurityPrincipal(new User { UserKey = userKey });
            AuthorizationContext authorizationContext = CreateAuthorizationContext(false, userKey);
            authorizationContext.HttpContext.Request.Expect(m => m.FilePath).Return("hsdjkfhdkjhsfkjhdkjsf");
            authorizationContext.HttpContext.User = expected;

            Target.OnAuthorization(authorizationContext);

            Assert.AreSame(expected, authorizationContext.HttpContext.User);
        }
 private void EditRoles(User user, IEnumerable<int> PostedRoles, UserRoleModel viewModel, EducationSecurityPrincipal requestor)
 {
     var rolesToEdit = user.UserRoles.Select(u => u.RoleId).Intersect(PostedRoles).ToList();
     foreach (int roleId in rolesToEdit)
     {
         var role = RoleRepository.Items.Where(r => r.Id == roleId).SingleOrDefault();
         if (role != null)
         {
             var schools = GetSelectedSchools(viewModel.allSchoolsSelected, role, viewModel.SelectedSchoolIds).ToList();
             var providers = GetSelectedProviders(role, viewModel.SelectedProviderIds).ToList();
             var updatedUserRole = user.UserRoles.Where(u => u.RoleId == roleId).Single();
             var schoolsToRemove = updatedUserRole.Schools.Except(schools).ToArray();
             foreach (School school in schoolsToRemove)
             {
                 UserRoleRepository.DeleteLink(updatedUserRole, school);
             }
             var schoolsToAdd = schools.Except(updatedUserRole.Schools).ToList();
             foreach (School school in schoolsToAdd)
             {
                 UserRoleRepository.AddLink(updatedUserRole, school);
             }
             var providersToRemove = updatedUserRole.Providers.Except(providers).ToArray();
             foreach (Provider provider in providersToRemove)
             {
                 UserRoleRepository.DeleteLink(updatedUserRole, provider);
             }
             var providersToAdd = providers.Except(updatedUserRole.Providers).ToList();
             foreach (Provider provider in providersToAdd)
             {
                 UserRoleRepository.AddLink(updatedUserRole, provider);
             }
             updatedUserRole.LastModifyingUser = requestor.Identity.User;
             updatedUserRole.LastModifyTime = DateTime.Now;
             UserRoleRepository.Update(updatedUserRole);
         }
     }
 }
 private void AddRoles(User user, IEnumerable<int> PostedRoles, UserRoleModel viewModel, EducationSecurityPrincipal requestor)
 {
     var rolesToAdd = PostedRoles.Except(user.UserRoles.Select(u => u.RoleId)).ToList();
     foreach (int roleId in rolesToAdd)
     {
         var role = RoleRepository.Items.SingleOrDefault(r => r.Id == roleId);
         if (role != null)
         {
             var schools = GetSelectedSchools(viewModel.allSchoolsSelected, role, viewModel.SelectedSchoolIds).ToList();
             var providers = GetSelectedProviders(role, viewModel.SelectedProviderIds).ToList();
             var newUserRole = new UserRole
             {
                 RoleId = roleId,
                 UserId = viewModel.UserId,
                 CreatingUser = requestor.Identity.User
             };
             user.UserRoles.Add(newUserRole);
             UserRoleRepository.Add(newUserRole);
             foreach (School school in schools)
             {
                 UserRoleRepository.AddLink(newUserRole, school);
             }
             foreach (Provider provider in providers)
             {
                 UserRoleRepository.AddLink(newUserRole, provider);
             }
         }
     }
 }
 public void GivenNullSecurityConfiguration_WhenCheckIsAdministrator_ThenThrowException()
 {
     TestExtensions.ExpectException <ArgumentNullException>(() => EducationSecurityPrincipal.IsAdministrator(new User(), null));
 }
 public void GivenNullClaimsPrincipal_WhenGetUserKey_ThenThrowException()
 {
     TestExtensions.ExpectException <ArgumentNullException>(() => EducationSecurityPrincipal.FindUserKey(null));
 }
        public void GivenUserEntityWhenConstructed_AndUserDoesNotContainRole_WhenIQueryForIsInRole_ThenReturnFalse()
        {
            EducationSecurityPrincipal target = CreateTarget("NonAdmin", null, null);

            Assert.IsFalse(target.IsInRole("Admin"));
        }
        public void GivenUserEntityIsConfiguredAsAdministorator_AndCaseDoesNotMatch_WhenIQueryForIsInRole_ThenReturnTrue()
        {
            EducationSecurityPrincipal target = CreateTarget("Admin", "*****@*****.**", "*****@*****.**");

            Assert.IsTrue(target.IsInRole(SecurityRoles.Administrator));
        }