Example #1
0
        public static BadRequestException InvalidColumnsException(IReadOnlyList <ProfileColumn> invalidColumns)
        {
            if (invalidColumns.IsEmpty())
            {
                throw new ArgumentException(nameof(invalidColumns));
            }

            string message;

            if (invalidColumns.Count == 1)
            {
                message = I18NHelper.FormatInvariant(
                    ErrorMessages.ArtifactList.ColumnsSettings.SingleInvalidColumn,
                    invalidColumns.First().PropertyName);
            }
            else
            {
                const int maxPropertiesToShow = 3;

                message = I18NHelper.FormatInvariant(
                    invalidColumns.Count > maxPropertiesToShow ?
                    ErrorMessages.ArtifactList.ColumnsSettings.MultipleInvalidColumns :
                    ErrorMessages.ArtifactList.ColumnsSettings.SomeInvalidColumns,
                    string.Join(", ", invalidColumns.Take(maxPropertiesToShow).Select(column => column.PropertyName)));
            }

            return(new BadRequestException(message, ErrorCodes.InvalidColumns));
        }
        public void TestGetSupportedOperationsDisplayItemsWithBool(string cultureName, string search, string expected)
        {
            if (!string.IsNullOrEmpty(cultureName))
            {
                var culture = CultureInfo.CreateSpecificCulture(cultureName);
                Thread.CurrentThread.CurrentCulture   = culture;
                Thread.CurrentThread.CurrentUICulture = culture;

                I18NHelper.LoadLanguage(culture.TwoLetterISOLanguageName);
            }
            else
            {
                I18NHelper.LoadDefaultLanguage();
            }


            var items = OperationHelper.GetSupportedOperationsDisplayItemsLocalized(typeof(string));

            Assert.IsNotNull(items);
            Assert.IsTrue(items.Length > 0);

            // Act
            var result = items.FirstOrDefault(x => x.Id == search);


            // Assert
            Assert.IsNotNull(result);

            Assert.AreEqual(expected, result.Name);
        }
Example #3
0
        public static BadRequestException ColumnCapacityExceededException(string columnName, int maxCapacity)
        {
            var errorMessage = I18NHelper.FormatInvariant(
                ErrorMessages.ArtifactList.ColumnCapacityExceeded, columnName, maxCapacity);

            return(new BadRequestException(errorMessage, ErrorCodes.BadRequest));
        }
Example #4
0
        private bool UserExistsInLdapDirectory(LdapSettings ldapSettings, LoginInfo loginInfo)
        {
            var userName = loginInfo.UserName != null?loginInfo.UserName.Trim() : loginInfo.Login;

            var filter = I18NHelper.FormatInvariant("(&(objectCategory={0})({1}={2}))", ldapSettings.GetEffectiveUserObjectCategoryAttribute(), ldapSettings.GetEffectiveAccountNameAttribute(), LdapHelper.EscapeLdapSearchFilter(userName));

            try
            {
                var found = _authenticator.SearchLdap(ldapSettings, filter);

                if (found)
                {
                    return(true);
                }

                _log.LogInformation(LogSourceLdap, I18NHelper.FormatInvariant("User '{0}' is not found in LDAP directory {1}", userName, ldapSettings.LdapAuthenticationUrl));

                return(false);
            }
            catch (Exception ex)
            {
                _log.LogInformation(LogSourceLdap, I18NHelper.FormatInvariant("Error while searching a user in LDAP directory {0}", ldapSettings.LdapAuthenticationUrl));
                _log.LogError(LogSourceLdap, ex);

                return(false);
            }
        }
        public async Task Search_NotFoundArtifact_ResourceNotFoundException()
        {
            // arrange
            ArtifactBasicDetails artifactBasicDetails = null;

            _sqlArtifactRepositoryMock.Setup(q => q.GetArtifactBasicDetails(ScopeId, UserId, null)).ReturnsAsync(artifactBasicDetails);
            _searchEngineRepositoryMock.Setup(q => q.GetCollectionContentSearchArtifactResults(ScopeId, _pagination, true, UserId, null)).ReturnsAsync(_searchArtifactsResult);
            var errorMessage   = I18NHelper.FormatInvariant(ErrorMessages.ArtifactNotFound, ScopeId);
            var excectedResult = new ResourceNotFoundException(errorMessage, ErrorCodes.ResourceNotFound);
            ResourceNotFoundException exception = null;

            // act
            try
            {
                await _searchEngineService.Search(ScopeId, _pagination, ScopeType.Contents, true, UserId);
            }
            catch (ResourceNotFoundException ex)
            {
                exception = ex;
            }

            // assert
            Assert.IsNotNull(exception);
            Assert.AreEqual(excectedResult.Message, exception.Message);
        }
Example #6
0
        public async Task <ReviewSettings> UpdateReviewSettingsAsync(int reviewId, ReviewSettings updatedReviewSettings, bool autoSave, int userId)
        {
            var reviewInfo = await GetReviewInfoAsync(reviewId, userId);

            if (!await _permissionsRepository.HasEditPermissions(reviewId, userId))
            {
                throw ReviewsExceptionHelper.UserCannotModifyReviewException(reviewId);
            }

            var reviewData = await _reviewsRepository.GetReviewAsync(reviewId, userId);

            if (reviewData.ReviewStatus == ReviewPackageStatus.Closed)
            {
                throw new ConflictException(I18NHelper.FormatInvariant(ErrorMessages.ReviewIsClosed, reviewId), ErrorCodes.ReviewClosed);
            }

            await LockReviewAsync(reviewId, userId, reviewInfo);

            UpdateEndDate(updatedReviewSettings, autoSave, reviewData.ReviewPackageRawData);
            UpdateShowOnlyDescription(updatedReviewSettings, reviewData.ReviewPackageRawData);
            UpdateCanMarkAsComplete(reviewId, updatedReviewSettings, reviewData.ReviewPackageRawData);

            UpdateRequireESignature(reviewData.ReviewType, updatedReviewSettings, reviewData.ReviewPackageRawData);
            await UpdateRequireMeaningOfSignatureAsync(reviewInfo.ItemId, userId, reviewInfo.ProjectId, reviewData.ReviewType, updatedReviewSettings, reviewData.ReviewPackageRawData);

            await _reviewsRepository.UpdateReviewPackageRawDataAsync(reviewId, reviewData.ReviewPackageRawData, userId);

            return(await GetReviewSettingsFromReviewData(reviewData, reviewInfo));
        }
Example #7
0
        private static bool Compare <T>(T obj1, T obj2, out string message)
        {
            message = null;
            if (obj1 == null && obj2 == null)
            {
                return(true);
            }
            if (obj1 == null || obj2 == null)
            {
                message = "One of the objects is null.";
                return(false);
            }

            var serializer  = new XmlSerializer(obj1.GetType());
            var serialized1 = new StringWriter(CultureInfo.InvariantCulture);
            var serialized2 = new StringWriter(CultureInfo.InvariantCulture);

            serializer.Serialize(serialized1, obj1);
            serializer.Serialize(serialized2, obj2);
            var str1     = serialized1.ToString();
            var str2     = serialized2.ToString();
            var areEqual = str1 == str2;

            if (!areEqual)
            {
                message = I18NHelper.FormatInvariant("object 1:\r\n{0}\r\nobject 2:\r\n{1}", str1, str2);
            }
            return(areEqual);
        }
Example #8
0
        public async Task DeleteProject(int userId, int projectId)
        {
            ProjectStatus?projectStatus;

            InstanceItem project = await _instanceRepository.GetInstanceProjectAsync(projectId, userId, fromAdminPortal : true);

            if (!TryGetProjectStatusIfProjectExist(project, out projectStatus))
            {
                throw new ResourceNotFoundException(
                          I18NHelper.FormatInvariant(ErrorMessages.ProjectWasDeletedByAnotherUser, project.Id,
                                                     project.Name), ErrorCodes.ResourceNotFound);
            }

            if (projectStatus == ProjectStatus.Live)
            {
                Func <IDbTransaction, long, Task> action = async(transaction, transactionId) =>
                {
                    var revisionId = await _instanceRepository.RemoveProject(userId, projectId, transaction);

                    await _instanceRepository.DeactivateWorkflowsWithLastAssignmentForDeletedProject(projectId, transaction);

                    var artifactIds = await _instanceRepository.GetProjectArtifactIds(projectId, revisionId - 1, userId, transaction : transaction);
                    await PostOperation(artifactIds, revisionId, userId, transactionId, transaction);
                };

                await _instanceRepository.RunInTransactionAsync(action);
            }
            else
            {
                await _instanceRepository.PurgeProject(projectId, project);
            }
        }
        public async Task <IEnumerable <Reply> > GetReplies(int artifactId, int discussionId, int?subArtifactId = null)
        {
            ValidateRequestParameters(artifactId, subArtifactId);

            if (discussionId < 1)
            {
                throw new BadRequestException(I18NHelper.FormatInvariant("Parameter: {0} is out of the range of valid values", nameof(discussionId)));
            }

            var userId = Session.UserId;

            var itemId     = subArtifactId.HasValue ? subArtifactId.Value : artifactId;
            var revisionId = int.MaxValue;
            var isDeleted  = await _artifactVersionsRepository.IsItemDeleted(itemId);

            var itemInfo = isDeleted ?
                           await _artifactVersionsRepository.GetDeletedItemInfo(itemId) :
                           await _artifactPermissionsRepository.GetItemInfo(itemId, userId, false);

            if (itemInfo == null || await _discussionsRepository.IsDiscussionDeleted(discussionId))
            {
                throw new ResourceNotFoundException();
            }

            if (subArtifactId.HasValue && itemInfo.ArtifactId != artifactId)
            {
                throw new BadRequestException("Please provide a proper subartifact Id");
            }

            if (isDeleted)
            {
                revisionId = ((DeletedItemInfo)itemInfo).VersionId;
            }

            var permissions = await _artifactPermissionsRepository.GetArtifactPermissions(new[] { artifactId }, Session.UserId, false, revisionId);

            if (permissions.IsEmpty())
            {
                permissions = await _artifactPermissionsRepository.GetArtifactPermissionDirectly(itemId, Session.UserId, itemInfo.ProjectId);
            }
            var projectPermissions = await _artifactPermissionsRepository.GetProjectPermissions(itemInfo.ProjectId);

            RolePermissions permission = RolePermissions.None;

            if (!permissions.TryGetValue(artifactId, out permission) || !permission.HasFlag(RolePermissions.Read))
            {
                throw new AuthorizationException("You do not have permission to access the artifact");
            }
            var result = await _discussionsRepository.GetReplies(discussionId, itemInfo.ProjectId);

            foreach (var reply in result)
            {
                reply.CanDelete = !projectPermissions.HasFlag(ProjectPermissions.CommentsDeletionDisabled) && permissions.TryGetValue(artifactId, out permission) &&
                                  (permission.HasFlag(RolePermissions.DeleteAnyComment) || (permission.HasFlag(RolePermissions.Comment) && reply.UserId == userId));
                reply.CanEdit = !projectPermissions.HasFlag(ProjectPermissions.CommentsModificationDisabled) &&
                                permissions.TryGetValue(artifactId, out permission) && (permission.HasFlag(RolePermissions.Comment) && reply.UserId == userId);
            }

            return(result);
        }
Example #10
0
        private async Task ValidateArtifact(VersionControlArtifactInfo artifactInfo)
        {
            // Confirm that the artifact is not deleted
            var isDeleted = await _stateChangeExecutorRepositories.ArtifactVersionsRepository.IsItemDeleted(_input.ArtifactId);

            if (isDeleted)
            {
                throw new ConflictException(I18NHelper.FormatInvariant("Artifact has been deleted and is no longer available for workflow state change. Please refresh your view."));
            }

            if (artifactInfo.IsDeleted)
            {
                throw new ConflictException(I18NHelper.FormatInvariant("Artifact has been deleted and is no longer available for workflow state change. Please refresh your view."));
            }

            if (artifactInfo.VersionCount != _input.CurrentVersionId)
            {
                throw new ConflictException(I18NHelper.FormatInvariant("Artifact has been updated. The current version of the artifact {0} does not match the specified version {1}. Please refresh your view.", artifactInfo.VersionCount, _input.CurrentVersionId));
            }

            // Lock is obtained by current user inside the stored procedure itself
            // Check that it is not locked by some other user
            if (artifactInfo.LockedByUser != null && artifactInfo.LockedByUser.Id != _userId)
            {
                throw new ConflictException(I18NHelper.FormatInvariant("Artifact has been updated. Artifact is locked by another user. Please refresh your view."));
            }
        }
Example #11
0
        private static XmlPropertyChangeAction ToXmlModel(IePropertyChangeAction ieAction, WorkflowDataMaps dataMaps)
        {
            if (ieAction == null)
            {
                return(null);
            }

            var xmlAction = new XmlPropertyChangeAction
            {
                Name          = ieAction.Name,
                PropertyValue = ieAction.PropertyValue,
                UsersGroups   = ToXmlModel(ieAction.UsersGroups, dataMaps)
            };

            int propertyTypeId;

            if (!dataMaps.PropertyTypeMap.TryGetValue(ieAction.PropertyName, out propertyTypeId) &&
                !WorkflowHelper.TryGetNameOrDescriptionPropertyTypeId(ieAction.PropertyName, out propertyTypeId))
            {
                throw new ExceptionWithErrorCode(I18NHelper.FormatInvariant("Id of Standard Property Type '{0}' is not found.", ieAction.PropertyName),
                                                 ErrorCodes.UnexpectedError);
            }
            xmlAction.PropertyTypeId = propertyTypeId;

            ToXmlModel(ieAction.ValidValues, propertyTypeId, ieAction.PropertyName, dataMaps, xmlAction);

            return(xmlAction);
        }
Example #12
0
        private async Task <int> SaveSettingsAsync(int itemId, int userId, ProfileSettingsParams profileSettings)
        {
            if (profileSettings == null)
            {
                throw new ArgumentException(I18NHelper.FormatInvariant(
                                                ErrorMessages.ArtifactList.SaveProfileSettingsProfileSettingsNull));
            }

            var existingSettings = await _artifactListSettingsRepository.GetSettingsAsync(itemId, userId);

            var settings =
                new XmlProfileSettings
            {
                Columns = !profileSettings.ColumnsUndefined
                        ? ArtifactListHelper.ConvertProfileColumnsToXmlProfileSettings(profileSettings.Columns)
                        : existingSettings?.Columns,
                PaginationLimit = !profileSettings.PaginationLimitUndefined ? profileSettings.PaginationLimit : existingSettings?.PaginationLimit,
            };

            if (existingSettings == null)
            {
                return(await _artifactListSettingsRepository.CreateSettingsAsync(itemId, userId, settings));
            }
            else
            {
                return(await _artifactListSettingsRepository.UpdateSettingsAsync(itemId, userId, settings));
            }
        }
Example #13
0
        private static XmlEmailNotificationAction ToXmlModel(IeEmailNotificationAction ieAction, IDictionary <string, int> propertyTypeMap)
        {
            if (ieAction == null)
            {
                return(null);
            }

            var xmlAction = new XmlEmailNotificationAction
            {
                Name    = ieAction.Name,
                Emails  = ieAction.Emails,
                Message = ieAction.Message
            };

            if (ieAction.PropertyName != null)
            {
                int propertyTypeId;
                if (!propertyTypeMap.TryGetValue(ieAction.PropertyName, out propertyTypeId))
                {
                    throw new ExceptionWithErrorCode(
                              I18NHelper.FormatInvariant("Id of Standard Property Type '{0}' is not found.",
                                                         ieAction.PropertyName),
                              ErrorCodes.UnexpectedError);
                }
                xmlAction.PropertyTypeId = propertyTypeId;
            }
            return(xmlAction);
        }
        private static int?FindDefaultValidValueId(List <XmlCustomPropertyValidValue> validValues)
        {
            if (validValues == null)
            {
                return(null);
            }

            var orderedValidValues = validValues.OrderBy(v => I18NHelper.Int32ParseInvariant(v.OrderIndex)).ToList();

            for (var i = 0; i < orderedValidValues.Count; i++)
            {
                var validValue = orderedValidValues.ElementAt(i);
                if (validValue?.Selected == "1")
                {
                    int?vvId = null;
                    if (!string.IsNullOrWhiteSpace(validValue.LookupListItemId))
                    {
                        int intValue;
                        if (int.TryParse(validValue.LookupListItemId, out intValue))
                        {
                            vvId = intValue;
                        }
                    }
                    return(vvId);
                }
            }

            return(null);
        }
Example #15
0
 /// <summary>
 /// Throws an exception if the argumentValue is less than lowerValue.
 /// </summary>
 /// <typeparam name="T">A type that implements <see cref="IComparable"/>.</typeparam>
 /// <param name="lowerValue">The lower value accepted as valid.</param>
 /// <param name="argumentValue">The argument value to test.</param>
 /// <param name="argumentName">Name of the argument.</param>
 /// <exception cref="System.ArgumentOutOfRangeException">Validation error.</exception>
 public static void ArgumentGreaterOrEqualThan <T>(T lowerValue, T argumentValue, string argumentName) where T : struct, IComparable
 {
     if (argumentValue.CompareTo((T)lowerValue) < 0)
     {
         throw new ArgumentOutOfRangeException(argumentName, argumentValue, I18NHelper.FormatInvariant("The size of '{0}' should be greater or equal to '{1}'.", argumentName, lowerValue));
     }
 }
        public static PropertyType ConvertToPropertyType(this SqlProjectMetaRepository.PropertyTypeVersion pv)
        {
            // Property XmlInfo is not supposed to be null, see bug 4819
            var propertyFromXml = pv.PrimitiveType == PropertyPrimitiveType.Choice
                ? XmlModelSerializer.DeserializeCustomProperties(pv.XmlInfo).CustomProperties[0]
                : null;

            return(new PropertyType
            {
                Id = pv.PropertyTypeId,
                Name = pv.Name,
                VersionId = pv.VersionId,
                InstancePropertyTypeId = pv.InstancePropertyTypeId,
                PrimitiveType = pv.PrimitiveType,
                IsRichText = pv.PrimitiveType == PropertyPrimitiveType.Text ? pv.RichText : null,
                IsRequired = pv.Required,
                IsValidated = pv.PrimitiveType == PropertyPrimitiveType.Number ||
                              pv.PrimitiveType == PropertyPrimitiveType.Date ||
                              pv.PrimitiveType == PropertyPrimitiveType.Choice
                                    ? pv.Validate : null,
                IsMultipleAllowed = pv.PrimitiveType == PropertyPrimitiveType.Text ||
                                    pv.PrimitiveType == PropertyPrimitiveType.Choice
                                    ? pv.AllowMultiple : null,
                StringDefaultValue = pv.PrimitiveType == PropertyPrimitiveType.Text ? pv.StringDefaultValue : null,
                DateDefaultValue = pv.PrimitiveType == PropertyPrimitiveType.Date ? pv.DateDefaultValue : null,
                DecimalDefaultValue = pv.PrimitiveType == PropertyPrimitiveType.Number
                                      ? PropertyHelper.ToDecimal(pv.DecimalDefaultValue) : null,
                UserGroupDefaultValue = pv.PrimitiveType == PropertyPrimitiveType.User
                                      ? PropertyHelper.ParseUserGroups(pv.UserDefaultValue) : null,
                MinDate = pv.PrimitiveType == PropertyPrimitiveType.Date && pv.Validate.GetValueOrDefault() ? pv.MinDate : null,
                MaxDate = pv.PrimitiveType == PropertyPrimitiveType.Date && pv.Validate.GetValueOrDefault() ? pv.MaxDate : null,
                MinNumber = pv.PrimitiveType == PropertyPrimitiveType.Number && pv.Validate.GetValueOrDefault()
                                      ? PropertyHelper.ToDecimal(pv.MinNumber) : null,
                MaxNumber = pv.PrimitiveType == PropertyPrimitiveType.Number && pv.Validate.GetValueOrDefault()
                                      ? PropertyHelper.ToDecimal(pv.MaxNumber) : null,
                DecimalPlaces = pv.PrimitiveType == PropertyPrimitiveType.Number ? pv.DecimalPlaces : null,
                ValidValues = pv.PrimitiveType == PropertyPrimitiveType.Choice
                                      ? propertyFromXml?.ValidValues.OrderBy(v => I18NHelper.Int32ParseInvariant(v.OrderIndex))
                              .Select(v =>
                {
                    int?vvId = null;
                    if (!string.IsNullOrWhiteSpace(v.LookupListItemId))
                    {
                        int intValue;
                        if (int.TryParse(v.LookupListItemId, out intValue))
                        {
                            vvId = intValue;
                        }
                    }
                    return new ValidValue {
                        Id = vvId, Value = v.Value
                    };
                }).ToList()
                                      : null,
                DefaultValidValueId = pv.PrimitiveType == PropertyPrimitiveType.Choice
                                      ? FindDefaultValidValueId(propertyFromXml.ValidValues) // TODO
                                      : null,
            });
        }
        public async Task GetFile_FileAlreadyExpiredBeforeNow_NotFound()
        {
            // Arrange
            var moq = new Mock <IFilesRepository>();
            var moqFileStreamRepo = new Mock <IFileStreamRepository>();
            var moqConfigRepo     = new Mock <IConfigRepository>();
            var moqLog            = new Mock <sl.IServiceLogRepository>();
            var contentString     = "Test2 content";
            var fileChunk         = new FileChunk()
            {
                ChunkNum     = 1,
                ChunkContent = Encoding.UTF8.GetBytes(contentString),
                ChunkSize    = Encoding.UTF8.GetBytes(contentString).Length
            };
            var file = new File
            {
                FileId      = new Guid("22222222-2222-2222-2222-222222222222"),
                FileName    = "Test2.txt",
                StoredTime  = I18NHelper.DateTimeParseExactInvariant("2015-09-05T22:57:31.7824054-04:00", "o"),
                FileType    = "application/octet-stream",
                FileSize    = fileChunk.ChunkSize,
                ChunkCount  = 1,
                ExpiredTime = DateTime.UtcNow
            };

            var moqDbConnection = new Mock <DbConnection>();

            moq.Setup(t => t.CreateConnection()).Returns(moqDbConnection.Object);

            moq.Setup(t => t.GetFileHead(It.IsAny <Guid>())).ReturnsAsync(file);
            moq.Setup(t => t.GetFileInfo(It.IsAny <Guid>())).Returns(file);

            moq.Setup(t => t.ReadChunkContent(moqDbConnection.Object, file.FileId, 1)).Returns(fileChunk.ChunkContent);

            moqConfigRepo.Setup(t => t.FileChunkSize).Returns(1 * 1024 * 1024);

            var controller = new FilesController(moq.Object, moqFileStreamRepo.Object, moqConfigRepo.Object, moqLog.Object)
            {
                Request = new HttpRequestMessage
                {
                    RequestUri = new Uri("http://localhost/files")
                },
                Configuration = new HttpConfiguration()
            };

            controller.Configuration.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "files/{id}",
                defaults: new { id = RouteParameter.Optional });

            // Act
            var actionResult = await controller.GetFileContent("22222222222222222222222222222222");

            System.Threading.CancellationToken cancellationToken = new System.Threading.CancellationToken();
            HttpResponseMessage response = await actionResult.ExecuteAsync(cancellationToken);

            // Assert
            Assert.IsTrue(response.StatusCode == HttpStatusCode.NotFound, "Expired file should return status code as NotFound");
        }
        public static ResourceNotFoundException ReviewNotFoundException(int reviewId, int revisionId = int.MaxValue)
        {
            var errorMessage = revisionId != int.MaxValue ?
                               I18NHelper.FormatInvariant("Review (Id:{0}) or its revision (#{1}) is not found.", reviewId, revisionId) :
                               I18NHelper.FormatInvariant("Review (Id:{0}) is not found.", reviewId);

            return(new ResourceNotFoundException(errorMessage, ErrorCodes.ResourceNotFound));
        }
Example #19
0
 public static I18NHelper GetInstance()
 {
     if (null == instance)
     {
         instance = new I18NHelper();
     }
     return(instance);
 }
Example #20
0
 /// <summary>
 /// 阿拉伯数字转为汉字(支持0-9)
 /// </summary>
 /// <param name="number"></param>
 /// <returns></returns>
 public static string GetChineseNumber(int number)
 {
     if (number >= 0 && number <= 9)
     {
         return(I18NHelper.GetText(chineseNumIndex + number));
     }
     Debug.LogWarning(string.Format("输入的数字{0}不在0~9范围内!", number));
     return("");
 }
Example #21
0
        public async Task <AuthenticationUser> AuthenticateSamlUserAsync(string samlResponse)
        {
            if (string.IsNullOrEmpty(samlResponse))
            {
                throw new FormatException("Saml response cannot be empty");
            }

            var instanceSettings = await _settingsRepository.GetInstanceSettingsAsync();

            if (!instanceSettings.IsSamlEnabled.GetValueOrDefault())
            {
                throw new AuthenticationException("Federated Authentication mechanism must be enabled");
            }

            var fedAuthSettings = await _settingsRepository.GetFederatedAuthenticationSettingsAsync();

            if (fedAuthSettings == null)
            {
                throw new AuthenticationException("Federated Authentication settings must be provided");
            }

            var principal           = _samlRepository.ProcessEncodedResponse(samlResponse, fedAuthSettings);
            AuthenticationUser user = null;

            if (fedAuthSettings.IsAllowingNoDomain)
            {
                foreach (var allowedDomain in fedAuthSettings.DomainList.OrderBy(l => l.OrderIndex))
                {
                    user = await _userRepository.GetUserByLoginAsync($"{allowedDomain.Name}\\{principal.Identity.Name}");

                    if (user != null)
                    {
                        break;
                    }
                }
            }
            else
            {
                user = await _userRepository.GetUserByLoginAsync(principal.Identity.Name);
            }

            if (user == null) // cannot find user in the DB
            {
                await _log.LogInformation(WebApiConfig.LogSourceSessions, I18NHelper.FormatInvariant("Could not get user with login '{0}'. NameClaimType '{1}'", principal.Identity.Name, fedAuthSettings.NameClaimType));

                throw new AuthenticationException("Invalid user name or password", ErrorCodes.InvalidCredentials);
            }

            if (!user.IsEnabled)
            {
                throw new AuthenticationException(I18NHelper.FormatInvariant("Your account '{0}' has been locked out, please contact your Blueprint Instance Administrator.", user.Login), ErrorCodes.AccountIsLocked);
            }

            user.LicenseType = await _userRepository.GetEffectiveUserLicenseAsync(user.Id);

            return(user);
        }
        public async Task Read_File_Chunks_Success()
        {
            // This tests reading file chunks and pushing them to the output stream

            // Arrange
            var moqFilesRepo  = new Mock <IFilesRepository>();
            var moqConfigRepo = new Mock <IConfigRepository>();

            int fileChunkSize = 125;
            var contentString = GetRandomString(125);

            // set the size of the content to force two loops to retrieve total of 250 bytes
            byte[] fileStreamContent = Encoding.UTF8.GetBytes(contentString + contentString);

            var file = new File
            {
                FileId     = new Guid("22222222-2222-2222-2222-222222222222"),
                FileName   = "Test2.txt",
                StoredTime = I18NHelper.DateTimeParseExactInvariant("2015-09-05T22:57:31.7824054-04:00", "o"),
                FileType   = "application/octet-stream",
                FileSize   = fileStreamContent.Length,
                ChunkCount = 2
            };

            var moqDbConnection = new Mock <DbConnection>();

            moqFilesRepo.Setup(t => t.CreateConnection()).Returns(moqDbConnection.Object);

            moqFilesRepo.Setup(t => t.GetFileHead(It.IsAny <Guid>())).ReturnsAsync(file);

            moqFilesRepo.Setup(t => t.ReadChunkContent(moqDbConnection.Object, It.IsAny <Guid>(), It.IsAny <int>())).Returns(fileStreamContent.Take <byte>(125).ToArray <byte>());

            moqConfigRepo.Setup(t => t.LegacyFileChunkSize).Returns(fileChunkSize);

            moqFilesRepo.Setup(t => t.GetFileInfo(It.IsAny <Guid>())).Returns(file);

            // Act
            SqlPushStream sqlPushStream = new SqlPushStream();

            sqlPushStream.Initialize(moqFilesRepo.Object, file.FileId);

            HttpContent responseContent = new PushStreamContent(sqlPushStream.WriteToStream, new MediaTypeHeaderValue(file.ContentType));

            Stream response = await responseContent.ReadAsStreamAsync();

            string originalContent = Encoding.UTF8.GetString(fileStreamContent);
            string resultContent   = string.Empty;

            using (var memoryStream = new MemoryStream())
            {
                response.CopyTo(memoryStream);
                resultContent = Encoding.UTF8.GetString(memoryStream.ToArray());
            }

            // Assert
            Assert.IsTrue(originalContent.Equals(resultContent));
        }
Example #23
0
        public async Task HeadFile_GetHeadForExistentFileStreamFile_Success()
        {
            // Arrange
            var moq = new Mock <IFilesRepository>();
            var moqFileStreamRepo = new Mock <IFileStreamRepository>();
            var moqConfigRepo     = new Mock <IConfigRepository>();
            var moqLog            = new Mock <sl.IServiceLogRepository>();

            var file = new File
            {
                FileId       = new Guid("33333333-3333-3333-3333-333333333333"),
                FileName     = "Test3.txt",
                StoredTime   = I18NHelper.DateTimeParseExactInvariant("2015-09-05T22:57:31.7824054-04:00", "o"),
                FileType     = "text/html",
                ChunkCount   = 1,
                IsLegacyFile = true
            };

            moq.Setup(t => t.GetFileHead(It.IsAny <Guid>())).ReturnsAsync((File)null);

            moqFileStreamRepo.Setup(t => t.FileExists(file.FileId)).Returns(true);
            moqFileStreamRepo.Setup(t => t.GetFileHead(file.FileId)).Returns(file);

            var controller = new FilesController(moq.Object, moqFileStreamRepo.Object, moqConfigRepo.Object, moqLog.Object)
            {
                Request = new HttpRequestMessage
                {
                    RequestUri = new Uri("http://localhost/files"),
                    Method     = HttpMethod.Head
                },
                Configuration = new HttpConfiguration()
            };

            controller.Configuration.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "files/{id}",
                defaults: new { id = RouteParameter.Optional });

            // Act
            var actionResult = await controller.GetFileHead("33333333333333333333333333333333");

            System.Threading.CancellationToken cancellationToken = new System.Threading.CancellationToken();
            HttpResponseMessage response = await actionResult.ExecuteAsync(cancellationToken);

            var content     = response.Content;
            var contentType = content.Headers.ContentType;
            var fileName    = content.Headers.ContentDisposition.FileName;
            var storedTime  = response.Headers.GetValues("Stored-Date");

            // Assert
            Assert.IsTrue(response.IsSuccessStatusCode);
            Assert.AreEqual("Test3.txt", fileName);
            Assert.AreEqual("application/octet-stream", contentType.MediaType, string.Format("Returned content type {0} does not match expected {1}", contentType, "text/html"));
            Assert.AreEqual(DateTime.Parse("2015-09-05T22:57:31.7824054-04:00"), DateTime.Parse(storedTime.First()));
        }
Example #24
0
        // public static SamlSecurityToken CreateSamlSecurityToken(byte[] certificate, string password, params Claim[] claims)
        // {
        //    const string acsUrl = "http://blueprintsys.com";

        // var assertion = new SamlAssertion(new SamlNameIdentifier(DefaultIssuer));

        // var conditions = new Saml2Conditions
        //    {
        //        NotBefore = DateTime.UtcNow,
        //        NotOnOrAfter = DateTime.MaxValue
        //    };
        //    conditions.AudienceRestrictions.Add(new Saml2AudienceRestriction(new Uri(acsUrl, UriKind.RelativeOrAbsolute)));
        //    assertion.Conditions = conditions;

        // var subject = new Saml2Subject();
        //    subject.SubjectConfirmations.Add(new Saml2SubjectConfirmation(Bearer));
        //    assertion.Subject = subject;

        // var statement = new Saml2AttributeStatement();
        //    foreach (var claim in claims)
        //    {
        //        statement.Attributes.Add(new Saml2Attribute(claim.Type, claim.Value));
        //        assertion.Statements.Add(statement);
        //    }

        // var clientSigningCredentials = new X509SigningCredentials(
        //            new X509Certificate2(certificate, password, X509KeyStorageFlags.MachineKeySet | X509KeyStorageFlags.Exportable));

        // assertion.SigningCredentials = clientSigningCredentials;

        // return new Saml2SecurityToken(assertion);
        // }

        public static string Serialize(Saml2SecurityToken token)
        {
            var handler = new Saml2SecurityTokenHandler();
            var sw      = I18NHelper.CreateStringWriterInvariant();

            using (var textWriter = new XmlTextWriter(sw))
            {
                handler.WriteToken(textWriter, token);
                return(sw.ToString());
            }
        }
        public void InvalidColumnsException_AllParamsIsValid_OneProfileColumn_ReturnBadRequestException()
        {
            var expectedMessage = I18NHelper.FormatInvariant(
                ErrorMessages.ArtifactList.ColumnsSettings.SingleInvalidColumn,
                _profileColumns.First().PropertyName);

            var result = ArtifactListExceptionHelper.InvalidColumnsException(_profileColumns);

            Assert.IsNotNull(result);
            Assert.AreEqual(expectedMessage, result.Message);
        }
        public async Task <WorkflowTriggersContainer> GetWorkflowEventTriggersForTransition(int userId, int artifactId, int workflowId,
                                                                                            int fromStateId, int toStateId, int transitionId)
        {
            var desiredTransition = await GetTransitionForAssociatedStatesAsync(userId, artifactId, workflowId, fromStateId, toStateId, transitionId);

            if (desiredTransition == null)
            {
                throw new ConflictException(I18NHelper.FormatInvariant("No transitions available. Workflow could have been updated. Please refresh your view."));
            }
            return(GetWorkflowTriggersContainer(desiredTransition.Triggers));
        }
Example #27
0
        public async Task <AuthenticationUser> AuthenticateUserAsync(string login, string password, bool ignoreInvalidLoginAttempts)
        {
            if (string.IsNullOrEmpty(login) || string.IsNullOrEmpty(password))
            {
                throw new AuthenticationException("Username and password cannot be empty", ErrorCodes.EmptyCredentials);
            }

            var user = await _userRepository.GetUserByLoginAsync(login);

            if (user == null)
            {
                await _log.LogInformation(WebApiConfig.LogSourceSessions, I18NHelper.FormatInvariant("Could not get user with login '{0}'", login));

                throw new AuthenticationException("Invalid username or password", ErrorCodes.InvalidCredentials);
            }

            var instanceSettings = await _settingsRepository.GetInstanceSettingsAsync();

            if (instanceSettings.IsSamlEnabled.GetValueOrDefault())
            {
                // Fallback is allowed by default (value is null)
                if (!user.IsFallbackAllowed.GetValueOrDefault(true))
                {
                    throw new AuthenticationException("User must be authenticated via Federated Authentication mechanism", ErrorCodes.FallbackIsDisabled);
                }
            }

            AuthenticationStatus authenticationStatus;

            switch (user.Source)
            {
            case UserGroupSource.Database:
                authenticationStatus = AuthenticateDatabaseUser(user, password, instanceSettings.PasswordExpirationInDays);
                break;

            case UserGroupSource.Windows:
                if (!instanceSettings.IsLdapIntegrationEnabled)
                {
                    throw new AuthenticationException(string.Format("To authenticate user with login: {0}, ldap integration must be enabled", login), ErrorCodes.LdapIsDisabled);
                }
                authenticationStatus = await _ldapRepository.AuthenticateLdapUserAsync(login, password, instanceSettings.UseDefaultConnection);

                break;

            default:
                throw new AuthenticationException(string.Format("Authentication provider could not be found for login: {0}", login));
            }

            await ProcessAuthenticationStatus(authenticationStatus, user, instanceSettings, ignoreInvalidLoginAttempts);

            user.LicenseType = await _userRepository.GetEffectiveUserLicenseAsync(user.Id);

            return(user);
        }
Example #28
0
 /// <summary>
 /// Throws an exception if the tested TimeSpam argument is not a valid timeout value.
 /// </summary>
 /// <exception cref="ArgumentOutOfRangeException">Thrown if the argument is not null and is not a valid timeout value.</exception>
 /// <param name="argumentValue">Argument value to check.</param>
 /// <param name="argumentName">Name of argument being checked.</param>
 public static void ArgumentIsValidTimeout(TimeSpan?argumentValue, string argumentName)
 {
     if (argumentValue.HasValue)
     {
         long totalMilliseconds = (long)argumentValue.Value.TotalMilliseconds;
         if (totalMilliseconds < (long)-1 || totalMilliseconds > (long)2147483647)
         {
             throw new ArgumentOutOfRangeException(I18NHelper.FormatInvariant("The valid range for '{0}' is from 0 to 24.20:31:23.647", argumentName));
         }
     }
 }
Example #29
0
        public void ToInt32_NonNumericValue_ReturnsDefaultValue()
        {
            // Arrange
            const string s            = "foo";
            const int    defaultValue = 5;

            // Act
            int x = I18NHelper.ToInt32(s, defaultValue);

            // Assert
            Assert.AreEqual(x, 5, I18NHelper.FormatInvariant("I18NHelper.ToInt32 converted '{0}' into {1} instead of {2}!", s, x, defaultValue));
        }
Example #30
0
        public void TestLoadLanguage()
        {
            // Arrange
            var count = I18NHelper.Languages.Count;

            Assert.IsTrue(count > 0);

            // Act
            I18NHelper.LoadLanguage("DE");

            // Assert
            Assert.IsTrue(I18NHelper.Count > 0);
        }