public void Configuration(IAppBuilder app) { app.Use(typeof(AuthMiddleware)); UserContext.Initialize(); SimpleCache.Initialize(); RoleBuilder.Init(); }
private void BtnSave_Click(object sender, EventArgs e) { this.SetEnable(false); Privilege privilege = new Privilege { Name = CREATE_ROLE }; bool check = this.privilegeBLL.HasRolePrivilege(this.currentUser.UserName, privilege); if (check) { RoleBuilder builder = new RoleBuilder(this.TxtName.Text); if (this.TxtPassword.Text != null && this.TxtPassword.Text != "") { builder = builder.Password(this.TxtPassword.Text); } Role role = builder.Build(); Boolean rs = this.roleBLL.Add(role); if (rs) { MessageBox.Show(String.Join(" ", "Add role ", role.Name, "sucessfull!")); } else { MessageBox.Show(String.Join(" ", "Add role ", role.Name, "failed!")); } } else { MessageBox.Show(String.Join(" ", "You don't have ", CREATE_ROLE, "privilege!")); } this.SetEnable(true); }
/// <summary> /// You must have the CREATE ROLE system privilege. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void BtnSave_Click(object sender, EventArgs e) { Privilege privilege = new Privilege { Name = CREATE_ROLE }; bool check = this.privilegeBLL.HasRolePrivilege(this.currentUser.UserName, privilege); if (check) { RoleBuilder builder = new RoleBuilder(this.TxtName.Text); Role role = builder.Password(this.TxtPassword.Text).Build(); Boolean rs = this.roleBLL.Update(role); if (rs) { MessageBox.Show(String.Join(" ", "Save role ", role.Name, "sucessfull!")); } else { MessageBox.Show(String.Join(" ", "Cannot save role ", role.Name)); } } else { MessageBox.Show(String.Join(" ", "You don't have ", CREATE_ROLE, "privilege!")); } }
public async override Task Invoke(IOwinContext context) { string path = context.Request.Path.ToString().ToLower(); var user = UserContext.UserInfo; if (path.ToLower().StartsWith("/logout")) { await Next.Invoke(context); return; } if (user.AccountID <= 0) { if (!path.ToLower().StartsWith("/login".ToLower()) && !path.ToLower().StartsWith("/Unauthorize".ToLower())) { HttpContext.Current.Response.Redirect((context.Request.PathBase + "/Login").ToLower(), true); return; } } else { if (!RoleBuilder.GetAllowPath().Exists(x => x.ToLower() == path.ToLower()) && path != "/" && !path.ToLower().StartsWith("/Unauthorize".ToLower())) { HttpContext.Current.Response.Redirect((context.Request.PathBase + "/Unauthorize").ToLower(), true); return; } } await Next.Invoke(context); }
public RoleService(IUnitOfWork unitOfWork, RoleBuilder roleBuilder, RoleAdapter roleAdapter, RoleBusinessRules roleBusinessRules) { this.unitOfWork = unitOfWork; this.roleBuilder = roleBuilder; this.roleAdapter = roleAdapter; this.roleBusinessRules = roleBusinessRules; }
public void Build() { var result = RoleBuilder.CreateRole("Role1").AddPermission(new Permission("Permission1")).AddPermission(new Permission("Permission2")).Build(); Assert.IsNotNull(result); Assert.IsInstanceOfType(result, typeof(Role)); Assert.AreEqual("Role1", result.Name); Assert.AreEqual(2, result.Permissions.Count()); }
public async Task ExecuteShouldAddGroupClass() { //Arrange SchoolManagementContext context = new ContextBuilder().BuildClean(); GroupLevel groupLevel = new GroupLevelBuilder(context).With(x => x.Level = 1).With(x => x.Name = "Początkujący").BuildAndSave(); Room room = new RoomBuilder(context).WithName("Sala biała").BuildAndSave(); User anchor = new UserBuilder(context).WithEmail("*****@*****.**").BuildAndSave(); Role role = new RoleBuilder(context).WithName(Roles.Anchor).AddUserToRole(anchor).BuildAndSave(); List <User> participants = new List <User>(); var participantRoleBuilder = new RoleBuilder(context).WithName(Roles.Participant); for (var i = 0; i < 10; i++) { User user = new UserBuilder(context).WithEmail($"email{i}@gmail.com").BuildAndSave(); participants.Add(user); participantRoleBuilder.AddUserToRole(user); } participantRoleBuilder.BuildAndSave(); Command cmd = new Command { Name = "Groupa zajęciowa", Anchors = new List <string> { anchor.Id }, IsSolo = true, PassPrice = 200, ParticipantLimit = 20, GroupLevelId = groupLevel.Id, Participants = participants.Select(x => new ParticipantDto { Id = x.Id, Role = ParticipantRole.Leader }).ToList(), DayOfWeeks = new List <ClassDayOfWeekDto>(), RoomId = room.Id }; //Act DataResult result = await new Handler(context).Handle(cmd, CancellationToken.None); //Assert result .Should().NotBeNull(); result.Status.Should().Be(DataResult.ResultStatus.Success, "all parameters are corrected"); context.GroupClass.Should().NotBeEmpty("we add new group"); GroupClass groupClass = context.GroupClass.First(); groupClass.Anchors.Should().NotBeEmpty(); groupClass.Room.Should().Be(room); groupClass.GroupLevel.Should().Be(groupLevel); groupClass.PassPrice.Should().Be(cmd.PassPrice); groupClass.Participants.Should().NotBeEmpty().And.HaveCount(participants.Count).And .Contain(x => participants.Contains(x.User)); }
public void GetRoleById_GivenExistingForId_ShouldRole() { //---------------Set up test pack------------------- var roles = new RoleBuilder().WithRandomProps().Build(); var dbContext = new TestDbContextBuilder().WithRoles(roles).Build(); var repository = new RoleRepository(dbContext); //---------------Assert Precondition--------------- //---------------Execute Test ---------------------- var roleById = repository.GetRoleById(roles.Id); //---------------Test Result ----------------------- Assert.AreEqual(roles,roleById); }
public void GivenNoRolesWhenCreatingARoleWithoutAUniqueIdThenRoleIsValid() { var role = new RoleBuilder(this.Session) .WithName("Role") .Build(); Assert.True(role.ExistUniqueId); var validation = this.Session.Derive(false); Assert.False(validation.HasErrors); }
public void GivenNoRolesWhenCreatingARoleWithoutAUniqueIdThenRoleIsValid() { var role = new RoleBuilder(this.DatabaseSession) .WithName("Role") .Build(); Assert.IsTrue(role.ExistUniqueId); var derivationLog = this.DatabaseSession.Derive(); Assert.IsFalse(derivationLog.HasErrors); }
public List <ActiveRole> GetActiveRoles(int user) { try { return(RoleBuilder.GetRoles(user)); } catch (Exception ex) { NLogManager.PublishException(ex); } return(null); }
public void GetRoleById_GivenExistingForId_ShouldReturnRole() { //---------------Set up test pack------------------- var roles = new RoleBuilder().WithRandomProps().Build(); var dbContext = new TestDbContextBuilder().WithRoles(roles).Build(); var repository = new RoleRepository(dbContext); //---------------Assert Precondition--------------- //---------------Execute Test ---------------------- var roleById = repository.GetRoleById(roles.Id); //---------------Test Result ----------------------- Assert.AreEqual(roles, roleById); }
public void GetAllRoles_GivenOneRole_ShouldRole() { //---------------Set up test pack------------------- var role = new RoleBuilder().WithRandomProps().Build(); var dbContext = new TestDbContextBuilder().WithRoles(role).Build(); var repository = new RoleRepository(dbContext); //---------------Assert Precondition--------------- //---------------Execute Test ---------------------- var roles = repository.GetAllRoles(); //---------------Test Result ----------------------- Assert.AreEqual(1, roles.Count); var actual = roles.First(); Assert.AreSame(roles.FirstOrDefault(), actual); }
private IEnumerable <Roles> MockedRoleList() { var builder = new RoleBuilder(); List <Roles> roleList = new List <Roles> { builder.WithId(1).WithName("PAGE_1").Build(), builder.WithId(2).WithName("PAGE_2").Build(), builder.WithId(3).WithName("PAGE_3").Build(), builder.WithId(4).WithName("ADMIN").Build() }; return(roleList); }
public bool AddAccount(string username, string password) { try { SecurityDAO.AddAccount(username, Utilities.Encryption.Security.MD5Encrypt(password), UserContext.UserInfo.AccountID); RoleBuilder.Init(); return(true); } catch (Exception ex) { NLogManager.PublishException(ex); } return(false); }
public void GetAllRoles_GivenOneRole_ShouldReturnRole() { //---------------Set up test pack------------------- var role = new RoleBuilder().WithRandomProps().Build(); var dbContext = new TestDbContextBuilder().WithRoles(role).Build(); var repository = new RoleRepository(dbContext); //---------------Assert Precondition--------------- //---------------Execute Test ---------------------- var roles = repository.GetAllRoles(); //---------------Test Result ----------------------- Assert.AreEqual(1, roles.Count); var actual = roles.First(); Assert.AreSame(roles.FirstOrDefault(), actual); }
public override void SetUp() { base.SetUp(); var roleBuilder = new RoleBuilder(); var userBuidler = new UserBuilder(); roleBuilder.With(r => r.Name, PvPStatics.Permissions_Admin); roleBuilder.AddUser(userBuidler.Build()); roleBuilder.BuildAndSave(); user = userBuidler.BuildAndSave(); requestHandler = new UserHasRoleRequestHandler(DataContext); request = new UserHasAnyRoleRequest(); }
protected override void OnModelCreating(DbModelBuilder modelBuilder) { base.OnModelCreating(modelBuilder); modelBuilder.Conventions.Remove <PluralizingTableNameConvention>(); modelBuilder.Conventions.Add <OneToManyCascadeDeleteConvention>(); var userBuilder = new UserBuilder(modelBuilder.Entity <UserEntity>()); var roleBuilder = new RoleBuilder(modelBuilder.Entity <RoleEntity>()); var companyBuilder = new CompanyBuilder(modelBuilder.Entity <CompanyEntity>()); var experimentBuilder = new ExperimentBuilder(modelBuilder.Entity <ExperimentEntity>()); var permissionBuilder = new PermissionBuilder(modelBuilder.Entity <PermissionEntity>()); var projectBuilder = new ProjectBuilder(modelBuilder.Entity <ProjectEntity>()); var auditTrailBuilder = new AuditTrailBuilder(modelBuilder.Entity <AuditTrailEntity>()); var auditTrailChangeLogBuilder = new AuditTrailChangeLogBuilder(modelBuilder.Entity <AuditTrailChangeLogEntity>()); var LicenseTypeBuilder = new LicenseTypeBuilder(modelBuilder.Entity <LicenseTypeEntity>()); var LicenseBuilder = new LicenseBuilder(modelBuilder.Entity <LicenseEntity>()); }
public void GetAllRoles_GivenTwoRoles_ShouldRole() { //---------------Set up test pack------------------- var role1 = new RoleBuilder().WithRandomProps().Build(); var role2 = new RoleBuilder().WithRandomProps().Build(); var dbContext = new TestDbContextBuilder().WithRoles(role1,role2).Build(); var repository = new RoleRepository(dbContext); //---------------Assert Precondition--------------- //---------------Execute Test ---------------------- var roles = repository.GetAllRoles(); //---------------Test Result ----------------------- Assert.AreEqual(2, roles.Count); var actualFirst = roles.First(); Assert.AreSame(role1, actualFirst); var actualLast = roles.Last(); Assert.AreSame(role2,actualLast); }
public void GivenAnAccessListWhenRemovingUserFromACLThenUserHasNoAccessToThePermissionsInTheRole() { var permission = this.FindPermission(M.Organisation.Name, Operations.Read); var role = new RoleBuilder(this.Session).WithName("Role").WithPermission(permission).Build(); var person = new PersonBuilder(this.Session).WithFirstName("John").WithLastName("Doe").Build(); var person2 = new PersonBuilder(this.Session).WithFirstName("Jane").WithLastName("Doe").Build(); new AccessControlBuilder(this.Session).WithSubject(person).WithRole(role).Build(); this.Session.Derive(); this.Session.Commit(); var sessions = new ISession[] { this.Session }; foreach (var session in sessions) { session.Commit(); var organisation = new OrganisationBuilder(session).WithName("Organisation").Build(); var token = new SecurityTokenBuilder(session).Build(); organisation.AddSecurityToken(token); var accessControl = (AccessControl)session.Instantiate(role.AccessControlsWhereRole.First); token.AddAccessControl(accessControl); this.Session.Derive(); var acl = new AccessControlLists(person)[organisation]; accessControl.RemoveSubject(person); accessControl.AddSubject(person2); this.Session.Derive(); acl = new AccessControlLists(person)[organisation]; Assert.False(acl.CanRead(M.Organisation.Name)); session.Rollback(); } }
public void GetAllRoles_GivenTwoRoles_ShouldReturnTwoRoles() { //---------------Set up test pack------------------- var role1 = new RoleBuilder().WithRandomProps().Build(); var role2 = new RoleBuilder().WithRandomProps().Build(); var dbContext = new TestDbContextBuilder().WithRoles(role1, role2).Build(); var repository = new RoleRepository(dbContext); //---------------Assert Precondition--------------- //---------------Execute Test ---------------------- var roles = repository.GetAllRoles(); //---------------Test Result ----------------------- Assert.AreEqual(2, roles.Count); var actualFirst = roles.First(); Assert.AreSame(role1, actualFirst); var actualLast = roles.Last(); Assert.AreSame(role2, actualLast); }
private void initList() { ActorController director = new ActorController(); for (int i = 0; i < 10; i++) { ActorBuilder builder = new RoleBuilder(roleControl); Actor a = director.Construct(builder); roles.Add(a); } for (int i = 0; i < 100; i++) { ActorBuilder guaiwub = new GuaiWuBuilder(guaiwuControl); Actor a = director.Construct(guaiwub); guaiwus.Add(a); } ActorBuilder self = new RoleBuilder(roleControl); selfRole = director.Construct(self); }
public bool DeleteAccount(int accountId) { try { if (accountId == 1) { return(false); } SecurityDAO.DeleteAccount(accountId); RoleBuilder.Init(); return(true); } catch (Exception ex) { NLogManager.PublishException(ex); } return(false); }
public void DeniedPermissions() { var readOrganisationName = this.FindPermission(M.Organisation.Name, Operations.Read); var databaseRole = new RoleBuilder(this.Session).WithName("Role").WithPermission(readOrganisationName).Build(); var person = new PersonBuilder(this.Session).WithFirstName("John").WithLastName("Doe").Build(); new AccessControlBuilder(this.Session).WithRole(databaseRole).WithSubject(person).Build(); this.Session.Derive(); this.Session.Commit(); var sessions = new ISession[] { this.Session }; foreach (var session in sessions) { session.Commit(); var organisation = new OrganisationBuilder(session).WithName("Organisation").Build(); var token = new SecurityTokenBuilder(session).Build(); organisation.AddSecurityToken(token); var role = (Role)session.Instantiate(new Roles(this.Session).FindBy(M.Role.Name, "Role")); var accessControl = (AccessControl)session.Instantiate(role.AccessControlsWhereRole.First); token.AddAccessControl(accessControl); Assert.False(this.Session.Derive(false).HasErrors); var acl = new AccessControlLists(person)[organisation]; Assert.True(acl.CanRead(M.Organisation.Name)); organisation.AddDeniedPermission(readOrganisationName); acl = new AccessControlLists(person)[organisation]; Assert.False(acl.CanRead(M.Organisation.Name)); session.Rollback(); } }
public void DeniedPermissions() { var readOrganisationName = this.FindPermission(Organisations.Meta.Name, Operation.Read); var databaseRole = new RoleBuilder(this.DatabaseSession).WithName("Role").WithPermission(readOrganisationName).Build(); var person = new PersonBuilder(this.DatabaseSession).WithFirstName("John").WithLastName("Doe").Build(); this.DatabaseSession.Derive(true); this.DatabaseSession.Commit(); new AccessControlBuilder(this.DatabaseSession).WithRole(databaseRole).WithSubject(person).Build(); this.DatabaseSession.Commit(); var sessions = new ISession[] { this.DatabaseSession, this.CreateWorkspaceSession() }; foreach (var session in sessions) { session.Commit(); var organisation = new OrganisationBuilder(session).WithName("Organisation").Build(); var token = new SecurityTokenBuilder(session).Build(); organisation.AddSecurityToken(token); var role = (Role)session.Instantiate(new Roles(this.DatabaseSession).FindBy(Roles.Meta.Name, "Role")); var accessControl = (AccessControl)session.Instantiate(role.AccessControlsWhereRole.First); accessControl.AddObject(token); Assert.IsFalse(this.DatabaseSession.Derive().HasErrors); var accessList = new AccessControlList(organisation, person); Assert.IsTrue(accessList.CanRead(Organisations.Meta.Name)); organisation.AddDeniedPermission(readOrganisationName); accessList = new AccessControlList(organisation, person); Assert.IsFalse(accessList.CanRead(Organisations.Meta.Name)); session.Rollback(); } }
public void GivenAnotherUserGroupAndAnAccessControlledObjectWhenGettingTheAccessListThenUserHasAccessToThePermissionsInTheRole() { var readOrganisationName = this.FindPermission(M.Organisation.Name, Operations.Read); var databaseRole = new RoleBuilder(this.Session).WithName("Role").WithPermission(readOrganisationName).Build(); var person = new PersonBuilder(this.Session).WithFirstName("John").WithLastName("Doe").Build(); new UserGroupBuilder(this.Session).WithName("Group").WithMember(person).Build(); var anotherUserGroup = new UserGroupBuilder(this.Session).WithName("AnotherGroup").Build(); this.Session.Derive(); this.Session.Commit(); new AccessControlBuilder(this.Session).WithSubjectGroup(anotherUserGroup).WithRole(databaseRole).Build(); this.Session.Commit(); var sessions = new ISession[] { this.Session }; foreach (var session in sessions) { session.Commit(); var organisation = new OrganisationBuilder(session).WithName("Organisation").Build(); var token = new SecurityTokenBuilder(session).Build(); organisation.AddSecurityToken(token); var role = (Role)session.Instantiate(new Roles(this.Session).FindBy(M.Role.Name, "Role")); var accessControl = (AccessControl)session.Instantiate(role.AccessControlsWhereRole.First); token.AddAccessControl(accessControl); Assert.False(this.Session.Derive(false).HasErrors); var acl = new AccessControlLists(person)[organisation]; Assert.False(acl.CanRead(M.Organisation.Name)); session.Rollback(); } }
public void GivenNoAccessControlWhenCreatingAAccessControlWithoutATokenThenAccessControlIsInvalid() { var role = new RoleBuilder(this.DatabaseSession).WithName("Role").Build(); var user = new PersonBuilder(this.DatabaseSession).WithUserName("user").WithLastName("Doe").Build(); new AccessControlBuilder(this.DatabaseSession) .WithSubject(user) .WithRole(role) .Build(); var derivationLog = this.DatabaseSession.Derive(); Assert.IsTrue(derivationLog.HasErrors); Assert.AreEqual(1, derivationLog.Errors.Length); var derivationError = derivationLog.Errors[0]; Assert.AreEqual(1, derivationError.Relations.Length); Assert.AreEqual(typeof(DerivationErrorRequired), derivationError.GetType()); Assert.IsTrue(new ArrayList(derivationError.RoleTypes).Contains((RoleType)AccessControls.Meta.Objects)); }
public void GivenNoAccessControlWhenCreatingAAccessControlWithoutAUserOrUserGroupThenAccessControlIsInvalid() { var securityToken = new SecurityTokenBuilder(this.Session).Build(); var role = new RoleBuilder(this.Session).WithName("Role").Build(); securityToken.AddAccessControl( new AccessControlBuilder(this.Session) .WithRole(role) .Build()); var validation = this.Session.Derive(false); Assert.True(validation.HasErrors); Assert.Equal(1, validation.Errors.Length); var derivationError = validation.Errors[0]; Assert.Equal(2, derivationError.Relations.Length); Assert.Equal(typeof(DerivationErrorAtLeastOne), derivationError.GetType()); Assert.True(new ArrayList(derivationError.RoleTypes).Contains((RoleType)M.AccessControl.Subjects)); Assert.True(new ArrayList(derivationError.RoleTypes).Contains((RoleType)M.AccessControl.SubjectGroups)); }
public void GivenNoAccessControlWhenCreatingAAccessControlWithoutAUserOrUserGroupThenAccessControlIsInvalid() { var securityToken = new SecurityTokenBuilder(this.DatabaseSession).Build(); var role = new RoleBuilder(this.DatabaseSession).WithName("Role").Build(); new AccessControlBuilder(this.DatabaseSession) .WithObject(securityToken) .WithRole(role) .Build(); var derivationLog = this.DatabaseSession.Derive(); Assert.IsTrue(derivationLog.HasErrors); Assert.AreEqual(1, derivationLog.Errors.Length); var derivationError = derivationLog.Errors[0]; Assert.AreEqual(2, derivationError.Relations.Length); Assert.AreEqual(typeof(DerivationErrorAtLeastOne), derivationError.GetType()); Assert.IsTrue(new ArrayList(derivationError.RoleTypes).Contains((RoleType)AccessControls.Meta.Subjects)); Assert.IsTrue(new ArrayList(derivationError.RoleTypes).Contains((RoleType)AccessControls.Meta.SubjectGroups)); }
public override void SetUp() { base.SetUp(); // unsure if this test fixture should include the internal handlers // as the validator has no clue about *how* the property is validated. // on the other hand, there isn't much of a better way to test a validator // than to do a kind of sort of integration test var token = new CancellationToken(); Task <bool> ReturnCall <TRequest, TRequestHandler>(CallInfo call) where TRequest : IRequest <bool> where TRequestHandler : IRequestHandler <TRequest, bool> { if (call.Args().Length > 0 && call.Args()[0] is TRequest sentRequest) { var handler = (TRequestHandler)System.Activator.CreateInstance(typeof(TRequestHandler), DataContext); return(handler.Handle(sentRequest, token)); } return(Task.FromResult(false)); } mediatorMock.Send(Arg.Any <UserHasAnyRoleRequest>()).Returns(ReturnCall <UserHasAnyRoleRequest, UserHasRoleRequestHandler>); mediatorMock.Send(Arg.Any <IsValidUserRequest>()).Returns(ReturnCall <IsValidUserRequest, IsValidUserRequestHandler>); var roleBuilder = new RoleBuilder(); var userBuidler = new UserBuilder(); roleBuilder.With(r => r.Name, PvPStatics.Permissions_Admin); roleBuilder.AddUser(userBuidler.Build()); roleBuilder.BuildAndSave(); adminUser = userBuidler.BuildAndSave(); normalUser = new UserBuilder().BuildAndSave(); request = new ResetSecurityStamp(); }
public bool UpdateRole([FromBody] List <ActiveRole> activeRoles, int user) { try { StringBuilder query = new StringBuilder(); query.AppendLine($"delete from dbo.Role where AccountID = {user}"); foreach (var r in activeRoles) { if (r.IsActive) { query.AppendLine($"insert into dbo.Role (AccountID, SubID) values ({user}, {r.SubID})"); } } RoleDAO.Execute(query.ToString()); RoleBuilder.Init(); return(true); }catch (Exception ex) { NLogManager.PublishException(ex); } return(false); }
private void BtnDelete_Click(object sender, EventArgs e) { String name = null; try { name = this.LvwRole.SelectedItems?[0]?.Text; } catch { } if (name != null) { DialogResult dr = MessageBox.Show("Are you sure?", "Delete", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question); if (dr == DialogResult.Yes) { RoleBuilder buider = new RoleBuilder(name); this.roleBLL.Remove(buider.Build()); MessageBox.Show(String.Join(" ", "Delete role ", name, "sucessfull!")); this.LoadAll(); } } }
public void GivenAUserAndAnAccessControlledObjectWhenGettingTheAccessListThenUserHasAccessToThePermissionsInTheRole() { var permission = this.FindPermission(M.Organisation.Name, Operations.Read); var role = new RoleBuilder(this.Session).WithName("Role").WithPermission(permission).Build(); var person = new PersonBuilder(this.Session).WithFirstName("John").WithLastName("Doe").Build(); new AccessControlBuilder(this.Session).WithSubject(person).WithRole(role).Build(); this.Session.Derive(true); this.Session.Commit(); var sessions = new ISession[] { this.Session }; foreach (var session in sessions) { session.Commit(); var organisation = new OrganisationBuilder(session).WithName("Organisation").Build(); var token = new SecurityTokenBuilder(session).Build(); organisation.AddSecurityToken(token); var accessControl = (AccessControl)session.Instantiate(role.AccessControlsWhereRole.First); token.AddAccessControl(accessControl); this.Session.Derive(true); Assert.False(this.Session.Derive(false).HasErrors); var accessList = new AccessControlList(organisation, person); Assert.True(accessList.CanRead(M.Organisation.Name)); session.Rollback(); } }
public void Before() { roleBuilder = new RoleBuilder(); }
public async Task ExecuteShouldEditScheduleGroupClass() { //Arrange SchoolManagementContext context = new ContextBuilder().BuildClean(); GroupLevel groupLevel = new GroupLevelBuilder(context).With(x => x.Level = 1).With(x => x.Name = "Początkujący").BuildAndSave(); Room room = new RoomBuilder(context).WithName("Sala biała").BuildAndSave(); User anchor = new UserBuilder(context).WithEmail("*****@*****.**").BuildAndSave(); new RoleBuilder(context).WithName(Roles.Anchor).AddUserToRole(anchor).BuildAndSave(); List <User> participants = new List <User>(); var participantRoleBuilder = new RoleBuilder(context).WithName(Roles.Participant); for (var i = 0; i < 10; i++) { User user = new UserBuilder(context).WithEmail($"email{i}@gmail.com").BuildAndSave(); participants.Add(user); participantRoleBuilder.AddUserToRole(user); } participantRoleBuilder.BuildAndSave(); string expectedAnchorEmail = "*****@*****.**"; var groupClass = CreateGroupClass(context, expectedAnchorEmail); string expectedAnchorId = groupClass.Anchors.Where(x => x.User.Email == expectedAnchorEmail).Select(x => x.UserId).First(); Command cmd = new Command { GroupClassId = groupClass.Id, Name = "Groupa zajęciowa", Anchors = new List <string> { anchor.Id, expectedAnchorId }, IsSolo = true, ParticipantLimit = 20, UtcOffsetInMinutes = 0, GroupLevelId = groupLevel.Id, Participants = participants.Select(x => new ParticipantDto { Id = x.Id, Role = ParticipantRole.Leader }).ToList(), DayOfWeeks = new List <ClassDayOfWeekDto> { new ClassDayOfWeekDto() { BeginTime = new TimeSpan(19, 0, 0), DayOfWeek = DayOfWeek.Tuesday }, new ClassDayOfWeekDto() { BeginTime = new TimeSpan(18, 0, 0), DayOfWeek = DayOfWeek.Wednesday }, new ClassDayOfWeekDto() { BeginTime = new TimeSpan(19, 0, 0), DayOfWeek = DayOfWeek.Friday }, }, DurationTimeInMinutes = 90, NumberOfClasses = 24, RoomId = room.Id }; var expectedParticipant = groupClass.Participants.Select(x => x.User).First(); ParticipantDto expectedRole = new ParticipantDto() { Id = expectedParticipant.Id, Role = ParticipantRole.Leader }; cmd.Participants.Add(expectedRole); //Act DataResult result = await new Handler(context).Handle(cmd, CancellationToken.None); //Assert result .Should().NotBeNull(); result.Status.Should().Be(DataResult.ResultStatus.Success, "all parameters are corrected"); context.GroupClass.Should().NotBeEmpty("we add new group"); groupClass.Anchors.Should().NotBeEmpty().And.HaveCount(cmd.Anchors.Count); groupClass.Room.Should().Be(room); groupClass.IsSolo.Should().BeTrue(); groupClass.Name.Should().Be(cmd.Name); groupClass.GroupLevel.Should().Be(groupLevel); groupClass.Participants.Should().NotBeEmpty().And.HaveCount(cmd.Participants.Count).And .Contain(x => participants.Contains(x.User)); groupClass.Participants.Where(x => x.User.Email == expectedParticipant.Email).Select(x => x.Role).First() .Should().Be(expectedRole.Role, "we changed role"); ValidateClassDayOfWeek(groupClass); groupClass.Schedule.Should().NotBeNullOrEmpty().And.HaveCount(24).And.OnlyContain(x => x.StartDate.DayOfWeek == DayOfWeek.Tuesday || x.StartDate.DayOfWeek == DayOfWeek.Friday || x.StartDate.DayOfWeek == DayOfWeek.Wednesday); }
public void GivenAUserGroupAndAnAccessControlledObjectWhenGettingTheAccessListThenUserHasAccessToThePermissionsInTheRole() { var readOrganisationName = this.FindPermission(Organisations.Meta.Name, Operation.Read); var databaseRole = new RoleBuilder(this.Session).WithName("Role").WithPermission(readOrganisationName).Build(); var person = new PersonBuilder(this.Session).WithFirstName("John").WithLastName("Doe").Build(); new UserGroupBuilder(this.Session).WithName("Group").WithMember(person).Build(); this.Session.Derive(true); this.Session.Commit(); new AccessControlBuilder(this.Session).WithSubject(person).WithRole(databaseRole).Build(); this.Session.Commit(); var sessions = new ISession[] { this.Session }; foreach (var session in sessions) { session.Commit(); var organisation = new OrganisationBuilder(session).WithName("Organisation").Build(); var token = new SecurityTokenBuilder(session).Build(); organisation.AddSecurityToken(token); var role = (Role)session.Instantiate(new Roles(this.Session).FindBy(Roles.Meta.Name, "Role")); var accessControl = (AccessControl)session.Instantiate(role.AccessControlsWhereRole.First); accessControl.AddObject(token); Assert.IsFalse(this.Session.Derive().HasErrors); var accessList = new AccessControlList(organisation, person); Assert.IsTrue(accessList.CanRead(Organisations.Meta.Name)); session.Rollback(); } }
public async Task ExecuteShouldAddGroupAndAddPresence() { SchoolManagementContext context = new ContextBuilder().BuildClean(); GroupLevel groupLevel = new GroupLevelBuilder(context).With(x => x.Level = 1).With(x => x.Name = "Początkujący").BuildAndSave(); Room room = new RoomBuilder(context).WithName("Sala biała").BuildAndSave(); User anchor = new UserBuilder(context).WithEmail("*****@*****.**").BuildAndSave(); Role role = new RoleBuilder(context).WithName(Roles.Anchor).AddUserToRole(anchor).BuildAndSave(); List <User> participants = new List <User>(); var participantRoleBuilder = new RoleBuilder(context).WithName(Roles.Participant); for (var i = 0; i < 10; i++) { User user = new UserBuilder(context).WithEmail($"email{i}@gmail.com").BuildAndSave(); participants.Add(user); participantRoleBuilder.AddUserToRole(user); } participantRoleBuilder.BuildAndSave(); Command cmd = new Command { Name = "Groupa zajęciowa", Anchors = new List <string> { anchor.Id }, IsSolo = true, ParticipantLimit = 20, PassPrice = 200, GroupLevelId = groupLevel.Id, UtcOffsetInMinutes = 0, Participants = participants.Select(x => new ParticipantDto { Id = x.Id, Role = ParticipantRole.Leader }).ToList(), RoomId = room.Id, DayOfWeeks = new List <ClassDayOfWeekDto> { new ClassDayOfWeekDto() { DayOfWeek = System.DayOfWeek.Monday, BeginTime = new TimeSpan(18, 0, 0) }, new ClassDayOfWeekDto() { DayOfWeek = System.DayOfWeek.Thursday, BeginTime = new TimeSpan(19, 0, 0) } }, Start = new DateTime(2019, 09, 01), //Sunday DurationTimeInMinutes = 90, NumberOfClasses = 20 }; DataResult dataResult = await new Handler(context).Handle(cmd, CancellationToken.None); dataResult.Status.Should().Be(DataResult.ResultStatus.Success, "all parameters are corrected"); context.ParticipantPresences.Should().NotBeNullOrEmpty() .And.HaveCount(cmd.NumberOfClasses * cmd.Participants.Count) .And.NotContainNulls(x => x.ClassTime) .And.NotContainNulls(x => x.Participant); context.ClassTimes.Should().NotBeEmpty().And.HaveCount(cmd.NumberOfClasses).And .NotContainNulls(x => x.PresenceParticipants); ClassTime classTime = context.ClassTimes.First(); classTime.PresenceParticipants.Should().HaveCount(10); ParticipantClassTime participantClassTime = context.ParticipantPresences.First(); AssertPass(context, participants, cmd); }
public async Task ExecuteShouldAddGroupAndAddScheduleWithOffset() { SchoolManagementContext context = new ContextBuilder().BuildClean(); GroupLevel groupLevel = new GroupLevelBuilder(context).With(x => x.Level = 1).With(x => x.Name = "Początkujący").BuildAndSave(); Room room = new RoomBuilder(context).WithName("Sala biała").BuildAndSave(); User anchor = new UserBuilder(context).WithEmail("*****@*****.**").BuildAndSave(); Role role = new RoleBuilder(context).WithName(Roles.Anchor).AddUserToRole(anchor).BuildAndSave(); Command cmd = new Command { Name = "Groupa zajęciowa", Anchors = new List <string> { anchor.Id }, IsSolo = true, ParticipantLimit = 20, GroupLevelId = groupLevel.Id, RoomId = room.Id, UtcOffsetInMinutes = 60, DayOfWeeks = new List <ClassDayOfWeekDto> { new ClassDayOfWeekDto() { DayOfWeek = System.DayOfWeek.Monday, BeginTime = new TimeSpan(18, 0, 0) }, new ClassDayOfWeekDto() { DayOfWeek = System.DayOfWeek.Thursday, BeginTime = new TimeSpan(19, 0, 0) } }, Start = new DateTime(2019, 09, 01), //Sunday DurationTimeInMinutes = 90, NumberOfClasses = 20 }; DataResult dataResult = await new Handler(context).Handle(cmd, CancellationToken.None); dataResult.Status.Should().Be(DataResult.ResultStatus.Success, "all parameters are corrected"); List <ClassTime> classTimes = context.ClassTimes.ToList(); classTimes.Should().NotBeEmpty("we set schedule") .And.HaveCount(20, "because we have classes 20 number of classes"); ClassTime classes = classTimes.First(); classes.Room.Should().Be(room); classes.RoomId.Should().Be(cmd.RoomId); GroupClass groupClass = context.GroupClass.First(); groupClass.DurationTimeInMinutes.Should().Be(90); groupClass.NumberOfClasses.Should().Be(20); groupClass.StartClasses.Should().Be(new DateTime(2019, 09, 01).ToUniversalTime()); List <ClassDayOfWeek> groupClassClassDaysOfWeek = groupClass.ClassDaysOfWeek; groupClassClassDaysOfWeek.Should() .NotBeNullOrEmpty() .And .HaveCount(2); groupClassClassDaysOfWeek.First().Hour.Should().Be(new TimeSpan(18, 0, 0)); classes.GroupClass.Should().Be(groupClass); classes.GroupClassId.Should().Be(groupClass.Id); DateTime expectedStartTimeForOdd = new DateTime(2019, 09, 02, 18, 0, 0); DateTime expectedEndTimeForOdd = new DateTime(2019, 09, 02, 19, 30, 0); DateTime expectedStartTimeForEven = new DateTime(2019, 09, 05, 19, 0, 0); DateTime expectedEndTimeForEven = new DateTime(2019, 09, 05, 20, 30, 0); int index = 1; foreach (ClassTime classTime in classTimes) { if (index % 2 == 1) { classTime.StartDate.Should().Be(expectedStartTimeForOdd.ToUniversalTime().AddMinutes(cmd.UtcOffsetInMinutes)); classTime.StartDate.DayOfWeek.Should().Be(System.DayOfWeek.Monday); classTime.EndDate.Should().Be(expectedEndTimeForOdd.ToUniversalTime().AddMinutes(cmd.UtcOffsetInMinutes), "because classes during 90 minutes"); expectedStartTimeForOdd = expectedStartTimeForOdd.AddDays(7); expectedEndTimeForOdd = expectedEndTimeForOdd.AddDays(7); } else { classTime.StartDate.Should().Be(expectedStartTimeForEven.ToUniversalTime().AddMinutes(cmd.UtcOffsetInMinutes)); classTime.StartDate.DayOfWeek.Should().Be(System.DayOfWeek.Thursday); classTime.EndDate.Should().Be(expectedEndTimeForEven.ToUniversalTime().AddMinutes(cmd.UtcOffsetInMinutes), "because classes during 90 minutes"); expectedStartTimeForEven = expectedStartTimeForEven.AddDays(7); expectedEndTimeForEven = expectedEndTimeForEven.AddDays(7); } index++; } }
public void GivenAWorkspaceNewAccessControlledObjectWhenGettingTheAccessControlListThenUserHasAccessToThePermissionsInTheRole() { var readOrganisationName = this.FindPermission(Organisations.Meta.Name, Operation.Read); var databaseRole = new RoleBuilder(this.DatabaseSession).WithName("Role").WithPermission(readOrganisationName).Build(); var person = new PersonBuilder(this.DatabaseSession).WithFirstName("John").WithLastName("Doe").Build(); this.DatabaseSession.Derive(true); this.DatabaseSession.Commit(); new AccessControlBuilder(this.DatabaseSession).WithSubject(person).WithRole(databaseRole).Build(); this.DatabaseSession.Commit(); var workspaceSession = this.CreateWorkspaceSession(); var organisation = new OrganisationBuilder(workspaceSession).WithName("Organisation").Build(); var token = new SecurityTokenBuilder(workspaceSession).Build(); organisation.AddSecurityToken(token); var role = (Role)workspaceSession.Instantiate(new Roles(this.DatabaseSession).FindBy(Roles.Meta.Name, "Role")); var accessControl = (AccessControl)workspaceSession.Instantiate(role.AccessControlsWhereRole.First); accessControl.AddObject(token); Assert.IsFalse(this.DatabaseSession.Derive().HasErrors); var accessList = new AccessControlList(organisation, person); accessList.CanRead(Organisations.Meta.Name); }