public IActionResult Get([FromRoute] string orgRoleId, [FromRoute] string reportId) { if (string.IsNullOrWhiteSpace(orgRoleId) || string.IsNullOrEmpty(orgRoleId)) { return(StatusCode(StatusCodes.Status400BadRequest, new BadRequestError($"'{nameof(orgRoleId)}' cannot be null or whitespace"))); } if (string.IsNullOrWhiteSpace(reportId) || string.IsNullOrEmpty(reportId)) { return(StatusCode(StatusCodes.Status400BadRequest, new BadRequestError($"'{nameof(reportId)}' cannot be null or whitespace"))); } OrganizationRole organizationRole = organizationRoleService .Get <OrganizationRole>(orgRole => orgRole.Id == orgRoleId, asNoTracking: true); if (organizationRole == null) { return(StatusCode(StatusCodes.Status404NotFound, new NotFoundError($"organizationRole not found"))); } ReportVM reportVM = reportService.Get <ReportVM>( report => report.Id == reportId, asNoTracking: true, r => r.CreatedBy); if (reportVM == null) { return(StatusCode(StatusCodes.Status404NotFound, new NotFoundError($"report not found"))); } return(StatusCode(StatusCodes.Status200OK, reportVM)); }
public IActionResult Get([FromRoute] string orgRoleId) { if (string.IsNullOrEmpty(orgRoleId) || string.IsNullOrWhiteSpace(orgRoleId)) { return(StatusCode(StatusCodes.Status400BadRequest, new BadRequestError("organizationRoleId Parameter cant be null"))); } OrganizationRole organizationRole = organizationRoleService.Get <OrganizationRole>( orgRole => orgRole.Id == orgRoleId, asNoTracking: true); if (organizationRole == null) { return(StatusCode(StatusCodes.Status404NotFound, new NotFoundError($"OrganizationRole not found"))); } var reportTemplates = reportTemplateService.GetAll <ShortReportTemplateVM>( filter: null, asNoTracking: true, rt => rt.CreatedBy); return(Ok(reportTemplates)); }
public IActionResult Get([FromRoute] string orgRoleId) { if (string.IsNullOrWhiteSpace(orgRoleId) || string.IsNullOrEmpty(orgRoleId)) { return(StatusCode(StatusCodes.Status400BadRequest, new BadRequestError($"'{nameof(orgRoleId)}' cannot be null or whitespace"))); } OrganizationRole organizationRole = organizationRoleService.Get <OrganizationRole>( orgRole => orgRole.Id == orgRoleId, asNoTracking: true, orgRole => orgRole.Organization); if (organizationRole == null) { return(StatusCode(StatusCodes.Status404NotFound, new NotFoundError($"organizationRole not found"))); } IEnumerable <Report> reports = reportService.GetAll <Report>(null, asNoTracking: true, report => report.CreatedBy); //.Where(report => // $"{report.MetadataJObject["organization"]}" == organizationRole.Organization.OrganizationName); return(Ok(_typeAdapter.Adapt <IEnumerable <ShortReportVM> >(reports))); }
private bool CheckRequiredRoleInRelationTo(IEntity target, OrganizationRole role) { var organizationIds = new HashSet <int>(); //If the entity has organizational relationship(s), we check permissions against that (target as IIsPartOfOrganization)?.GetOrganizationIds()?.ToList().ForEach(id => organizationIds.Add(id)); if (target is IOwnedByOrganization ownedByOrganization) { //If organization is unknown, the object will be fresh and validation must be in the context of the users other rights if (ownedByOrganization.Organization != null) { organizationIds.Add(ownedByOrganization.Organization.Id); } } if (!organizationIds.Any()) { //Target is not specific to organization so base the check on any role in any of the users organizations foreach (var organizationId in _userContext.OrganizationIds) { organizationIds.Add(organizationId); } } return(organizationIds.Any(id => _userContext.HasRole(id, role))); }
public static async Task <int> CreateOdataUserAsync(ApiUserDTO userDto, OrganizationRole role, int organizationId = TestEnvironment.DefaultOrganizationId) { var cookie = await GetCookieAsync(OrganizationRole.GlobalAdmin); var createUserDto = ObjectCreateHelper.MakeSimpleCreateUserDto(userDto); int userId; using (var createdResponse = await PostWithCookieAsync(TestEnvironment.CreateUrl("odata/Users/Users.Create"), cookie, createUserDto)) { Assert.Equal(HttpStatusCode.Created, createdResponse.StatusCode); var response = await createdResponse.ReadResponseBodyAsAsync <UserDTO>(); userId = response.Id; Assert.Equal(userDto.Email, response.Email); } using (var addedRole = await SendAssignRoleToUserAsync(userId, role, organizationId)) { Assert.Equal(HttpStatusCode.Created, addedRole.StatusCode); } return(userId); }
public async Task User_Is_Able_To_Get_Interfaces_From_Own_Org_Or_Public(OrganizationRole role, int orgId) { //Arrange var interFacePrefixName = CreateInterFacePrefixName(); var token = await HttpApi.GetTokenAsync(role); var interfacesCreated = await GenerateTestInterfaces(interFacePrefixName); var expectedResults = interfacesCreated.Where(x => x.OrganizationId == TestEnvironment.DefaultOrganizationId && orgId == x.OrganizationId || //If queried org is same as user org and interface org it is returned even if private role == OrganizationRole.GlobalAdmin && orgId == x.OrganizationId || //Both public and private of queried org are returned if global admin x.AccessModifier == AccessModifier.Public //All public are included ).ToList(); var url = TestEnvironment.CreateUrl($"/odata/Organizations({orgId})/ItInterfaces"); //Act using (var httpResponse = await HttpApi.GetWithTokenAsync(url, token.Token)) { //Assert var response = await httpResponse.ReadOdataListResponseBodyAsAsync <ItInterface>(); Assert.NotNull(response); var filteredResult = response.Where(x => x.Name.StartsWith(interFacePrefixName)).ToList(); Assert.Equal(expectedResults.Count, filteredResult.Count); Assert.True(expectedResults.Select(x => x.InterfaceId).SequenceEqual(filteredResult.Select(x => x.InterfaceId))); } }
public void UpdateKLE_Authorizes_And_Updates(OrganizationRole role, bool isOk) { // Arrange _mockOrganizationalUserContext.Setup(r => r.IsGlobalAdmin()).Returns(role == OrganizationRole.GlobalAdmin); const int activeOrganizationId = 1; var publishedDate = DateTime.Today; _mockKleStandardRepository .Setup(r => r.UpdateKLE(activeOrganizationId)) .Returns(publishedDate); _mockKleStandardRepository.Setup(r => r.GetKLEStatus(It.IsAny <DateTime>())).Returns( new KLEStatus { UpToDate = false, Published = publishedDate } ); _mockKleStandardRepository.Setup(r => r.GetKLEChangeSummary()).Returns(new List <KLEChange> { new KLEChange { ChangeType = KLEChangeType.Added, TaskKey = "dummy", UpdatedDescription = "dummy" } }.OrderBy(c => c.TaskKey)); // Act var result = _sut.UpdateKLE(activeOrganizationId); // Assert Assert.Equal(isOk, result.Ok); _mockUpdateHistoryItemRepository.Verify(r => r.Insert(publishedDate), isOk ? Times.Once() : Times.Never()); }
public async Task Can_Add_Assignment(OrganizationRole role) { //Arrange var login = await HttpApi.GetCookieAsync(role); var description = A <string>(); var name = A <string>(); var note = A <string>(); var statusPercentage = A <int>() % 100; var timeEstimate = A <int>(); var startDate = A <DateTime>().Date; var endDate = startDate.AddDays(10); //Act - perform the action with the actual role var result = await ItProjectHelper.AddAssignmentAsync(OrganizationId, _project.Id, description, name, note, statusPercentage, timeEstimate, startDate, endDate, login); //Assert Assert.Equal(_project.Id, result.AssociatedItProjectId.GetValueOrDefault()); Assert.Equal(description, result.Description); Assert.Equal(name, result.Name); Assert.Equal(note, result.Note); Assert.Equal(statusPercentage, result.StatusProcentage); Assert.Equal(timeEstimate, result.TimeEstimate); Assert.Equal(startDate, result.StartDate); Assert.Equal(endDate, result.EndDate); }
private static KitosCredentials LoadUserFromEnvironment(OrganizationRole role, bool apiAccess = false) { var suffix = string.Empty; switch (role) { case OrganizationRole.User when apiAccess: suffix = "ApiUser"; break; case OrganizationRole.User: suffix = "NormalUser"; break; case OrganizationRole.LocalAdmin: suffix = "LocalAdmin"; break; case OrganizationRole.GlobalAdmin when apiAccess: suffix = "ApiGlobalAdmin"; break; case OrganizationRole.GlobalAdmin: suffix = "GlobalAdmin"; break; default: throw new NotSupportedException($"{role} Not mapped in environment loader:{nameof(LoadUserFromEnvironment)}"); } var username = GetEnvironmentVariable($"TestUser{suffix}"); var password = GetEnvironmentVariable($"TestUser{suffix}Pw"); return(new KitosCredentials(username, password)); }
/// <summary> /// Create <see cref="ClaimsIdentity"/> for specified <see cref="IUser"/>. /// </summary> /// <param name="user">The tenant user to create the principal for.</param> /// <param name="tenant">The tenant which the user is a member of.</param> /// <param name="tenantRole">The user role within the tenant.</param> /// <param name="authenticationType">Authentication type to use in authentication scheme.</param> /// <returns>Instance of <see cref="ClaimsIdentity"/>.</returns> public static ClaimsIdentity CreateTenantUserIdentity( IUser user, ITenant tenant, OrganizationRole tenantRole, string authenticationType) { if (user is null) { throw new ArgumentNullException(nameof(user)); } if (tenant is null) { throw new ArgumentNullException(nameof(tenant)); } var claims = new[] { new Claim(ClaimTypes.NameIdentifier, user.Id.ToString()), new Claim(ClaimTypes.Role, user.Role.ToString()), new Claim(FunderMapsAuthenticationClaimTypes.Tenant, tenant.Id.ToString()), new Claim(FunderMapsAuthenticationClaimTypes.TenantRole, tenantRole.ToString()), }; return(new(claims, authenticationType, ClaimTypes.Name, ClaimTypes.Role)); }
public async Task Api_User_Can_Get_It_System_ParentId(OrganizationRole role) { //Arrange var login = await HttpApi.GetCookieAsync(role); const int organizationId = TestEnvironment.DefaultOrganizationId; var mainSystem = await ItSystemHelper.CreateItSystemInOrganizationAsync(A <string>(), organizationId, AccessModifier.Public); var childSystem = await ItSystemHelper.CreateItSystemInOrganizationAsync(A <string>(), organizationId, AccessModifier.Public); await ItSystemHelper.SendSetParentSystemRequestAsync(childSystem.Id, mainSystem.Id, organizationId, login); var token = await HttpApi.GetTokenAsync(role); var url = TestEnvironment.CreateUrl($"api/itsystem/{childSystem.Id}?hierarchy=true"); //Act using (var httpResponse = await HttpApi.GetWithTokenAsync(url, token.Token)) { //Assert var response = await httpResponse.ReadResponseBodyAsKitosApiResponseAsync <IEnumerable <ItSystemDTO> >(); Assert.Equal(HttpStatusCode.OK, httpResponse.StatusCode); var itSystemDtos = response.ToList(); Assert.NotEmpty(itSystemDtos); Assert.Equal(mainSystem.Id, itSystemDtos.First(x => x.Id == childSystem.Id).ParentId); } }
/// <summary> /// Creates an org role /// </summary> /// <param name="dbCtx"></param> /// <param name="role"></param> /// <returns></returns> public async Task <Role> CreateRoleAsync(DbContext dbCtx, OrganizationRole role) { var roleName = string.Empty; var roleIdentifier = string.Empty; switch (role) { case OrganizationRole.Owner: roleIdentifier = OrgRoleIdentifierOwner; roleName = OrgRoleNameOwner; break; case OrganizationRole.Admin: roleIdentifier = OrgRoleIdentifierAdmin; roleName = OrgRoleNameAdmin; break; default: roleIdentifier = OrgRoleIdentifierMember; roleName = OrgRoleNameMember; break; } return(await CreateRoleAsync(dbCtx, roleIdentifier, roleName)); }
public async Task Cannot_Delete_System_With_Interface_Exhibits(OrganizationRole role) { //Arrange var login = await HttpApi.GetCookieAsync(role); const int organizationId = TestEnvironment.DefaultOrganizationId; var system = await ItSystemHelper.CreateItSystemInOrganizationAsync(A <string>(), organizationId, AccessModifier.Public); var itInterfaceDto = InterfaceHelper.CreateInterfaceDto( A <string>(), A <string>(), organizationId, AccessModifier.Public); var itInterface = await InterfaceHelper.CreateInterface(itInterfaceDto); await InterfaceExhibitHelper.CreateExhibit(system.Id, itInterface.Id); //Act using (var result = await ItSystemHelper.DeleteItSystemAsync(system.Id, organizationId, login)) { //Assert await AssertCorrectConflictResponseAsync(SystemDeleteConflict.HasInterfaceExhibits, result, system.Id); } }
public void AddOrganizationRole(string name) { using (LInstContext entities = _dbContextFactory.CreateDbContext(new string[] { })) { OrganizationRole newRole = new OrganizationRole { Name = name, Description = "" }; entities.OrganizationRoles.Add(newRole); foreach (Organization org in entities.Organizations) { OrganizationRoleMapping newMapping = new OrganizationRoleMapping { OrganizationRole = newRole, Organization = org, IsSelected = false }; entities.OrganizationRoleMappings.Add(newMapping); } entities.SaveChanges(); } }
public async Task GetUnusedItSystems_Can_Limit_How_Many_Systems_To_Return(OrganizationRole role) { //Arrange var prefix = CreateName(); var itSystemName1 = prefix + CreateName(); var itSystemName2 = prefix + CreateName(); var itSystemName3 = prefix + CreateName(); var itSystem1 = await CreateSystemAsync(name : itSystemName1); var itSystem2 = await CreateSystemAsync(name : itSystemName2); var itSystem3 = await CreateSystemAsync(name : itSystemName3); var createdSystemsIds = new[] { itSystem1.Id, itSystem2.Id, itSystem3.Id }; //Act using (var httpResponse = await GetUnusedSystemsAsync(role, TestEnvironment.DefaultOrganizationId, prefix, 2, true)) { var response = await httpResponse.ReadResponseBodyAsKitosApiResponseAsync <IEnumerable <ItSystemSimpleDTO> >(); //Assert Assert.Equal(HttpStatusCode.OK, httpResponse.StatusCode); var itSystems = response.ToList(); Assert.Equal(2, itSystems.Count); Assert.True(itSystems.All(x => createdSystemsIds.Contains(x.Id))); } }
public async Task <IActionResult> Put([FromRoute] string orgRoleId, [FromRoute] string reportId, [FromBody] ReportContentVM model) { if (string.IsNullOrEmpty(orgRoleId) || string.IsNullOrWhiteSpace(orgRoleId)) { return(StatusCode(StatusCodes.Status400BadRequest, new BadRequestError($"'{nameof(orgRoleId)}' cannot be null or whitespace"))); } if (string.IsNullOrEmpty(reportId) || string.IsNullOrWhiteSpace(reportId)) { return(StatusCode(StatusCodes.Status400BadRequest, new BadRequestError("reportId Parameter cant be null"))); } if (!ModelState.IsValid) { return(BadRequest(ModelState)); } OrganizationRole organizationRole = organizationRoleService .Get <OrganizationRole>(orgRole => orgRole.Id == orgRoleId); if (organizationRole == null) { return(StatusCode(StatusCodes.Status404NotFound, new NotFoundError($"OrganizationRole not found"))); } User user = await GetCurrentUser(); ReportContentDto reportUpdated = _typeAdapter.Adapt <ReportContentVM, ReportContentDto>(model); reportUpdated.ReportId = reportId; reportUpdated.UserId = user.Id; try { reportService.Update(reportUpdated); if (_unitOfWork.SaveChanges() < 0) { return(StatusCode(StatusCodes.Status400BadRequest, new BadRequestError("Error when trying to update a report content"))); } return(StatusCode(StatusCodes.Status200OK)); } catch (NullReferenceException e) { return(StatusCode(StatusCodes.Status500InternalServerError, new InternalServerError(e.Message))); } catch (InvalidOperationException e) { return(StatusCode(StatusCodes.Status400BadRequest, new BadRequestError(e.Message))); } catch (Exception) { throw; } }
private static async Task <HttpResponseMessage> GetUsingOrganizations(OrganizationRole role, int itSystemId) { var cookie = await HttpApi.GetCookieAsync(role); var url = TestEnvironment.CreateUrl($"api/v1/ItSystem/{itSystemId}/usingOrganizations"); return(await HttpApi.GetWithCookieAsync(url, cookie)); }
public void User_With_Role_Is_Available(OrganizationRole role, bool apiAccess) { var user = TestEnvironment.GetCredentials(role, apiAccess); Assert.NotNull(user); Assert.False(string.IsNullOrWhiteSpace(user.Username)); Assert.False(string.IsNullOrWhiteSpace(user.Password)); }
public CreateKitosUserTask(string email, string password, OrganizationRole role, string organizationNames, bool apiAccess = false) { _email = email ?? throw new ArgumentNullException(nameof(email)); _password = password ?? throw new ArgumentNullException(nameof(password)); _role = role; _organizationNames = ParseOrganizationNames(organizationNames ?? throw new ArgumentNullException(nameof(organizationNames))); _apiAccess = apiAccess; _salt = string.Format("{0:N}{0:N}", Guid.NewGuid()); }
public async Task GetUsingOrganizations_Cannot_Find_Non_Existing_System(OrganizationRole role) { //Act using (var httpResponse = await GetUsingOrganizations(role, int.MaxValue)) { //Assert Assert.Equal(HttpStatusCode.NotFound, httpResponse.StatusCode); } }
protected UserInOrganization(User user, OrganizationRole role) { if (user == null) throw new DomainException("Can not create new user in organization from empty user."); Id = user.Id; Email = user.Email; Role = role; CreatedAt = DateTime.UtcNow; }
public static KitosCredentials GetCredentials(OrganizationRole role, bool apiAccess = false) { var userEnvironment = apiAccess ? ApiUsersFromEnvironment : UsersFromEnvironment; if (userEnvironment.TryGetValue(role, out var credentials)) { return(credentials); } throw new ArgumentNullException($"No environment {(apiAccess ? "api " : "")}user configured for role:{role:G}"); }
public Report CreateReport( string name, ReportTemplate template, User user, Organization organization, OrganizationRole organizationRole, Dictionary <string, dynamic> parameters) { Report report = _typeAdapter.Adapt <ReportTemplate, Report>(template); report.SetCreationOptions(parameters); var properties = new (string, object)[]
protected override void Seed(NotesContext context) { User system = new User { Name = NotesContext.ContextUserName, PasswordHash = NotesContext.ContextPasswordHash, PasswordSalt = NotesContext.ContextPasswordSalt, IsSystemOnly = true }; context.Users.Add(system); Role role = new Role { Name = NotesContext.ContextRoleName, IsSystemOnly = true }; context.Roles.Add(role); Organization org = new Organization { Name = NotesContext.ContextOrganizationName, IsSystemOnly = true }; context.Organizations.Add(org); OrganizationRole orgRole = new OrganizationRole { Organization = org, Role = role }; context.OrganizationRoles.Add(orgRole); OrganizationRoleUser systemOrgRole = new OrganizationRoleUser { User = system, OrganizationRole = orgRole }; context.OrganizationRoleUsers.Add(systemOrgRole); OrganizationUser systemOrg = new OrganizationUser { User = system, Organization = org }; context.OrganizationUsers.Add(systemOrg); base.Seed(context); }
public OrganizationOptionsBuilder WithAdminRole() { var adminRole = new OrganizationRole(); adminRole.Organization = this.Organization; this.Organization.Roles.Add(adminRole); adminRole.RoleName = "Admin"; adminRole.CanCreateProject = true; adminRole.CanManageMembers = true; return(this); }
protected UserInOrganization(User user, OrganizationRole role) { if (user == null) { throw new DomainException("Can not create new user in organization from empty user."); } Id = user.Id; Email = user.Email; Role = role; CreatedAt = DateTime.UtcNow; }
public async Task Cannot_Add_Communication(OrganizationRole role) { //Arrange var login = await HttpApi.GetCookieAsync(role); //Act - perform the action with the actual role using (var result = await ItProjectHelper.SendAddCommunicationRequestAsync(OrganizationId, _project.Id, A <string>(), A <string>(), A <string>(), TestEnvironment.DefaultUserId, A <string>(), A <DateTime>().Date, login)) { //Assert Assert.Equal(HttpStatusCode.Forbidden, result.StatusCode); } }
private static async Task <HttpResponseMessage> GetUnusedSystemsAsync(OrganizationRole role, int organizationId, string nameContent, int take, bool getPublic) { var cookie = await HttpApi.GetCookieAsync(role); var url = TestEnvironment.CreateUrl($"api/v1/ItSystemUsageMigration/UnusedItSystems" + $"?organizationId={organizationId}" + $"&nameContent={nameContent}" + $"&numberOfItSystems={take}" + $"&getPublicFromOtherOrganizations={getPublic}"); return(await HttpApi.GetWithCookieAsync(url, cookie)); }
public async Task <IActionResult> Post([FromRoute] string orgRoleId, [FromBody] ReportTemplateVM reportTemplateVM) { if (string.IsNullOrWhiteSpace(orgRoleId) || string.IsNullOrEmpty(orgRoleId)) { return(StatusCode(StatusCodes.Status400BadRequest, new BadRequestError($"'{nameof(orgRoleId)}' cannot be null or whitespace"))); } if (!ModelState.IsValid) { return(BadRequest(ModelState)); } OrganizationRole organizationRole = organizationRoleService .Get <OrganizationRole>(orgRole => orgRole.Id == orgRoleId, asNoTracking: true); if (organizationRole == null) { return(StatusCode(StatusCodes.Status404NotFound, new NotFoundError($"OrganizationRole not found"))); } User user = await GetCurrentUser(); if (user == null) { return(StatusCode(StatusCodes.Status404NotFound, new NotFoundError("Current user not found"))); } ReportTemplateDto reportTemplateDto = _typeAdapter.Adapt <ReportTemplateVM, ReportTemplateDto>(reportTemplateVM); var reportTemplateCreationDto = new ReportTemplateCreationDto { UserId = user.Id, ReportTemplateDto = reportTemplateDto }; ReportTemplate reportTemplate = reportTemplateService.Add(reportTemplateCreationDto); _unitOfWork.SaveChanges(); return(CreatedAtAction( actionName: nameof(Get), routeValues: new { version = $"{HttpContext.GetRequestedApiVersion()}", orgRoleId = organizationRole.Id, templateId = reportTemplate.Id }, value: reportTemplate.Id)); }
public async Task Get_Kle_Changes_Returns_Forbidden(OrganizationRole role) { //Arrange var url = TestEnvironment.CreateUrl("api/v1/kle/changes"); var login = await HttpApi.GetCookieAsync(role); //Act using (var response = await HttpApi.GetWithCookieAsync(url, login)) { //Assert Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode); } }
public async Task Can_Not_Save_Configuration_If_Not_Allowed(OrganizationRole orgRole) { //Arrange var overviewType = A <OverviewType>(); var config = A <string>(); var cookie = await HttpApi.GetCookieAsync(orgRole); //Act using var response = await KendoOverviewConfigurationHelper.SendSaveConfigurationRequestAsync(TestEnvironment.DefaultOrganizationId, overviewType, config, cookie); //Assert Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode); }
private User CreateUserWithOrganizationRole(Organization organization, OrganizationRole role) { User user = new User { Id = Guid.NewGuid().ToString() }; user.OrganizationAssociations.Add(new OrganizationUser { User = user, UserId = user.Id, Organization = organization, OrganizationId = organization.Id, Role = role }); var task = userManager.CreateAsync(user); while (!task.IsCompleted) { } return user; }
public static UserInOrganization Create(User user, OrganizationRole role = OrganizationRole.User) => new UserInOrganization(user, role);