diff --git a/.csscomb.json b/.csscomb.json index e353e6a63d..741cc1488b 100644 --- a/.csscomb.json +++ b/.csscomb.json @@ -1,16 +1,20 @@ { - "always-semicolon": true, - "color-case": "lower", - "block-indent": " ", - "color-shorthand": true, - "element-case": "lower", - "space-before-colon": "", - "space-after-colon": " ", - "space-before-combinator": " ", - "space-after-combinator": " ", - "space-between-declarations": "\n", - "space-before-opening-brace": " ", - "space-after-opening-brace": "\n", - "space-before-closing-brace": "\n", - "unitless-zero": true + "exclude": [ + "app/assets/stylesheets/framework/tw_bootstrap_variables.scss", + "app/assets/stylesheets/framework/fonts.scss" + ], + "always-semicolon": true, + "color-case": "lower", + "block-indent": " ", + "color-shorthand": true, + "element-case": "lower", + "space-before-colon": "", + "space-after-colon": " ", + "space-before-combinator": " ", + "space-after-combinator": " ", + "space-between-declarations": "\n", + "space-before-opening-brace": " ", + "space-after-opening-brace": "\n", + "space-before-closing-brace": "\n", + "unitless-zero": true } diff --git a/.gitlab-ci.yml b/.gitlab-ci.yml index 2ad63548d7..53f115c92c 100644 --- a/.gitlab-ci.yml +++ b/.gitlab-ci.yml @@ -128,7 +128,6 @@ scss-lint: - bundle exec rake scss_lint tags: - ruby - allow_failure: true brakeman: stage: test diff --git a/.scss-lint.yml b/.scss-lint.yml index e350b2073c..937d3407b6 100644 --- a/.scss-lint.yml +++ b/.scss-lint.yml @@ -100,7 +100,7 @@ linters: # Selectors should always use hyphenated-lowercase, rather than camelCase or # snake_case. SelectorFormat: - enabled: true + enabled: false convention: hyphenated_lowercase # Prefer the shortest shorthand form possible for properties that support it. diff --git a/CHANGELOG b/CHANGELOG index 7109c63ace..d9be95defd 100644 --- a/CHANGELOG +++ b/CHANGELOG @@ -1,9 +1,29 @@ Please view this file on the master branch, on stable branches it's out of date. -v 8.6.0 (unreleased) - - Add ability to move issue to another project - - Fix bug where wrong commit ID was being used in a merge request diff to show old image (Stan Hu) +v 8.7.0 (unreleased) + - Preserve time notes/comments have been updated at when moving issue - Make HTTP(s) label consistent on clone bar (Stan Hu) + - Fix avatar stretching by providing a cropping feature + +v 8.6.1 + - Add option to reload the schema before restoring a database backup. !2807 + - Display navigation controls on mobile. !3214 + - Fixed bug where participants would not work correctly on merge requests. !3329 + - Fix sorting issues by votes on the groups issues page results in SQL errors. !3333 + - Restrict notifications for confidential issues. !3334 + - Do not allow to move issue if it has not been persisted. !3340 + - Add a confirmation step before deleting an issuable. !3341 + - Fixes issue with signin button overflowing on mobile. !3342 + - Auto collapses the navigation sidebar when resizing. !3343 + - Fix build dependencies, when the dependency is a string. !3344 + - Shows error messages when trying to create label in dropdown menu. !3345 + - Fixes issue with assign milestone not loading milestone list. !3346 + - Fix an issue causing the Dashboard/Milestones page to be blank. !3348 + +v 8.6.0 + - Add ability to move issue to another project + - Prevent tokens in the import URL to be showed by the UI + - Fix bug where wrong commit ID was being used in a merge request diff to show old image (Stan Hu) - Add confidential issues - Bump gitlab_git to 9.0.3 (Stan Hu) - Fix diff image view modes (2-up, swipe, onion skin) not working (Stan Hu) @@ -18,9 +38,11 @@ v 8.6.0 (unreleased) setup. A password can be provided during setup (see installation docs), or GitLab will ask the user to create a new one upon first visit. - Fix issue when pushing to projects ending in .wiki + - Properly display YAML front matter in Markdown - Add support for wiki with UTF-8 page names (Hiroyuki Sato) - Fix wiki search results point to raw source (Hiroyuki Sato) - Don't load all of GitLab in mail_room + - Add information about `image` and `services` field at `job` level in the `.gitlab-ci.yml` documentation (Pat Turner) - HTTP error pages work independently from location and config (Artem Sidorenko) - Update `omniauth-saml` to 1.5.0 to allow for custom response attributes to be set - Memoize @group in Admin::GroupsController (Yatish Mehta) @@ -60,6 +82,7 @@ v 8.6.0 (unreleased) - User deletion is now done in the background so the request can not time out - Canceled builds are now ignored in compound build status if marked as `allowed to fail` - Trigger a todo for mentions on commits page + - Let project owners and admins soft delete issues and merge requests v 8.5.8 - Bump Git version requirement to 2.7.4 diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 7540fa1afc..511336f384 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -16,6 +16,7 @@ - [Issue tracker guidelines](#issue-tracker-guidelines) - [Issue weight](#issue-weight) - [Regression issues](#regression-issues) + - [Technical debt](#technical-debt) - [Merge requests](#merge-requests) - [Merge request guidelines](#merge-request-guidelines) - [Merge request description format](#merge-request-description-format) @@ -242,6 +243,28 @@ addressed. [8.3 Regressions]: https://gitlab.com/gitlab-org/gitlab-ce/issues/4127 [update the notes]: https://gitlab.com/gitlab-org/release-tools/blob/master/doc/pro-tips.md#update-the-regression-issue +### Technical debt + +In order to track things that can be improved in GitLab's codebase, we created +the ~"technical debt" label in [GitLab's issue tracker][ce-tracker]. + +This label should be added to issues that describe things that can be improved, +shortcuts that have been taken, code that needs refactoring, features that need +additional attention, and all other things that have been left behind due to +high velocity of development. + +Everyone can create an issue, though you may need to ask for adding a specific +label, if you do not have permissions to do it by yourself. Additional labels +can be combined with the `technical debt` label, to make it easier to schedule +the improvements for a release. + +Issues tagged with the `technical debt` label have the same priority like issues +that describe a new feature to be introduced in GitLab, and should be scheduled +for a release by the appropriate person. + +Make sure to mention the merge request that the `technical debt` issue is +associated with in the description of the issue. + ## Merge requests We welcome merge requests with fixes and improvements to GitLab code, tests, diff --git a/Gemfile.lock b/Gemfile.lock index 284964e7ec..16c09ab6e6 100644 --- a/Gemfile.lock +++ b/Gemfile.lock @@ -1064,6 +1064,3 @@ DEPENDENCIES web-console (~> 2.0) webmock (~> 1.21.0) wikicloth (= 0.8.1) - -BUNDLED WITH - 1.11.2 diff --git a/app/assets/javascripts/api.js.coffee b/app/assets/javascripts/api.js.coffee index 2ddf8612db..f3ed9a6671 100644 --- a/app/assets/javascripts/api.js.coffee +++ b/app/assets/javascripts/api.js.coffee @@ -74,6 +74,8 @@ dataType: "json" ).done (label) -> callback(label) + .error (message) -> + callback(message.responseJSON) # Return group projects list. Filtered by query groupProjects: (group_id, query, callback) -> diff --git a/app/assets/javascripts/application.js.coffee b/app/assets/javascripts/application.js.coffee index 7f98332504..f01c67e947 100644 --- a/app/assets/javascripts/application.js.coffee +++ b/app/assets/javascripts/application.js.coffee @@ -43,6 +43,7 @@ #= require jquery.nicescroll #= require_tree . #= require fuzzaldrin-plus +#= require cropper window.slugify = (text) -> text.replace(/[^-a-zA-Z0-9]+/g, '_').toLowerCase() @@ -139,7 +140,7 @@ $ -> # Initialize tooltips $('body').tooltip( - selector: '.has_tooltip, [data-toggle="tooltip"]' + selector: '.has-tooltip, [data-toggle="tooltip"]' placement: (_, el) -> $el = $(el) $el.data('placement') || 'bottom' @@ -218,13 +219,20 @@ $ -> $this = $(this) $this.attr 'value', $this.val() + $sidebarGutterToggle = $('.js-sidebar-toggle') + $navIconToggle = $('.toggle-nav-collapse') + $(document) .off 'breakpoint:change' .on 'breakpoint:change', (e, breakpoint) -> if breakpoint is 'sm' or breakpoint is 'xs' - $gutterIcon = $('.js-sidebar-toggle').find('i') + $gutterIcon = $sidebarGutterToggle.find('i') if $gutterIcon.hasClass('fa-angle-double-right') - $gutterIcon.closest('a').trigger('click') + $sidebarGutterToggle.trigger('click') + + $navIcon = $navIconToggle.find('.fa') + if $navIcon.hasClass('fa-angle-left') + $navIconToggle.trigger('click') $(document) .off 'click', '.js-sidebar-toggle' diff --git a/app/assets/javascripts/awards_handler.coffee b/app/assets/javascripts/awards_handler.coffee index 03a4487416..47b080406d 100644 --- a/app/assets/javascripts/awards_handler.coffee +++ b/app/assets/javascripts/awards_handler.coffee @@ -122,7 +122,7 @@ class @AwardsHandler nodes = [] nodes.push( - "" diff --git a/app/assets/javascripts/gl_crop.js.coffee b/app/assets/javascripts/gl_crop.js.coffee new file mode 100644 index 0000000000..df9bfdfa6c --- /dev/null +++ b/app/assets/javascripts/gl_crop.js.coffee @@ -0,0 +1,152 @@ +class GitLabCrop + # Matches everything but the file name + FILENAMEREGEX = /^.*[\\\/]/ + + constructor: (input, opts = {}) -> + @fileInput = $(input) + + # We should rename to avoid spec to fail + # Form will submit the proper input filed with a file using FormData + @fileInput + .attr('name', "#{@fileInput.attr('name')}-trigger") + .attr('id', "#{@fileInput.attr('id')}-trigger") + + # Set defaults + { + @exportWidth = 200 + @exportHeight = 200 + @cropBoxWidth = 200 + @cropBoxHeight = 200 + @form = @fileInput.parents('form') + + # Required params + @filename + @previewImage + @modalCrop + @pickImageEl + @uploadImageBtn + @modalCropImg + } = opts + + # Ensure needed elements are jquery objects + # If selector is provided we will convert them to a jQuery Object + @filename = @getElement(@filename) + @previewImage = @getElement(@previewImage) + @pickImageEl = @getElement(@pickImageEl) + + # Modal elements usually are outside the @form element + @modalCrop = if _.isString(@modalCrop) then $(@modalCrop) else @modalCrop + @uploadImageBtn = if _.isString(@uploadImageBtn) then $(@uploadImageBtn) else @uploadImageBtn + @modalCropImg = if _.isString(@modalCropImg) then $(@modalCropImg) else @modalCropImg + + @cropActionsBtn = @modalCrop.find('[data-method]') + + @bindEvents() + + getElement: (selector) -> + $(selector, @form) + + bindEvents: -> + _this = @ + @fileInput.on 'change', (e) -> + _this.onFileInputChange(e, @) + + @pickImageEl.on 'click', @onPickImageClick + @modalCrop.on 'shown.bs.modal', @onModalShow + @modalCrop.on 'hidden.bs.modal', @onModalHide + @uploadImageBtn.on 'click', @onUploadImageBtnClick + @cropActionsBtn.on 'click', (e) -> + btn = @ + _this.onActionBtnClick(btn) + @croppedImageBlob = null + + onPickImageClick: => + @fileInput.trigger('click') + + onModalShow: => + _this = @ + @modalCropImg.cropper( + viewMode: 1 + center: false + aspectRatio: 1 + modal: true + scalable: false + rotatable: false + zoomable: true + dragMode: 'move' + guides: false + zoomOnTouch: false + zoomOnWheel: false + cropBoxMovable: false + cropBoxResizable: false + toggleDragModeOnDblclick: false + built: -> + $image = $(@) + container = $image.cropper 'getContainerData' + cropBoxWidth = _this.cropBoxWidth; + cropBoxHeight = _this.cropBoxHeight; + + $image.cropper('setCropBoxData', + width: cropBoxWidth, + height: cropBoxHeight, + left: (container.width - cropBoxWidth) / 2, + top: (container.height - cropBoxHeight) / 2 + ) + ) + + + onModalHide: => + @modalCropImg + .attr('src', '') # Remove attached image + .cropper('destroy') # Destroy cropper instance + + onUploadImageBtnClick: (e) => + e.preventDefault() + @setBlob() + @setPreview() + @modalCrop.modal('hide') + @fileInput.val('') + + onActionBtnClick: (btn) -> + data = $(btn).data() + + if @modalCropImg.data('cropper') && data.method + result = @modalCropImg.cropper data.method, data.option + + onFileInputChange: (e, input) -> + @readFile(input) + + readFile: (input) -> + _this = @ + reader = new FileReader + reader.onload = -> + _this.modalCropImg.attr('src', reader.result) + _this.modalCrop.modal('show') + + reader.readAsDataURL(input.files[0]) + + dataURLtoBlob: (dataURL) -> + binary = atob(dataURL.split(',')[1]) + array = [] + for v, k in binary + array.push(binary.charCodeAt(k)) + new Blob([new Uint8Array(array)], type: 'image/png') + + setPreview: -> + @previewImage.attr('src', @dataURL) + filename = @fileInput.val().replace(FILENAMEREGEX, '') + @filename.text(filename) + + setBlob: -> + @dataURL = @modalCropImg.cropper('getCroppedCanvas', + width: 200 + height: 200 + ).toDataURL('image/png') + @croppedImageBlob = @dataURLtoBlob(@dataURL) + + getBlob: -> + @croppedImageBlob + +$.fn.glCrop = (opts) -> + return @.each -> + $(@).data('glcrop', new GitLabCrop(@, opts)) diff --git a/app/assets/javascripts/gl_dropdown.js.coffee b/app/assets/javascripts/gl_dropdown.js.coffee index 418da68f17..ea064f28dd 100644 --- a/app/assets/javascripts/gl_dropdown.js.coffee +++ b/app/assets/javascripts/gl_dropdown.js.coffee @@ -1,16 +1,33 @@ class GitLabDropdownFilter BLUR_KEYCODES = [27, 40] + HAS_VALUE_CLASS = "has-value" - constructor: (@dropdown, @options) -> + constructor: (@input, @options) -> { - @input @filterInputBlur = true } = @options + $inputContainer = @input.parent() + $clearButton = $inputContainer.find('.js-dropdown-input-clear') + + # Clear click + $clearButton.on 'click', (e) => + e.preventDefault() + e.stopPropagation() + @input + .val('') + .trigger('keyup') + .focus() + # Key events timeout = "" @input.on "keyup", (e) => - if e.keyCode is 13 && @input.val() isnt "" + if @input.val() isnt "" and !$inputContainer.hasClass HAS_VALUE_CLASS + $inputContainer.addClass HAS_VALUE_CLASS + else if @input.val() is "" and $inputContainer.hasClass HAS_VALUE_CLASS + $inputContainer.removeClass HAS_VALUE_CLASS + + if e.keyCode is 13 and @input.val() isnt "" if @options.enterCallback @options.enterCallback() return @@ -119,7 +136,9 @@ class GitLabDropdown # Init filterable if @options.filterable - @filter = new GitLabDropdownFilter @dropdown, + @input = @dropdown.find('.dropdown-input .dropdown-input-field') + + @filter = new GitLabDropdownFilter @input, filterInputBlur: @filterInputBlur input: @filterInput remote: @options.filterRemote @@ -129,6 +148,7 @@ class GitLabDropdown return @fullData callback: (data) => @parseData data + @highlightRow 1 enterCallback: => @selectFirstRow() @@ -278,11 +298,19 @@ class GitLabDropdown noResults: -> html = "
  • " - html += "" + html += "" html += "No matching results." html += "" html += "
  • " + highlightRow: (index) -> + if @input.val() isnt "" + selector = '.dropdown-content li:first-child a' + if @dropdown.find(".dropdown-toggle-page").length + selector = ".dropdown-page-one .dropdown-content li:first-child a" + + $(selector).addClass 'is-focused' + rowClicked: (el) -> fieldName = @options.fieldName field = @dropdown.parent().find("input[name='#{fieldName}']") @@ -326,7 +354,7 @@ class GitLabDropdown if @dropdown.find(".dropdown-toggle-page").length selector = ".dropdown-page-one .dropdown-content li:first-child a" - # similute a click on the first link + # simulate a click on the first link $(selector).trigger "click" $.fn.glDropdown = (opts) -> diff --git a/app/assets/javascripts/issuable_context.js.coffee b/app/assets/javascripts/issuable_context.js.coffee index e52b73f94f..d6d09b36d8 100644 --- a/app/assets/javascripts/issuable_context.js.coffee +++ b/app/assets/javascripts/issuable_context.js.coffee @@ -1,7 +1,7 @@ -#= require jquery.waitforimages - class @IssuableContext constructor: -> + @initParticipants() + new UsersSelect() $('select.select2').select2({width: 'resolve', dropdownAutoWidth: true}) @@ -17,3 +17,27 @@ class @IssuableContext block.find('.js-select2').select2("open") $(".right-sidebar").niceScroll() + + initParticipants: -> + _this = @ + $(document).on "click", ".js-participants-more", @toggleHiddenParticipants + + $(".js-participants-author").each (i) -> + if i >= _this.PARTICIPANTS_ROW_COUNT + $(@) + .addClass "js-participants-hidden" + .hide() + + toggleHiddenParticipants: (e) -> + e.preventDefault() + + currentText = $(this).text().trim() + lessText = $(this).data("less-text") + originalText = $(this).data("original-text") + + if currentText is originalText + $(this).text(lessText) + else + $(this).text(originalText) + + $(".js-participants-hidden").toggle() diff --git a/app/assets/javascripts/issue.js.coffee b/app/assets/javascripts/issue.js.coffee index f50df1f5ea..d663e34871 100644 --- a/app/assets/javascripts/issue.js.coffee +++ b/app/assets/javascripts/issue.js.coffee @@ -7,7 +7,6 @@ class @Issue # Prevent duplicate event bindings @disableTaskList() @fixAffixScroll() - @initParticipants() if $('a.btn-close').length @initTaskList() @initIssueBtnEventListeners() @@ -85,27 +84,3 @@ class @Issue type: 'PATCH' url: $('form.js-issuable-update').attr('action') data: patchData - - initParticipants: -> - _this = @ - $(document).on "click", ".js-participants-more", @toggleHiddenParticipants - - $(".js-participants-author").each (i) -> - if i >= _this.PARTICIPANTS_ROW_COUNT - $(@) - .addClass "js-participants-hidden" - .hide() - - toggleHiddenParticipants: (e) -> - e.preventDefault() - - currentText = $(this).text().trim() - lessText = $(this).data("less-text") - originalText = $(this).data("original-text") - - if currentText is originalText - $(this).text(lessText) - else - $(this).text(originalText) - - $(".js-participants-hidden").toggle() diff --git a/app/assets/javascripts/labels_select.js.coffee b/app/assets/javascripts/labels_select.js.coffee index 4a0c18a99a..e08648d583 100644 --- a/app/assets/javascripts/labels_select.js.coffee +++ b/app/assets/javascripts/labels_select.js.coffee @@ -6,7 +6,7 @@ class @LabelsSelect labelUrl = $dropdown.data('labels') selectedLabel = $dropdown.data('selected') if selectedLabel - selectedLabel = selectedLabel.split(',') + selectedLabel = selectedLabel.toString().split(',') newLabelField = $('#new_label_name') newColorField = $('#new_label_color') showNo = $dropdown.data('show-no') @@ -14,28 +14,81 @@ class @LabelsSelect defaultLabel = $dropdown.data('default-label') if newLabelField.length + $newLabelCreateButton = $('.js-new-label-btn') + $colorPreview = $('.js-dropdown-label-color-preview') + $newLabelError = $dropdown.parent().find('.js-label-error') + $newLabelError.hide() + + # Suggested colors in the dropdown to chose from pre-chosen colors $('.suggest-colors-dropdown a').on 'click', (e) -> e.preventDefault() e.stopPropagation() - newColorField.val $(this).data('color') - $('.js-dropdown-label-color-preview') + newColorField + .val($(this).data('color')) + .trigger('change') + $colorPreview .css 'background-color', $(this).data('color') + .parent() .addClass 'is-active' - $('.js-new-label-btn').on 'click', (e) -> + # Cancel button takes back to first page + resetForm = -> + newLabelField + .val '' + .trigger 'change' + newColorField + .val '' + .trigger 'change' + $colorPreview + .css 'background-color', '' + .parent() + .removeClass 'is-active' + + $('.dropdown-menu-back').on 'click', -> + resetForm() + + $('.js-cancel-label-btn').on 'click', (e) -> e.preventDefault() e.stopPropagation() + resetForm() + $('.dropdown-menu-back', $dropdown.parent()).trigger 'click' + # Listen for change and keyup events on label and color field + # This allows us to enable the button when ready + enableLabelCreateButton = -> if newLabelField.val() isnt '' and newColorField.val() isnt '' - $('.js-new-label-btn').disable() + $newLabelCreateButton.enable() + else + $newLabelCreateButton.disable() - # Create new label with API - Api.newLabel projectId, { - name: newLabelField.val() - color: newColorField.val() - }, (label) -> - $('.js-new-label-btn').enable() - $('.dropdown-menu-back', $dropdown.parent()).trigger 'click' + newLabelField.on 'keyup change', enableLabelCreateButton + + newColorField.on 'keyup change', enableLabelCreateButton + + # Send the API call to create the label + $newLabelCreateButton + .disable() + .on 'click', (e) -> + e.preventDefault() + e.stopPropagation() + + if newLabelField.val() isnt '' and newColorField.val() isnt '' + $newLabelError.hide() + $('.js-new-label-btn').disable() + + # Create new label with API + Api.newLabel projectId, { + name: newLabelField.val() + color: newColorField.val() + }, (label) -> + $('.js-new-label-btn').enable() + + if label.message? + $newLabelError + .text label.message + .show() + else + $('.dropdown-menu-back', $dropdown.parent()).trigger 'click' $dropdown.glDropdown( data: (term, callback) -> @@ -68,8 +121,11 @@ class @LabelsSelect else selected = if label.title is selectedLabel then 'is-active' else '' + color = if label.color? then "" else "" + "
  • + #{color} #{label.title}
  • " diff --git a/app/assets/javascripts/profile.js.coffee b/app/assets/javascripts/profile.js.coffee index 20f8744055..ae87c6c4e4 100644 --- a/app/assets/javascripts/profile.js.coffee +++ b/app/assets/javascripts/profile.js.coffee @@ -1,5 +1,9 @@ class @Profile - constructor: -> + constructor: (opts = {}) -> + { + @form = $('.edit-user') + } = opts + # Automatically submit the Preferences form when any of its radio buttons change $('.js-preferences-form').on 'change.preference', 'input[type=radio]', -> $(this).parents('form').submit() @@ -17,14 +21,46 @@ class @Profile $('.update-notifications').on 'ajax:complete', -> $(this).find('.btn-save').enable() - $('.js-choose-user-avatar-button').bind "click", -> - form = $(this).closest("form") - form.find(".js-user-avatar-input").click() + @bindEvents() - $('.js-user-avatar-input').bind "change", -> - form = $(this).closest("form") - filename = $(this).val().replace(/^.*[\\\/]/, '') - form.find(".js-avatar-filename").text(filename) + cropOpts = + filename: '.js-avatar-filename' + previewImage: '.avatar-image .avatar' + modalCrop: '.modal-profile-crop' + pickImageEl: '.js-choose-user-avatar-button' + uploadImageBtn: '.js-upload-user-avatar' + modalCropImg: '.modal-profile-crop-image' + + @avatarGlCrop = $('.js-user-avatar-input').glCrop(cropOpts).data 'glcrop' + + bindEvents: -> + @form.on 'submit', @onSubmitForm + + onSubmitForm: (e) => + e.preventDefault() + @saveForm() + + saveForm: -> + self = @ + + formData = new FormData(@form[0]) + formData.append('user[avatar]', @avatarGlCrop.getBlob(), 'avatar.png') + + $.ajax + url: @form.attr('action') + type: @form.attr('method') + data: formData + dataType: "json" + processData: false + contentType: false + success: (response) -> + new Flash(response.message, 'notice') + error: (jqXHR) -> + new Flash(jqXHR.responseJSON.message, 'alert') + complete: -> + window.scrollTo 0, 0 + # Enable submit button after requests ends + self.form.find(':input[disabled]').enable() $ -> # Extract the SSH Key title from its comment diff --git a/app/assets/javascripts/sidebar.js.coffee b/app/assets/javascripts/sidebar.js.coffee index eea3f5ee91..860d4f438d 100644 --- a/app/assets/javascripts/sidebar.js.coffee +++ b/app/assets/javascripts/sidebar.js.coffee @@ -4,7 +4,6 @@ expanded = 'page-sidebar-expanded' toggleSidebar = -> $('.page-with-sidebar').toggleClass("#{collapsed} #{expanded}") $('header').toggleClass("header-collapsed header-expanded") - $('.sidebar-wrapper').toggleClass("sidebar-collapsed sidebar-expanded") $('.toggle-nav-collapse i').toggleClass("fa-angle-right fa-angle-left") $.cookie("collapsed_nav", $('.page-with-sidebar').hasClass(collapsed), { path: '/' }) diff --git a/app/assets/javascripts/stat_graph_contributors_util.js.coffee b/app/assets/javascripts/stat_graph_contributors_util.js.coffee index f5584bcfe4..31617c88b4 100644 --- a/app/assets/javascripts/stat_graph_contributors_util.js.coffee +++ b/app/assets/javascripts/stat_graph_contributors_util.js.coffee @@ -95,4 +95,4 @@ window.ContributorsStatGraphUtil = if date_range is null || date_range[0] <= new Date(date) <= date_range[1] true else - false \ No newline at end of file + false diff --git a/app/assets/javascripts/users_select.js.coffee b/app/assets/javascripts/users_select.js.coffee index 3d6452d2f4..8419340089 100644 --- a/app/assets/javascripts/users_select.js.coffee +++ b/app/assets/javascripts/users_select.js.coffee @@ -30,6 +30,7 @@ class @UsersSelect if showNullUser showDivider += 1 users.unshift( + beforeDivider: true name: 'Unassigned', id: 0 ) @@ -39,6 +40,7 @@ class @UsersSelect name = showAnyUser name = 'Any User' if name == true anyUser = { + beforeDivider: true name: name, id: null } @@ -75,20 +77,27 @@ class @UsersSelect selected = if user.id is selectedId then "is-active" else "" img = "" - if avatar - img = "" - - "
  • - - #{img} - + if user.beforeDivider? + "
  • + #{user.name} - - - #{username} - - -
  • " + + " + else + if avatar + img = "" + + "
  • + + #{img} + + #{user.name} + + + #{username} + + +
  • " ) $('.ajax-users-select').each (i, select) => diff --git a/app/assets/stylesheets/application.scss b/app/assets/stylesheets/application.scss index 2d301d21ab..e2d590f4df 100644 --- a/app/assets/stylesheets/application.scss +++ b/app/assets/stylesheets/application.scss @@ -9,6 +9,7 @@ *= require_self *= require dropzone/basic *= require cal-heatmap + *= require cropper.css */ /* diff --git a/app/assets/stylesheets/framework/blocks.scss b/app/assets/stylesheets/framework/blocks.scss index c36f29dda0..62b2af0dbf 100644 --- a/app/assets/stylesheets/framework/blocks.scss +++ b/app/assets/stylesheets/framework/blocks.scss @@ -107,10 +107,28 @@ margin: 0; font-size: 23px; font-weight: normal; - margin: 16px 0 5px 0; + margin: 16px 0 5px; color: #4c4e54; font-size: 23px; line-height: 1.1; + + h1 { + color: #313236; + margin-bottom: 6px; + font-size: 23px; + } + + .visibility-icon { + display: inline-block; + margin-left: 5px; + font-size: 18px; + color: $gray; + } + + p { + padding: 0 $gl-padding; + color: #5c5d5e; + } } .cover-desc { diff --git a/app/assets/stylesheets/framework/common.scss b/app/assets/stylesheets/framework/common.scss index bc03c2180b..8625817fda 100644 --- a/app/assets/stylesheets/framework/common.scss +++ b/app/assets/stylesheets/framework/common.scss @@ -292,8 +292,11 @@ table { } .btn-sign-in { - margin-top: 10px; text-shadow: none; + + @media (min-width: $screen-sm-min) { + margin-top: 11px; + } } .side-filters { @@ -375,7 +378,6 @@ table { position: absolute; top: 0; right: 0; - width: 250px !important; visibility: hidden; } } diff --git a/app/assets/stylesheets/framework/dropdowns.scss b/app/assets/stylesheets/framework/dropdowns.scss index a48b6c17fa..2d616fc660 100644 --- a/app/assets/stylesheets/framework/dropdowns.scss +++ b/app/assets/stylesheets/framework/dropdowns.scss @@ -75,7 +75,7 @@ width: 240px; margin-top: 2px; margin-bottom: 0; - padding: 10px 10px; + padding: 10px; font-size: 14px; font-weight: normal; background-color: $dropdown-bg; @@ -130,6 +130,12 @@ text-decoration: none; outline: 0; } + + &.dropdown-menu-empty-link { + &.is-focused { + background-color: $dropdown-empty-row-bg; + } + } } } @@ -183,7 +189,7 @@ } .dropdown-select { - width: 280px; + width: 300px; } .dropdown-menu-align-right { @@ -237,7 +243,7 @@ .dropdown-title-button { position: absolute; - top: -1px; + top: 0; padding: 0; color: $dropdown-title-btn-color; font-size: 14px; @@ -270,6 +276,22 @@ font-size: 12px; pointer-events: none; } + + .dropdown-input-clear { + display: none; + cursor: pointer; + pointer-events: all; + } + + &.has-value { + .dropdown-input-clear { + display: block; + } + + .dropdown-input-search { + display: none; + } + } } .dropdown-input-field { @@ -286,13 +308,13 @@ border-color: $dropdown-input-focus-border; box-shadow: 0 0 4px $dropdown-input-focus-shadow; - + .fa { + ~ .fa { color: $dropdown-link-color; } } &:hover { - + .fa { + ~ .fa { color: $dropdown-link-color; } } @@ -338,11 +360,12 @@ } } -.dropdown-menu-labels { - .label { - position: relative; - width: 30px; - margin-right: 5px; - text-indent: -99999px; - } +.dropdown-label-box { + position: relative; + top: 3px; + margin-right: 5px; + display: inline-block; + width: 15px; + height: 15px; + border-radius: $border-radius-base; } diff --git a/app/assets/stylesheets/framework/filters.scss b/app/assets/stylesheets/framework/filters.scss index 40a508c1eb..b05c5df1bd 100644 --- a/app/assets/stylesheets/framework/filters.scss +++ b/app/assets/stylesheets/framework/filters.scss @@ -11,3 +11,11 @@ } } } + +@media (max-width: $screen-xs-max) { + .filter-item { + display: block; + margin: 0 0 10px; + } +} + diff --git a/app/assets/stylesheets/framework/fonts.scss b/app/assets/stylesheets/framework/fonts.scss index 7a946109e3..5f9685bc71 100644 --- a/app/assets/stylesheets/framework/fonts.scss +++ b/app/assets/stylesheets/framework/fonts.scss @@ -1,3 +1,7 @@ +// Disabling "SpaceAfterPropertyColon" linter because the linter doesn't like +// the way the `src` property is formatted in this file. +// scss-lint:disable SpaceAfterPropertyColon + /* latin-ext */ @font-face { font-family: 'Source Sans Pro'; diff --git a/app/assets/stylesheets/framework/gitlab-theme.scss b/app/assets/stylesheets/framework/gitlab-theme.scss index 2a4cf4fc33..c83cf88159 100644 --- a/app/assets/stylesheets/framework/gitlab-theme.scss +++ b/app/assets/stylesheets/framework/gitlab-theme.scss @@ -117,4 +117,4 @@ body { &.ui_violet { @include gitlab-theme(#98c, $theme-violet, #436, #325); } -} \ No newline at end of file +} diff --git a/app/assets/stylesheets/framework/header.scss b/app/assets/stylesheets/framework/header.scss index a6c9fce5b8..a450167b04 100644 --- a/app/assets/stylesheets/framework/header.scss +++ b/app/assets/stylesheets/framework/header.scss @@ -70,6 +70,11 @@ header { .header-content { height: $header-height; + padding-right: 20px; + + @media (min-width: $screen-sm-min) { + padding-right: 0; + } .title { margin: 0; diff --git a/app/assets/stylesheets/framework/layout.scss b/app/assets/stylesheets/framework/layout.scss index e901c78d02..8bb047db2d 100644 --- a/app/assets/stylesheets/framework/layout.scss +++ b/app/assets/stylesheets/framework/layout.scss @@ -16,7 +16,7 @@ body { } .container .content { - margin: 0 0; + margin: 0; } .navless-container { diff --git a/app/assets/stylesheets/framework/mixins.scss b/app/assets/stylesheets/framework/mixins.scss index 377bfa174b..250d630929 100644 --- a/app/assets/stylesheets/framework/mixins.scss +++ b/app/assets/stylesheets/framework/mixins.scss @@ -1,7 +1,7 @@ /** * Generic mixins */ - @mixin box-shadow($shadow) { +@mixin box-shadow($shadow) { -webkit-box-shadow: $shadow; -moz-box-shadow: $shadow; -ms-box-shadow: $shadow; diff --git a/app/assets/stylesheets/framework/nav.scss b/app/assets/stylesheets/framework/nav.scss index 5f4ce87b08..95bdd6d1ea 100644 --- a/app/assets/stylesheets/framework/nav.scss +++ b/app/assets/stylesheets/framework/nav.scss @@ -102,6 +102,10 @@ display: inline-block; } + .icon-label { + display: none; + } + input { height: 34px; display: inline-block; @@ -124,9 +128,38 @@ } } - /* Hide on extra small devices (phones) */ @media (max-width: $screen-xs-max) { - display: none; + padding-bottom: 0; + + .btn, form, .dropdown, .dropdown-menu-toggle, .form-control { + margin: 0 0 10px; + display: block; + width: 100%; + } + + form { + display: block; + height: auto; + + input { + width: 100%; + margin: 0 0 10px; + } + } + + .input-short { + width: 100%; + } + + .icon-label { + display: inline-block; + } + + // Applies on /dashboard/issues + .project-item-select-holder { + display: block; + margin: 0; + } } /* Small devices (tablets, 768px and lower) */ diff --git a/app/assets/stylesheets/framework/sidebar.scss b/app/assets/stylesheets/framework/sidebar.scss index be05db58c4..9d18831778 100644 --- a/app/assets/stylesheets/framework/sidebar.scss +++ b/app/assets/stylesheets/framework/sidebar.scss @@ -1,3 +1,10 @@ +#logo { + z-index: 2; + position: absolute; + width: 58px; + cursor: pointer; +} + .page-with-sidebar { padding-top: $header-height; transition-duration: .3s; @@ -18,28 +25,10 @@ position: absolute; left: 0; } - - #logo { - z-index: 2; - position: absolute; - width: 58px; - cursor: pointer; - } - - &.right-sidebar-expanded { - /* Extra small devices (phones, less than 768px) */ - /* No media query since this is the default in Bootstrap */ - padding-right: 0; - /* Small devices (tablets, 768px and up) */ - @media (min-width: $screen-sm-min) { - padding-right: $gutter_width; - } - - } } .sidebar-wrapper { - z-index: 999; + z-index: 1000; background: $background-color; } @@ -202,53 +191,27 @@ } } -@mixin expanded-sidebar { - padding-left: $sidebar_collapsed_width; +.collapse-nav a { + width: $sidebar_width; + position: fixed; + bottom: 0; + left: 0; + font-size: 13px; + background: transparent; + height: 40px; + text-align: center; + line-height: 40px; + transition-duration: .3s; + outline: none; - @media (min-width: $screen-md-min) { - padding-left: $sidebar_width; - } - - &.right-sidebar-collapsed { - /* Extra small devices (phones, less than 768px) */ - padding-right: 0; - /* Small devices (tablets, 768px and up) */ - @media (min-width: $screen-sm-min) { - padding-right: $sidebar_collapsed_width; - } - } - - .sidebar-wrapper { - width: $sidebar_width; - - .nav-sidebar { - width: $sidebar_width; - } - - .nav-sidebar li a{ - width: 230px; - - &.back-link { - i { - opacity: 0; - } - } - } + &:hover { + text-decoration: none; } } -@mixin collapsed-sidebar { +.page-sidebar-collapsed { padding-left: $sidebar_collapsed_width; - &.right-sidebar-collapsed { - /* Extra small devices (phones, less than 768px) */ - padding-right: 0; - /* Small devices (tablets, 768px and up) */ - @media (min-width: $screen-sm-min) { - padding-right: $sidebar_collapsed_width; - } - } - .sidebar-wrapper { width: $sidebar_collapsed_width; @@ -293,35 +256,48 @@ } } -.collapse-nav a { - width: $sidebar_width; - position: fixed; - bottom: 0; - left: 0; - font-size: 13px; - background: transparent; - height: 40px; - text-align: center; - line-height: 40px; - transition-duration: .3s; - outline: none; -} +.page-sidebar-expanded { + padding-left: $sidebar_collapsed_width; -.collapse-nav a:hover { - text-decoration: none; - background: #f2f6f7; -} + @media (min-width: $screen-md-min) { + padding-left: $sidebar_width; + } -.page-sidebar-collapsed { - /* Extra small devices (phones, less than 768px) */ - @include collapsed-sidebar; - padding-right: 0; - /* Small devices (tablets, 768px and up) */ - @media (min-width: $screen-sm-min) { - @include collapsed-sidebar; + .sidebar-wrapper { + width: $sidebar_width; + + .nav-sidebar { + width: $sidebar_width; + } + + .nav-sidebar li a { + width: 230px; + + &.back-link { + i { + opacity: 0; + } + } + } } } -.page-sidebar-expanded { - @include expanded-sidebar; +.right-sidebar-collapsed { + padding-right: 0; + + @media (min-width: $screen-sm-min) { + padding-right: $sidebar_collapsed_width; + } +} + +.right-sidebar-expanded { + padding-right: 0; + + @media (min-width: $screen-sm-min) and (max-width: $screen-sm-max) { + padding-right: $sidebar_collapsed_width; + } + + @media (min-width: $screen-md-min) { + padding-right: $gutter_width; + } } diff --git a/app/assets/stylesheets/framework/typography.scss b/app/assets/stylesheets/framework/typography.scss index 949295a1d0..b1886fbe67 100644 --- a/app/assets/stylesheets/framework/typography.scss +++ b/app/assets/stylesheets/framework/typography.scss @@ -39,8 +39,8 @@ h1 { font-size: 1.3em; font-weight: 600; - margin: 24px 0 12px 0; - padding: 0 0 10px 0; + margin: 24px 0 12px; + padding: 0 0 10px; border-bottom: 1px solid #e7e9ed; color: #313236; } @@ -48,27 +48,27 @@ h2 { font-size: 1.2em; font-weight: 600; - margin: 24px 0 12px 0; + margin: 24px 0 12px; color: #313236; } h3 { - margin: 24px 0 12px 0; + margin: 24px 0 12px; font-size: 1.1em; } h4 { - margin: 24px 0 12px 0; + margin: 24px 0 12px; font-size: 0.98em; } h5 { - margin: 24px 0 12px 0; + margin: 24px 0 12px; font-size: 0.95em; } h6 { - margin: 24px 0 12px 0; + margin: 24px 0 12px; font-size: 0.90em; } @@ -76,7 +76,7 @@ color: #7f8fa4; font-size: inherit; padding: 8px 21px; - margin: 12px 0 12px; + margin: 12px 0; border-left: 3px solid #e7e9ed; } @@ -88,13 +88,13 @@ p { color: #5c5d5e; - margin: 6px 0 0 0; + margin: 6px 0 0; } table { @extend .table; @extend .table-bordered; - margin: 12px 0 12px 0; + margin: 12px 0; color: #5c5d5e; th { background: #f8fafc; @@ -102,7 +102,7 @@ } pre { - margin: 12px 0 12px 0; + margin: 12px 0; font-size: 13px; line-height: 1.6em; overflow-x: auto; @@ -191,7 +191,7 @@ body { line-height: 1.3; font-size: 1.25em; font-weight: 600; - margin: 12px 7px 12px 7px; + margin: 12px 7px; } h1, h2, h3, h4, h5, h6 { diff --git a/app/assets/stylesheets/framework/variables.scss b/app/assets/stylesheets/framework/variables.scss index 8f260f24c4..e5e0f9ce0a 100644 --- a/app/assets/stylesheets/framework/variables.scss +++ b/app/assets/stylesheets/framework/variables.scss @@ -168,13 +168,14 @@ $regular_font: 'Source Sans Pro', "Helvetica Neue", Helvetica, Arial, sans-serif */ $dropdown-bg: #fff; $dropdown-link-color: #555; -$dropdown-link-hover-bg: rgba(#000, .04); +$dropdown-link-hover-bg: $row-hover; +$dropdown-empty-row-bg: rgba(#000, .04); $dropdown-border-color: rgba(#000, .1); $dropdown-shadow-color: rgba(#000, .1); $dropdown-divider-color: rgba(#000, .1); $dropdown-header-color: #959494; $dropdown-title-btn-color: #bfbfbf; -$dropdown-input-color: #c7c7c7; +$dropdown-input-color: #555; $dropdown-input-focus-border: rgb(58, 171, 240); $dropdown-input-focus-shadow: rgba(#000, .2); $dropdown-loading-bg: rgba(#fff, .6); diff --git a/app/assets/stylesheets/notify.scss b/app/assets/stylesheets/notify.scss index f1d42f80f5..0a13a7e0b5 100644 --- a/app/assets/stylesheets/notify.scss +++ b/app/assets/stylesheets/notify.scss @@ -3,12 +3,12 @@ img { height: auto; } p.details { - font-style:italic; - color:#777 + font-style: italic; + color: #777 } .footer p { - font-size:small; - color:#777 + font-size: small; + color: #777 } pre.commit-message { white-space: pre-wrap; @@ -20,5 +20,5 @@ pre.commit-message { color: #090; } .file-stats .deleted-file { - color: #B00; + color: #b00; } diff --git a/app/assets/stylesheets/pages/admin.scss b/app/assets/stylesheets/pages/admin.scss index a61161810a..e05f14e749 100644 --- a/app/assets/stylesheets/pages/admin.scss +++ b/app/assets/stylesheets/pages/admin.scss @@ -34,9 +34,9 @@ background: #fff } - .visibility-levels { - .controls { - margin-bottom: 9px; + .visibility-levels { + .controls { + margin-bottom: 9px; } i { diff --git a/app/assets/stylesheets/pages/diff.scss b/app/assets/stylesheets/pages/diff.scss index d5862a11ac..f1368d74b3 100644 --- a/app/assets/stylesheets/pages/diff.scss +++ b/app/assets/stylesheets/pages/diff.scss @@ -132,7 +132,7 @@ } .image-info { font-size: 12px; - margin: 5px 0 0 0; + margin: 5px 0 0; color: grey; } diff --git a/app/assets/stylesheets/pages/issuable.scss b/app/assets/stylesheets/pages/issuable.scss index 2760af8a48..5300bb52a1 100644 --- a/app/assets/stylesheets/pages/issuable.scss +++ b/app/assets/stylesheets/pages/issuable.scss @@ -183,7 +183,7 @@ .block { width: $sidebar_collapsed_width - 1px; margin-left: -19px; - padding: 15px 0 0 0; + padding: 15px 0 0; border-bottom: none; overflow: hidden; } @@ -273,12 +273,12 @@ } .participants-list { - margin: -5px -5px; + margin: -5px; } .participants-author { display: inline-block; - padding: 5px 5px; + padding: 5px; .author_link { display: block; diff --git a/app/assets/stylesheets/pages/labels.scss b/app/assets/stylesheets/pages/labels.scss index 61ee34b695..4e02ec4e89 100644 --- a/app/assets/stylesheets/pages/labels.scss +++ b/app/assets/stylesheets/pages/labels.scss @@ -9,28 +9,45 @@ } &.suggest-colors-dropdown { - margin-bottom: 5px; + margin-top: 10px; + margin-bottom: 10px; + border-radius: $border-radius-base; + overflow: hidden; a { @include border-radius(0); - width: 36.7px; + width: (100% / 7); margin-right: 0; margin-bottom: -5px; } } } -.dropdown-label-color-preview { - display: none; - margin-top: 5px; - width: 100%; - height: 25px; +.dropdown-new-label { + .dropdown-content { + max-height: 260px; + } +} + +.dropdown-label-color-input { + position: relative; + margin-bottom: 10px; &.is-active { - display: block; + padding-left: 32px; } } +.dropdown-label-color-preview { + position: absolute; + left: 0; + top: 0; + width: 32px; + height: 32px; + border-top-left-radius: $border-radius-base; + border-bottom-left-radius: $border-radius-base; +} + .label-row { .label { padding: 9px; @@ -45,3 +62,10 @@ .label-subscription { display: inline-block; } + +.dropdown-labels-error { + padding: 5px 10px; + margin-bottom: 10px; + background-color: $gl-danger; + color: $white-light; +} diff --git a/app/assets/stylesheets/pages/login.scss b/app/assets/stylesheets/pages/login.scss index bc41f7d306..777bcbca5c 100644 --- a/app/assets/stylesheets/pages/login.scss +++ b/app/assets/stylesheets/pages/login.scss @@ -45,7 +45,7 @@ .login-heading h3 { font-weight: 300; line-height: 1.5; - margin: 0 0 10px 0; + margin: 0 0 10px; } .login-footer { diff --git a/app/assets/stylesheets/pages/profile.scss b/app/assets/stylesheets/pages/profile.scss index 260179074c..d8c991356a 100644 --- a/app/assets/stylesheets/pages/profile.scss +++ b/app/assets/stylesheets/pages/profile.scss @@ -54,7 +54,7 @@ } .account-well { - padding: 10px 10px; + padding: 10px; background-color: $help-well-bg; border: 1px solid $help-well-border; border-radius: $border-radius-base; @@ -197,3 +197,24 @@ width: 105px; } } + +.modal-profile-crop { + .modal-dialog { + width: 380px; + + @media (max-width: $screen-sm-min) { + width: auto; + } + + } + + .profile-crop-image-container { + height: 300px; + margin: 0 auto; + } + + .crop-controls { + padding: 10px 0 0 0; + text-align: center; + } +} diff --git a/app/assets/stylesheets/pages/projects.scss b/app/assets/stylesheets/pages/projects.scss index 4caf11929f..c68bd673a6 100644 --- a/app/assets/stylesheets/pages/projects.scss +++ b/app/assets/stylesheets/pages/projects.scss @@ -68,28 +68,6 @@ } } - .project-home-desc { - h1 { - color: #313236; - margin: 0; - margin-bottom: 6px; - font-size: 23px; - font-weight: normal; - } - - .visibility-icon { - display: inline-block; - margin-left: 5px; - font-size: 18px; - color: $gray; - } - - p { - padding: 0 $gl-padding; - color: #5c5d5e; - } - } - .project-repo-buttons { margin-top: 20px; margin-bottom: 0; @@ -333,7 +311,7 @@ pre.light-well { } .git-empty { - margin: 0 7px 0 7px; + margin: 0 7px; h5 { color: #5c5d5e; diff --git a/app/assets/stylesheets/pages/stat_graph.scss b/app/assets/stylesheets/pages/stat_graph.scss index b9be47e770..85a0304196 100644 --- a/app/assets/stylesheets/pages/stat_graph.scss +++ b/app/assets/stylesheets/pages/stat_graph.scss @@ -16,7 +16,7 @@ #contributors { .contributors-list { - margin: 0 0 10px 0; + margin: 0 0 10px; list-style: none; padding: 0; } diff --git a/app/assets/stylesheets/pages/xterm.scss b/app/assets/stylesheets/pages/xterm.scss index 8886c1dff5..3f28e40292 100644 --- a/app/assets/stylesheets/pages/xterm.scss +++ b/app/assets/stylesheets/pages/xterm.scss @@ -21,19 +21,19 @@ $l-white: #fff; .term-bold { - font-weight: bold; + font-weight: bold; } .term-italic { - font-style: italic; + font-style: italic; } .term-conceal { - visibility: hidden; + visibility: hidden; } .term-underline { - text-decoration: underline; + text-decoration: underline; } .term-cross { - text-decoration: line-through; + text-decoration: line-through; } .term-fg-black { diff --git a/app/controllers/admin/application_settings_controller.rb b/app/controllers/admin/application_settings_controller.rb index 04a99d8c84..ed9f603138 100644 --- a/app/controllers/admin/application_settings_controller.rb +++ b/app/controllers/admin/application_settings_controller.rb @@ -61,6 +61,7 @@ class Admin::ApplicationSettingsController < Admin::ApplicationController :session_expire_delay, :default_project_visibility, :default_snippet_visibility, + :default_group_visibility, :restricted_signup_domains_raw, :version_check_enabled, :admin_notification_email, diff --git a/app/controllers/admin/groups_controller.rb b/app/controllers/admin/groups_controller.rb index b2b817e64f..a6db4690df 100644 --- a/app/controllers/admin/groups_controller.rb +++ b/app/controllers/admin/groups_controller.rb @@ -59,6 +59,6 @@ class Admin::GroupsController < Admin::ApplicationController end def group_params - params.require(:group).permit(:name, :description, :path, :avatar) + params.require(:group).permit(:name, :description, :path, :avatar, :visibility_level) end end diff --git a/app/controllers/admin/projects_controller.rb b/app/controllers/admin/projects_controller.rb index 4a6edafdee..4089091d56 100644 --- a/app/controllers/admin/projects_controller.rb +++ b/app/controllers/admin/projects_controller.rb @@ -1,7 +1,6 @@ class Admin::ProjectsController < Admin::ApplicationController before_action :project, only: [:show, :transfer] before_action :group, only: [:show, :transfer] - before_action :repository, only: [:show, :transfer] def index @projects = Project.all diff --git a/app/controllers/application_controller.rb b/app/controllers/application_controller.rb index de7d323907..c81cb85dc1 100644 --- a/app/controllers/application_controller.rb +++ b/app/controllers/application_controller.rb @@ -23,7 +23,6 @@ class ApplicationController < ActionController::Base helper_method :abilities, :can?, :current_application_settings helper_method :import_sources_enabled?, :github_import_enabled?, :github_import_configured?, :gitlab_import_enabled?, :gitlab_import_configured?, :bitbucket_import_enabled?, :bitbucket_import_configured?, :gitorious_import_enabled?, :google_code_import_enabled?, :fogbugz_import_enabled?, :git_import_enabled? - helper_method :repository, :can_collaborate_with_project? rescue_from Encoding::CompatibilityError do |exception| log_exception(exception) @@ -116,47 +115,6 @@ class ApplicationController < ActionController::Base abilities.allowed?(object, action, subject) end - def project - unless @project - namespace = params[:namespace_id] - id = params[:project_id] || params[:id] - - # Redirect from - # localhost/group/project.git - # to - # localhost/group/project - # - if id =~ /\.git\Z/ - redirect_to request.original_url.gsub(/\.git\/?\Z/, '') and return - end - - project_path = "#{namespace}/#{id}" - @project = Project.find_with_namespace(project_path) - - if @project and can?(current_user, :read_project, @project) - if @project.path_with_namespace != project_path - redirect_to request.original_url.gsub(project_path, @project.path_with_namespace) and return - end - @project - elsif current_user.nil? - @project = nil - authenticate_user! - else - @project = nil - render_404 and return - end - end - @project - end - - def repository - @repository ||= project.repository - end - - def authorize_project!(action) - return access_denied! unless can?(current_user, action, project) - end - def access_denied! render "errors/access_denied", layout: "errors", status: 404 end @@ -165,14 +123,6 @@ class ApplicationController < ActionController::Base render "errors/git_not_found.html", layout: "errors", status: 404 end - def method_missing(method_sym, *arguments, &block) - if method_sym.to_s =~ /\Aauthorize_(.*)!\z/ - authorize_project!($1.to_sym) - else - super - end - end - def render_403 head :forbidden end @@ -181,10 +131,6 @@ class ApplicationController < ActionController::Base render file: Rails.root.join("public", "404"), layout: false, status: "404" end - def require_non_empty_project - redirect_to @project if @project.empty_repo? - end - def no_cache_headers response.headers["Cache-Control"] = "no-cache, no-store, max-age=0, must-revalidate" response.headers["Pragma"] = "no-cache" @@ -410,13 +356,6 @@ class ApplicationController < ActionController::Base current_user.nil? && root_path == request.path end - def can_collaborate_with_project?(project = nil) - project ||= @project - - can?(current_user, :push_code, project) || - (current_user && current_user.already_forked?(project)) - end - private def set_default_sort diff --git a/app/controllers/concerns/global_milestones.rb b/app/controllers/concerns/global_milestones.rb index 54ea1e454f..5c503c5b69 100644 --- a/app/controllers/concerns/global_milestones.rb +++ b/app/controllers/concerns/global_milestones.rb @@ -6,7 +6,6 @@ module GlobalMilestones @milestones = MilestonesFinder.new.execute(@projects, params) @milestones = GlobalMilestone.build_collection(@milestones) @milestones = @milestones.sort_by { |x| x.due_date.nil? ? epoch : x.due_date } - @milestones = Kaminari.paginate_array(@milestones).page(params[:page]) end def milestone diff --git a/app/controllers/concerns/issuable_actions.rb b/app/controllers/concerns/issuable_actions.rb new file mode 100644 index 0000000000..f40b62446e --- /dev/null +++ b/app/controllers/concerns/issuable_actions.rb @@ -0,0 +1,23 @@ +module IssuableActions + extend ActiveSupport::Concern + + included do + before_action :authorize_destroy_issuable!, only: :destroy + end + + def destroy + issuable.destroy + + name = issuable.class.name.titleize.downcase + flash[:notice] = "The #{name} was successfully deleted." + redirect_to polymorphic_path([@project.namespace.becomes(Namespace), @project, issuable.class]) + end + + private + + def authorize_destroy_issuable! + unless current_user.can?(:"destroy_#{issuable.to_ability_name}", issuable) + return access_denied! + end + end +end diff --git a/app/controllers/dashboard/application_controller.rb b/app/controllers/dashboard/application_controller.rb index 962ea38d6c..9d3d1c23c2 100644 --- a/app/controllers/dashboard/application_controller.rb +++ b/app/controllers/dashboard/application_controller.rb @@ -1,3 +1,9 @@ class Dashboard::ApplicationController < ApplicationController layout 'dashboard' + + private + + def projects + @projects ||= current_user.authorized_projects.sorted_by_activity.non_archived + end end diff --git a/app/controllers/dashboard/labels_controller.rb b/app/controllers/dashboard/labels_controller.rb new file mode 100644 index 0000000000..23a4ef21ea --- /dev/null +++ b/app/controllers/dashboard/labels_controller.rb @@ -0,0 +1,9 @@ +class Dashboard::LabelsController < Dashboard::ApplicationController + def index + labels = Label.where(project_id: projects).select(:title, :color).uniq(:title) + + respond_to do |format| + format.json { render json: labels } + end + end +end diff --git a/app/controllers/dashboard/milestones_controller.rb b/app/controllers/dashboard/milestones_controller.rb index 2bdce0f8a0..fa9c6c054f 100644 --- a/app/controllers/dashboard/milestones_controller.rb +++ b/app/controllers/dashboard/milestones_controller.rb @@ -2,18 +2,19 @@ class Dashboard::MilestonesController < Dashboard::ApplicationController include GlobalMilestones before_action :projects - before_action :milestones, only: [:index] before_action :milestone, only: [:show] def index + respond_to do |format| + format.html do + @milestones = Kaminari.paginate_array(milestones).page(params[:page]) + end + format.json do + render json: milestones + end + end end def show end - - private - - def projects - @projects ||= current_user.authorized_projects.sorted_by_activity.non_archived - end end diff --git a/app/controllers/dashboard_controller.rb b/app/controllers/dashboard_controller.rb index b538c7d160..1dce4a2172 100644 --- a/app/controllers/dashboard_controller.rb +++ b/app/controllers/dashboard_controller.rb @@ -3,7 +3,7 @@ class DashboardController < Dashboard::ApplicationController include MergeRequestsAction before_action :event_filter, only: :activity - before_action :projects, only: [:issues, :merge_requests, :labels, :milestones] + before_action :projects, only: [:issues, :merge_requests] respond_to :html @@ -20,29 +20,6 @@ class DashboardController < Dashboard::ApplicationController end end - def labels - labels = Label.where(project_id: @projects).select(:title, :color).uniq(:title) - - respond_to do |format| - format.json do - render json: labels - end - end - end - - def milestones - milestones = Milestone.where(project_id: @projects).active - epoch = DateTime.parse('1970-01-01') - grouped_milestones = GlobalMilestone.build_collection(milestones) - grouped_milestones = grouped_milestones.sort_by { |x| x.due_date.nil? ? epoch : x.due_date } - - respond_to do |format| - format.json do - render json: grouped_milestones - end - end - end - protected def load_events @@ -57,8 +34,4 @@ class DashboardController < Dashboard::ApplicationController @events = @event_filter.apply_filter(@events).with_associations @events = @events.limit(20).offset(params[:offset] || 0) end - - def projects - @projects ||= current_user.authorized_projects.sorted_by_activity.non_archived - end end diff --git a/app/controllers/explore/groups_controller.rb b/app/controllers/explore/groups_controller.rb index 2580f15c43..a962f9a093 100644 --- a/app/controllers/explore/groups_controller.rb +++ b/app/controllers/explore/groups_controller.rb @@ -1,6 +1,6 @@ class Explore::GroupsController < Explore::ApplicationController def index - @groups = Group.order_id_desc + @groups = GroupsFinder.new.execute(current_user) @groups = @groups.search(params[:search]) if params[:search].present? @groups = @groups.sort(@sort = params[:sort]) @groups = @groups.page(params[:page]) diff --git a/app/controllers/groups/application_controller.rb b/app/controllers/groups/application_controller.rb index be801858ea..949b4a6c25 100644 --- a/app/controllers/groups/application_controller.rb +++ b/app/controllers/groups/application_controller.rb @@ -1,21 +1,32 @@ class Groups::ApplicationController < ApplicationController layout 'group' + + skip_before_action :authenticate_user! before_action :group private def group - @group ||= Group.find_by(path: params[:group_id]) - end + unless @group + id = params[:group_id] || params[:id] + @group = Group.find_by(path: id) - def authorize_read_group! - unless @group and can?(current_user, :read_group, @group) - if current_user.nil? - return authenticate_user! - else - return render_404 + unless @group && can?(current_user, :read_group, @group) + @group = nil + + if current_user.nil? + authenticate_user! + else + render_404 + end end end + + @group + end + + def group_projects + @projects ||= GroupProjectsFinder.new(group).execute(current_user) end def authorize_admin_group! diff --git a/app/controllers/groups/avatars_controller.rb b/app/controllers/groups/avatars_controller.rb index 76c87366ba..ad2c20b42d 100644 --- a/app/controllers/groups/avatars_controller.rb +++ b/app/controllers/groups/avatars_controller.rb @@ -1,4 +1,6 @@ class Groups::AvatarsController < Groups::ApplicationController + before_action :authorize_admin_group! + def destroy @group.remove_avatar! @group.save diff --git a/app/controllers/groups/group_members_controller.rb b/app/controllers/groups/group_members_controller.rb index 0e902c4bb4..d5ef33888c 100644 --- a/app/controllers/groups/group_members_controller.rb +++ b/app/controllers/groups/group_members_controller.rb @@ -1,8 +1,5 @@ class Groups::GroupMembersController < Groups::ApplicationController - skip_before_action :authenticate_user!, only: [:index] - # Authorize - before_action :authorize_read_group! before_action :authorize_admin_group_member!, except: [:index, :leave] def index diff --git a/app/controllers/groups/milestones_controller.rb b/app/controllers/groups/milestones_controller.rb index 0c2a350bc3..b23c3022fb 100644 --- a/app/controllers/groups/milestones_controller.rb +++ b/app/controllers/groups/milestones_controller.rb @@ -1,12 +1,16 @@ class Groups::MilestonesController < Groups::ApplicationController include GlobalMilestones - before_action :projects - before_action :milestones, only: [:index] + before_action :group_projects before_action :milestone, only: [:show, :update] - before_action :authorize_group_milestone!, only: [:create, :update] + before_action :authorize_admin_milestones!, only: [:new, :create, :update] def index + respond_to do |format| + format.html do + @milestones = Kaminari.paginate_array(milestones).page(params[:page]) + end + end end def new @@ -17,7 +21,7 @@ class Groups::MilestonesController < Groups::ApplicationController project_ids = params[:milestone][:project_ids] title = milestone_params[:title] - @group.projects.where(id: project_ids).each do |project| + @projects.where(id: project_ids).each do |project| Milestones::CreateService.new(project, current_user, milestone_params).execute end @@ -37,7 +41,7 @@ class Groups::MilestonesController < Groups::ApplicationController private - def authorize_group_milestone! + def authorize_admin_milestones! return render_404 unless can?(current_user, :admin_milestones, group) end @@ -48,8 +52,4 @@ class Groups::MilestonesController < Groups::ApplicationController def milestone_path(title) group_milestone_path(@group, title.to_slug.to_s, title: title) end - - def projects - @projects ||= @group.projects - end end diff --git a/app/controllers/groups_controller.rb b/app/controllers/groups_controller.rb index 5f9844104b..c1adc99956 100644 --- a/app/controllers/groups_controller.rb +++ b/app/controllers/groups_controller.rb @@ -5,16 +5,15 @@ class GroupsController < Groups::ApplicationController respond_to :html - skip_before_action :authenticate_user!, only: [:index, :show, :issues, :merge_requests] + before_action :authenticate_user!, only: [:new, :create] before_action :group, except: [:index, :new, :create] # Authorize - before_action :authorize_read_group!, except: [:index, :show, :new, :create, :autocomplete] before_action :authorize_admin_group!, only: [:edit, :update, :destroy, :projects] before_action :authorize_create_group!, only: [:new, :create] # Load group projects - before_action :load_projects, except: [:index, :new, :create, :projects, :edit, :update, :autocomplete] + before_action :group_projects, only: [:show, :projects, :activity, :issues, :merge_requests] before_action :event_filter, only: [:activity] layout :determine_layout @@ -28,11 +27,9 @@ class GroupsController < Groups::ApplicationController end def create - @group = Group.new(group_params) - @group.name = @group.path.dup unless @group.name + @group = Groups::CreateService.new(current_user, group_params).execute - if @group.save - @group.add_owner(current_user) + if @group.persisted? redirect_to @group, notice: "Group '#{@group.name}' was successfully created." else render action: "new" @@ -41,12 +38,13 @@ class GroupsController < Groups::ApplicationController def show @last_push = current_user.recent_push if current_user + @projects = @projects.includes(:namespace) @projects = filter_projects(@projects) @projects = @projects.sort(@sort = params[:sort]) @projects = @projects.page(params[:page]) if params[:filter_projects].blank? - @shared_projects = @group.shared_projects + @shared_projects = GroupProjectsFinder.new(group, only_shared: true).execute(current_user) respond_to do |format| format.html @@ -83,7 +81,7 @@ class GroupsController < Groups::ApplicationController end def update - if @group.update_attributes(group_params) + if Groups::UpdateService.new(@group, current_user, group_params).execute redirect_to edit_group_path(@group), notice: "Group '#{@group.name}' was successfully updated." else render action: "edit" @@ -98,26 +96,6 @@ class GroupsController < Groups::ApplicationController protected - def group - @group ||= Group.find_by(path: params[:id]) - @group || render_404 - end - - def load_projects - @projects ||= ProjectsFinder.new.execute(current_user, group: group).sorted_by_activity - end - - # Dont allow unauthorized access to group - def authorize_read_group! - unless @group and (@projects.present? or can?(current_user, :read_group, @group)) - if current_user.nil? - return authenticate_user! - else - return render_404 - end - end - end - def authorize_create_group! unless can?(current_user, :create_group, nil) return render_404 @@ -135,7 +113,7 @@ class GroupsController < Groups::ApplicationController end def group_params - params.require(:group).permit(:name, :description, :path, :avatar, :public, :share_with_group_lock) + params.require(:group).permit(:name, :description, :path, :avatar, :public, :visibility_level, :share_with_group_lock) end def load_events diff --git a/app/controllers/namespaces_controller.rb b/app/controllers/namespaces_controller.rb index 282012c60a..5a94dcb0db 100644 --- a/app/controllers/namespaces_controller.rb +++ b/app/controllers/namespaces_controller.rb @@ -14,7 +14,7 @@ class NamespacesController < ApplicationController if user redirect_to user_path(user) - elsif group + elsif group && can?(current_user, :read_group, namespace) redirect_to group_path(group) elsif current_user.nil? authenticate_user! diff --git a/app/controllers/profiles_controller.rb b/app/controllers/profiles_controller.rb index 9042d8e5f0..c5fa756d02 100644 --- a/app/controllers/profiles_controller.rb +++ b/app/controllers/profiles_controller.rb @@ -11,15 +11,16 @@ class ProfilesController < Profiles::ApplicationController def update user_params.except!(:email) if @user.ldap_user? - if @user.update_attributes(user_params) - flash[:notice] = "Profile was successfully updated" - else - messages = @user.errors.full_messages.uniq.join('. ') - flash[:alert] = "Failed to update profile. #{messages}" - end - respond_to do |format| - format.html { redirect_back_or_default(default: { action: 'show' }) } + if @user.update_attributes(user_params) + message = "Profile was successfully updated" + format.html { redirect_back_or_default(default: { action: 'show' }, options: { notice: message }) } + format.json { render json: { message: message } } + else + message = @user.errors.full_messages.uniq.join('. ') + format.html { redirect_back_or_default(default: { action: 'show' }, options: { alert: "Failed to update profile. #{message}" }) } + format.json { render json: { message: message }, status: :unprocessable_entity } + end end end diff --git a/app/controllers/projects/application_controller.rb b/app/controllers/projects/application_controller.rb index a326bc5821..657ee94cfd 100644 --- a/app/controllers/projects/application_controller.rb +++ b/app/controllers/projects/application_controller.rb @@ -1,20 +1,74 @@ class Projects::ApplicationController < ApplicationController + skip_before_action :authenticate_user! before_action :project before_action :repository layout 'project' - def authenticate_user! - # Restrict access to Projects area only - # for non-signed users - if !current_user - id = params[:project_id] || params[:id] - project_with_namespace = "#{params[:namespace_id]}/#{id}" - @project = Project.find_with_namespace(project_with_namespace) + helper_method :repository, :can_collaborate_with_project? - return if @project && @project.public? + private + + def project + unless @project + namespace = params[:namespace_id] + id = params[:project_id] || params[:id] + + # Redirect from + # localhost/group/project.git + # to + # localhost/group/project + # + if id =~ /\.git\Z/ + redirect_to request.original_url.gsub(/\.git\/?\Z/, '') + return + end + + project_path = "#{namespace}/#{id}" + @project = Project.find_with_namespace(project_path) + + if @project && can?(current_user, :read_project, @project) + if @project.path_with_namespace != project_path + redirect_to request.original_url.gsub(project_path, @project.path_with_namespace) + end + else + @project = nil + + if current_user.nil? + authenticate_user! + else + render_404 + end + end end - super + @project + end + + def repository + @repository ||= project.repository + end + + def can_collaborate_with_project?(project = nil) + project ||= @project + + can?(current_user, :push_code, project) || + (current_user && current_user.already_forked?(project)) + end + + def authorize_project!(action) + return access_denied! unless can?(current_user, action, project) + end + + def method_missing(method_sym, *arguments, &block) + if method_sym.to_s =~ /\Aauthorize_(.*)!\z/ + authorize_project!($1.to_sym) + else + super + end + end + + def require_non_empty_project + redirect_to namespace_project_path(@project.namespace, @project) if @project.empty_repo? end def require_branch_head @@ -26,8 +80,6 @@ class Projects::ApplicationController < ApplicationController end end - private - def apply_diff_view_cookie! view = params[:view] || cookies[:diff_view] cookies.permanent[:diff_view] = params[:view] = view if view diff --git a/app/controllers/projects/avatars_controller.rb b/app/controllers/projects/avatars_controller.rb index a6bebc46b0..72921b3aa1 100644 --- a/app/controllers/projects/avatars_controller.rb +++ b/app/controllers/projects/avatars_controller.rb @@ -1,7 +1,7 @@ class Projects::AvatarsController < Projects::ApplicationController include BlobHelper - before_action :project + before_action :authorize_admin_project!, only: [:destroy] def show @blob = @repository.blob_at_branch('master', @project.avatar_in_git) diff --git a/app/controllers/projects/issues_controller.rb b/app/controllers/projects/issues_controller.rb index a3c28a82d2..877b39c9b1 100644 --- a/app/controllers/projects/issues_controller.rb +++ b/app/controllers/projects/issues_controller.rb @@ -1,5 +1,6 @@ class Projects::IssuesController < Projects::ApplicationController include ToggleSubscriptionAction + include IssuableActions before_action :module_enabled before_action :issue, only: [:edit, :update, :show] @@ -133,6 +134,7 @@ class Projects::IssuesController < Projects::ApplicationController end end alias_method :subscribable_resource, :issue + alias_method :issuable, :issue def authorize_read_issue! return render_404 unless can?(current_user, :read_issue, @issue) diff --git a/app/controllers/projects/merge_requests_controller.rb b/app/controllers/projects/merge_requests_controller.rb index 99cb598194..b830d77775 100644 --- a/app/controllers/projects/merge_requests_controller.rb +++ b/app/controllers/projects/merge_requests_controller.rb @@ -1,6 +1,7 @@ class Projects::MergeRequestsController < Projects::ApplicationController include ToggleSubscriptionAction include DiffHelper + include IssuableActions before_action :module_enabled before_action :merge_request, only: [ @@ -255,6 +256,7 @@ class Projects::MergeRequestsController < Projects::ApplicationController @merge_request ||= @project.merge_requests.find_by!(iid: params[:id]) end alias_method :subscribable_resource, :merge_request + alias_method :issuable, :merge_request def closes_issues @closes_issues ||= @merge_request.closes_issues diff --git a/app/controllers/projects/uploads_controller.rb b/app/controllers/projects/uploads_controller.rb index e1fe7ea211..caed064dfb 100644 --- a/app/controllers/projects/uploads_controller.rb +++ b/app/controllers/projects/uploads_controller.rb @@ -1,7 +1,9 @@ class Projects::UploadsController < Projects::ApplicationController - skip_before_action :authenticate_user!, :reject_blocked!, :project, + skip_before_action :reject_blocked!, :project, :repository, if: -> { action_name == 'show' && image? } + before_action :authorize_upload_file!, only: [:create] + def create link_to_file = ::Projects::UploadService.new(project, params[:file]). execute @@ -26,6 +28,8 @@ class Projects::UploadsController < Projects::ApplicationController send_file uploader.file.path, disposition: disposition end + private + def uploader return @uploader if defined?(@uploader) diff --git a/app/controllers/projects_controller.rb b/app/controllers/projects_controller.rb index c993048077..928817ba81 100644 --- a/app/controllers/projects_controller.rb +++ b/app/controllers/projects_controller.rb @@ -1,7 +1,7 @@ -class ProjectsController < ApplicationController +class ProjectsController < Projects::ApplicationController include ExtractsPath - skip_before_action :authenticate_user!, only: [:show, :activity] + before_action :authenticate_user!, except: [:show, :activity] before_action :project, except: [:new, :create] before_action :repository, except: [:new, :create] before_action :assign_ref_vars, :tree, only: [:show], if: :repo_exists? diff --git a/app/controllers/users_controller.rb b/app/controllers/users_controller.rb index 169bef670a..8e7956da48 100644 --- a/app/controllers/users_controller.rb +++ b/app/controllers/users_controller.rb @@ -108,7 +108,7 @@ class UsersController < ApplicationController end def load_groups - @groups = @user.groups.order_id_desc + @groups = JoinedGroupsFinder.new(@user).execute(current_user) end def projects_for_current_user diff --git a/app/finders/contributed_projects_finder.rb b/app/finders/contributed_projects_finder.rb index 0209649b01..a685719555 100644 --- a/app/finders/contributed_projects_finder.rb +++ b/app/finders/contributed_projects_finder.rb @@ -1,4 +1,4 @@ -class ContributedProjectsFinder +class ContributedProjectsFinder < UnionFinder def initialize(user) @user = user end @@ -11,27 +11,19 @@ class ContributedProjectsFinder # # Returns an ActiveRecord::Relation. def execute(current_user = nil) - if current_user - relation = projects_visible_to_user(current_user) - else - relation = public_projects - end + segments = all_projects(current_user) - relation.includes(:namespace).order_id_desc + find_union(segments, Project).includes(:namespace).order_id_desc end private - def projects_visible_to_user(current_user) - authorized = @user.contributed_projects.visible_to_user(current_user) + def all_projects(current_user) + projects = [] - union = Gitlab::SQL::Union. - new([authorized.select(:id), public_projects.select(:id)]) + projects << @user.contributed_projects.visible_to_user(current_user) if current_user + projects << @user.contributed_projects.public_to_user(current_user) - Project.where("projects.id IN (#{union.to_sql})") - end - - def public_projects - @user.contributed_projects.public_only + projects end end diff --git a/app/finders/group_projects_finder.rb b/app/finders/group_projects_finder.rb new file mode 100644 index 0000000000..3b9a421b11 --- /dev/null +++ b/app/finders/group_projects_finder.rb @@ -0,0 +1,42 @@ +class GroupProjectsFinder < UnionFinder + def initialize(group, options = {}) + @group = group + @options = options + end + + def execute(current_user = nil) + segments = group_projects(current_user) + find_union(segments, Project) + end + + private + + def group_projects(current_user) + only_owned = @options.fetch(:only_owned, false) + only_shared = @options.fetch(:only_shared, false) + + projects = [] + + if current_user + if @group.users.include?(current_user) + projects << @group.projects unless only_shared + projects << @group.shared_projects unless only_owned + else + unless only_shared + projects << @group.projects.visible_to_user(current_user) + projects << @group.projects.public_to_user(current_user) + end + + unless only_owned + projects << @group.shared_projects.visible_to_user(current_user) + projects << @group.shared_projects.public_to_user(current_user) + end + end + else + projects << @group.projects.public_only unless only_shared + projects << @group.shared_projects.public_only unless only_owned + end + + projects + end +end diff --git a/app/finders/groups_finder.rb b/app/finders/groups_finder.rb new file mode 100644 index 0000000000..4e43f42e9e --- /dev/null +++ b/app/finders/groups_finder.rb @@ -0,0 +1,18 @@ +class GroupsFinder < UnionFinder + def execute(current_user = nil) + segments = all_groups(current_user) + + find_union(segments, Group).order_id_desc + end + + private + + def all_groups(current_user) + groups = [] + + groups << current_user.authorized_groups if current_user + groups << Group.unscoped.public_to_user(current_user) + + groups + end +end diff --git a/app/finders/issuable_finder.rb b/app/finders/issuable_finder.rb index 19e8c7a92b..046286dd9e 100644 --- a/app/finders/issuable_finder.rb +++ b/app/finders/issuable_finder.rb @@ -80,9 +80,10 @@ class IssuableFinder @projects = project elsif current_user && params[:authorized_only].presence && !current_user_related? @projects = current_user.authorized_projects.reorder(nil) + elsif group + @projects = GroupProjectsFinder.new(group).execute(current_user).reorder(nil) else - @projects = ProjectsFinder.new.execute(current_user, group: group). - reorder(nil) + @projects = ProjectsFinder.new.execute(current_user).reorder(nil) end end @@ -171,14 +172,12 @@ class IssuableFinder def by_scope(items) case params[:scope] - when 'created-by-me', 'authored' then + when 'created-by-me', 'authored' items.where(author_id: current_user.id) - when 'all' then - items - when 'assigned-to-me' then + when 'assigned-to-me' items.where(assignee_id: current_user.id) else - raise 'You must specify default scope' + items end end @@ -198,8 +197,7 @@ class IssuableFinder end def by_group(items) - items = items.of_group(group) if group - + # Selection by group is already covered by `by_project` and `projects` items end diff --git a/app/finders/joined_groups_finder.rb b/app/finders/joined_groups_finder.rb new file mode 100644 index 0000000000..4717498025 --- /dev/null +++ b/app/finders/joined_groups_finder.rb @@ -0,0 +1,24 @@ +class JoinedGroupsFinder < UnionFinder + def initialize(user) + @user = user + end + + # Finds the groups of the source user, optionally limited to those visible to + # the current user. + def execute(current_user = nil) + segments = all_groups(current_user) + + find_union(segments, Group).order_id_desc + end + + private + + def all_groups(current_user) + groups = [] + + groups << @user.authorized_groups.visible_to_user(current_user) if current_user + groups << @user.authorized_groups.public_to_user(current_user) + + groups + end +end diff --git a/app/finders/personal_projects_finder.rb b/app/finders/personal_projects_finder.rb index a61ffa2299..3ad4bd5f06 100644 --- a/app/finders/personal_projects_finder.rb +++ b/app/finders/personal_projects_finder.rb @@ -1,4 +1,4 @@ -class PersonalProjectsFinder +class PersonalProjectsFinder < UnionFinder def initialize(user) @user = user end @@ -11,31 +11,19 @@ class PersonalProjectsFinder # # Returns an ActiveRecord::Relation. def execute(current_user = nil) - if current_user - relation = projects_visible_to_user(current_user) - else - relation = public_projects - end + segments = all_projects(current_user) - relation.includes(:namespace).order_id_desc + find_union(segments, Project).includes(:namespace).order_id_desc end private - def projects_visible_to_user(current_user) - authorized = @user.personal_projects.visible_to_user(current_user) + def all_projects(current_user) + projects = [] - union = Gitlab::SQL::Union. - new([authorized.select(:id), public_and_internal_projects.select(:id)]) + projects << @user.personal_projects.visible_to_user(current_user) if current_user + projects << @user.personal_projects.public_to_user(current_user) - Project.where("projects.id IN (#{union.to_sql})") - end - - def public_projects - @user.personal_projects.public_only - end - - def public_and_internal_projects - @user.personal_projects.public_and_internal_only + projects end end diff --git a/app/finders/projects_finder.rb b/app/finders/projects_finder.rb index 3a5fc5b590..2f0a9659d1 100644 --- a/app/finders/projects_finder.rb +++ b/app/finders/projects_finder.rb @@ -1,81 +1,18 @@ -class ProjectsFinder - # Returns all projects, optionally including group projects a user has access - # to. - # - # ## Examples - # - # Retrieving all public projects: - # - # ProjectsFinder.new.execute - # - # Retrieving all public/internal projects and those the given user has access - # to: - # - # ProjectsFinder.new.execute(some_user) - # - # Retrieving all public/internal projects as well as the group's projects the - # user has access to: - # - # ProjectsFinder.new.execute(some_user, group: some_group) - # - # Returns an ActiveRecord::Relation. +class ProjectsFinder < UnionFinder def execute(current_user = nil, options = {}) - group = options[:group] + segments = all_projects(current_user) - if group - segments = group_projects(current_user, group) - else - segments = all_projects(current_user) - end - - if segments.length > 1 - union = Gitlab::SQL::Union.new(segments.map { |s| s.select(:id) }) - - Project.where("projects.id IN (#{union.to_sql})") - else - segments.first - end + find_union(segments, Project) end private - def group_projects(current_user, group) - return [group.projects.public_only] unless current_user - - user_group_projects = [ - group_projects_for_user(current_user, group), - group.shared_projects.visible_to_user(current_user) - ] - if current_user.external? - user_group_projects << group.projects.public_only - else - user_group_projects << group.projects.public_and_internal_only - end - end - def all_projects(current_user) - return [public_projects] unless current_user + projects = [] - if current_user.external? - [current_user.authorized_projects, public_projects] - else - [current_user.authorized_projects, public_and_internal_projects] - end - end + projects << current_user.authorized_projects if current_user + projects << Project.unscoped.public_to_user(current_user) - def group_projects_for_user(current_user, group) - if group.users.include?(current_user) - group.projects - else - group.projects.visible_to_user(current_user) - end - end - - def public_projects - Project.unscoped.public_only - end - - def public_and_internal_projects - Project.unscoped.public_and_internal_only + projects end end diff --git a/app/finders/union_finder.rb b/app/finders/union_finder.rb new file mode 100644 index 0000000000..33cd1a491f --- /dev/null +++ b/app/finders/union_finder.rb @@ -0,0 +1,11 @@ +class UnionFinder + def find_union(segments, klass) + if segments.length > 1 + union = Gitlab::SQL::Union.new(segments.map { |s| s.select(:id) }) + + klass.where("#{klass.table_name}.id IN (#{union.to_sql})") + else + segments.first + end + end +end diff --git a/app/helpers/blob_helper.rb b/app/helpers/blob_helper.rb index 0f77b3b299..820d69c230 100644 --- a/app/helpers/blob_helper.rb +++ b/app/helpers/blob_helper.rb @@ -27,7 +27,7 @@ module BlobHelper link_opts) if !on_top_of_branch?(project, ref) - button_tag "Edit", class: "btn btn-default disabled has_tooltip", title: "You can only edit files when you are on a branch", data: { container: 'body' } + button_tag "Edit", class: "btn btn-default disabled has-tooltip", title: "You can only edit files when you are on a branch", data: { container: 'body' } elsif can_edit_blob?(blob, project, ref) link_to "Edit", edit_path, class: 'btn' elsif can?(current_user, :fork_project, project) @@ -50,9 +50,9 @@ module BlobHelper return unless blob if !on_top_of_branch?(project, ref) - button_tag label, class: "btn btn-#{btn_class} disabled has_tooltip", title: "You can only #{action} files when you are on a branch", data: { container: 'body' } + button_tag label, class: "btn btn-#{btn_class} disabled has-tooltip", title: "You can only #{action} files when you are on a branch", data: { container: 'body' } elsif blob.lfs_pointer? - button_tag label, class: "btn btn-#{btn_class} disabled has_tooltip", title: "It is not possible to #{action} files that are stored in LFS using the web interface", data: { container: 'body' } + button_tag label, class: "btn btn-#{btn_class} disabled has-tooltip", title: "It is not possible to #{action} files that are stored in LFS using the web interface", data: { container: 'body' } elsif can_edit_blob?(blob, project, ref) button_tag label, class: "btn btn-#{btn_class}", 'data-target' => "#modal-#{modal_type}-blob", 'data-toggle' => 'modal' elsif can?(current_user, :fork_project, project) diff --git a/app/helpers/button_helper.rb b/app/helpers/button_helper.rb index ee2cb6ab0e..a9047ede8c 100644 --- a/app/helpers/button_helper.rb +++ b/app/helpers/button_helper.rb @@ -24,7 +24,7 @@ module ButtonHelper def http_clone_button(project) klass = 'http-selector' - klass << ' has_tooltip' if current_user.try(:require_password?) + klass << ' has-tooltip' if current_user.try(:require_password?) protocol = gitlab_config.protocol.upcase @@ -41,7 +41,7 @@ module ButtonHelper def ssh_clone_button(project) klass = 'ssh-selector' - klass << ' has_tooltip' if current_user.try(:require_ssh_key?) + klass << ' has-tooltip' if current_user.try(:require_ssh_key?) content_tag :a, 'SSH', class: klass, diff --git a/app/helpers/commits_helper.rb b/app/helpers/commits_helper.rb index f994c9e617..bde0799f3d 100644 --- a/app/helpers/commits_helper.rb +++ b/app/helpers/commits_helper.rb @@ -182,7 +182,7 @@ module CommitsHelper end options = { - class: "commit-#{options[:source]}-link has_tooltip", + class: "commit-#{options[:source]}-link has-tooltip", data: { 'original-title'.to_sym => sanitize(source_email) } } diff --git a/app/helpers/dropdowns_helper.rb b/app/helpers/dropdowns_helper.rb index ceff1fbb16..316a10b7da 100644 --- a/app/helpers/dropdowns_helper.rb +++ b/app/helpers/dropdowns_helper.rb @@ -70,7 +70,8 @@ module DropdownsHelper def dropdown_filter(placeholder) content_tag :div, class: "dropdown-input" do filter_output = search_field_tag nil, nil, class: "dropdown-input-field", placeholder: placeholder - filter_output << icon('search') + filter_output << icon('search', class: "dropdown-input-search") + filter_output << icon('times', class: "dropdown-input-clear js-dropdown-input-clear", role: "button") filter_output.html_safe end diff --git a/app/helpers/groups_helper.rb b/app/helpers/groups_helper.rb index 1d36969cd6..b1f0a765bb 100644 --- a/app/helpers/groups_helper.rb +++ b/app/helpers/groups_helper.rb @@ -19,6 +19,10 @@ module GroupsHelper end end + def can_change_group_visibility_level?(group) + can?(current_user, :change_visibility_level, group) + end + def group_icon(group) if group.is_a?(String) group = Group.find_by(path: group) diff --git a/app/helpers/labels_helper.rb b/app/helpers/labels_helper.rb index ed37176aa6..3dded7c2f2 100644 --- a/app/helpers/labels_helper.rb +++ b/app/helpers/labels_helper.rb @@ -56,7 +56,7 @@ module LabelsHelper # Intentionally not using content_tag here so that this method can be called # by LabelReferenceFilter - span = %() + %(#{escape_once(label.name)}#{label_suffix}) @@ -114,7 +114,7 @@ module LabelsHelper if @project namespace_project_labels_path(@project.namespace, @project, :json) else - labels_dashboard_path(:json) + dashboard_labels_path(:json) end end diff --git a/app/helpers/milestones_helper.rb b/app/helpers/milestones_helper.rb index c9d8787bd1..87fc2db690 100644 --- a/app/helpers/milestones_helper.rb +++ b/app/helpers/milestones_helper.rb @@ -50,7 +50,7 @@ module MilestonesHelper if @project namespace_project_milestones_path(@project.namespace, @project, :json) else - milestones_dashboard_path(:json) + dashboard_milestones_path(:json) end end diff --git a/app/helpers/projects_helper.rb b/app/helpers/projects_helper.rb index 322a7021fd..4e4c6e301d 100644 --- a/app/helpers/projects_helper.rb +++ b/app/helpers/projects_helper.rb @@ -52,7 +52,7 @@ module ProjectsHelper link_to(author_html, user_path(author), class: "author_link #{"#{opts[:mobile_classes]}" if opts[:mobile_classes]}").html_safe else title = opts[:title].sub(":name", sanitize(author.name)) - link_to(author_html, user_path(author), class: "author_link has_tooltip", data: { 'original-title'.to_sym => title, container: 'body' } ).html_safe + link_to(author_html, user_path(author), class: "author_link has-tooltip", data: { 'original-title'.to_sym => title, container: 'body' } ).html_safe end end diff --git a/app/helpers/visibility_level_helper.rb b/app/helpers/visibility_level_helper.rb index 71d33b445c..3a83ae15dd 100644 --- a/app/helpers/visibility_level_helper.rb +++ b/app/helpers/visibility_level_helper.rb @@ -19,6 +19,8 @@ module VisibilityLevelHelper case form_model when Project project_visibility_level_description(level) + when Group + group_visibility_level_description(level) when Snippet snippet_visibility_level_description(level, form_model) end @@ -35,6 +37,17 @@ module VisibilityLevelHelper end end + def group_visibility_level_description(level) + case level + when Gitlab::VisibilityLevel::PRIVATE + "The group and its projects can only be viewed by members." + when Gitlab::VisibilityLevel::INTERNAL + "The group and any internal projects can be viewed by any logged in user." + when Gitlab::VisibilityLevel::PUBLIC + "The group and any public projects can be viewed without any authentication." + end + end + def snippet_visibility_level_description(level, snippet = nil) case level when Gitlab::VisibilityLevel::PRIVATE @@ -50,6 +63,23 @@ module VisibilityLevelHelper end end + def visibility_icon_description(form_model) + case form_model + when Project + project_visibility_icon_description(form_model.visibility_level) + when Group + group_visibility_icon_description(form_model.visibility_level) + end + end + + def group_visibility_icon_description(level) + "#{visibility_level_label(level)} - #{group_visibility_level_description(level)}" + end + + def project_visibility_icon_description(level) + "#{visibility_level_label(level)} - #{project_visibility_level_description(level)}" + end + def visibility_level_label(level) Project.visibility_levels.key(level) end @@ -67,8 +97,11 @@ module VisibilityLevelHelper current_application_settings.default_snippet_visibility end + def default_group_visibility + current_application_settings.default_group_visibility + end + def skip_level?(form_model, level) - form_model.is_a?(Project) && - !form_model.visibility_level_allowed?(level) + form_model.is_a?(Project) && !form_model.visibility_level_allowed?(level) end end diff --git a/app/models/ability.rb b/app/models/ability.rb index e22da4806e..fa2345f6fa 100644 --- a/app/models/ability.rb +++ b/app/models/ability.rb @@ -85,7 +85,7 @@ class Ability subject.group end - if group && group.projects.public_only.any? + if group && group.public? [:read_group] else [] @@ -114,6 +114,13 @@ class Ability # Push abilities on the users team role rules.push(*project_team_rules(project.team, user)) + if project.owner == user || + (project.group && project.group.has_owner?(user)) || + user.admin? + + rules.push(*project_owner_rules) + end + if project.public? || (project.internal? && !user.external?) rules.push(*public_project_rules) @@ -121,14 +128,6 @@ class Ability rules << :read_build if project.public_builds? end - if project.owner == user || user.admin? - rules.push(*project_admin_rules) - end - - if project.group && project.group.has_owner?(user) - rules.push(*project_admin_rules) - end - if project.archived? rules -= project_archived_rules end @@ -171,7 +170,8 @@ class Ability :read_note, :create_project, :create_issue, - :create_note + :create_note, + :upload_file ] end @@ -228,14 +228,16 @@ class Ability ] end - def project_admin_rules - @project_admin_rules ||= project_master_rules + [ + def project_owner_rules + @project_owner_rules ||= project_master_rules + [ :change_namespace, :change_visibility_level, :rename_project, :remove_project, :archive_project, - :remove_fork_project + :remove_fork_project, + :destroy_merge_request, + :destroy_issue ] end @@ -273,11 +275,9 @@ class Ability def group_abilities(user, group) rules = [] - if user.admin? || group.users.include?(user) || ProjectsFinder.new.execute(user, group: group).any? - rules << :read_group - end + rules << :read_group if can_read_group?(user, group) - # Only group masters and group owners can create new projects in group + # Only group masters and group owners can create new projects if group.has_master?(user) || group.has_owner?(user) || user.admin? rules += [ :create_projects, @@ -290,13 +290,23 @@ class Ability rules += [ :admin_group, :admin_namespace, - :admin_group_member + :admin_group_member, + :change_visibility_level ] end rules.flatten end + def can_read_group?(user, group) + return true if user.admin? + return true if group.public? + return true if group.internal? && !user.external? + return true if group.users.include?(user) + + GroupProjectsFinder.new(group).execute(user).any? + end + def namespace_abilities(user, namespace) rules = [] diff --git a/app/models/application_setting.rb b/app/models/application_setting.rb index 269056e0e7..c4879598c4 100644 --- a/app/models/application_setting.rb +++ b/app/models/application_setting.rb @@ -18,6 +18,7 @@ # max_attachment_size :integer default(10), not null # default_project_visibility :integer # default_snippet_visibility :integer +# default_group_visibility :integer # restricted_signup_domains :text # user_oauth_applications :boolean default(TRUE) # after_sign_out_path :string(255) diff --git a/app/models/commit.rb b/app/models/commit.rb index ce0b85d50c..d0dbe009d0 100644 --- a/app/models/commit.rb +++ b/app/models/commit.rb @@ -230,7 +230,7 @@ class Commit end def revert_message - %Q{Revert "#{title}"\n\n#{revert_description}} + %Q{Revert "#{title.strip}"\n\n#{revert_description}} end def reverts_commit?(commit) diff --git a/app/models/concerns/internal_id.rb b/app/models/concerns/internal_id.rb index 821ed54fb9..51288094ef 100644 --- a/app/models/concerns/internal_id.rb +++ b/app/models/concerns/internal_id.rb @@ -7,7 +7,10 @@ module InternalId end def set_iid - max_iid = project.send(self.class.name.tableize).maximum(:iid) + records = project.send(self.class.name.tableize) + records = records.with_deleted if self.paranoid? + max_iid = records.maximum(:iid) + self.iid = max_iid.to_i + 1 end diff --git a/app/models/concerns/issuable.rb b/app/models/concerns/issuable.rb index 9ab7265219..cf5b2c7167 100644 --- a/app/models/concerns/issuable.rb +++ b/app/models/concerns/issuable.rb @@ -41,7 +41,7 @@ module Issuable scope :join_project, -> { joins(:project) } scope :references_project, -> { references(:project) } - scope :non_archived, -> { join_project.merge(Project.non_archived) } + scope :non_archived, -> { join_project.merge(Project.non_archived.only(:where)) } delegate :name, :email, @@ -58,6 +58,8 @@ module Issuable attr_mentionable :description, cache: true participant :author, :assignee, :notes_with_associations strip_attributes :title + + acts_as_paranoid end module ClassMethods diff --git a/app/models/group.rb b/app/models/group.rb index 9919ca112d..b332601c59 100644 --- a/app/models/group.rb +++ b/app/models/group.rb @@ -2,15 +2,16 @@ # # Table name: namespaces # -# id :integer not null, primary key -# name :string(255) not null -# path :string(255) not null -# owner_id :integer -# created_at :datetime -# updated_at :datetime -# type :string(255) -# description :string(255) default(""), not null -# avatar :string(255) +# id :integer not null, primary key +# name :string(255) not null +# path :string(255) not null +# owner_id :integer +# visibility_level :integer default(20), not null +# created_at :datetime +# updated_at :datetime +# type :string(255) +# description :string(255) default(""), not null +# avatar :string(255) # require 'carrierwave/orm/activerecord' @@ -18,6 +19,7 @@ require 'file_size_validator' class Group < Namespace include Gitlab::ConfigHelper + include Gitlab::VisibilityLevel include Referable has_many :group_members, dependent: :destroy, as: :source, class_name: 'GroupMember' @@ -27,6 +29,8 @@ class Group < Namespace has_many :shared_projects, through: :project_group_links, source: :project validate :avatar_type, if: ->(user) { user.avatar.present? && user.avatar_changed? } + validate :visibility_level_allowed_by_projects + validates :avatar, file_size: { maximum: 200.kilobytes.to_i } mount_uploader :avatar, AvatarUploader @@ -74,6 +78,21 @@ class Group < Namespace name end + def visibility_level_field + visibility_level + end + + def visibility_level_allowed_by_projects + allowed_by_projects = self.projects.where('visibility_level > ?', self.visibility_level).none? + + unless allowed_by_projects + level_name = Gitlab::VisibilityLevel.level_name(visibility_level).downcase + self.errors.add(:visibility_level, "#{level_name} is not allowed since there are projects with higher visibility.") + end + + allowed_by_projects + end + def avatar_url(size = nil) if avatar.present? [gitlab_config.url, avatar.url].join diff --git a/app/models/issue.rb b/app/models/issue.rb index ddb51ad577..ed960cb39f 100644 --- a/app/models/issue.rb +++ b/app/models/issue.rb @@ -36,9 +36,6 @@ class Issue < ActiveRecord::Base validates :project, presence: true - scope :of_group, - ->(group) { where(project_id: group.projects.select(:id).reorder(nil)) } - scope :cared, ->(user) { where(assignee_id: user) } scope :open_for, ->(user) { opened.assigned_to(user) } scope :in_projects, ->(project_ids) { where(project_id: project_ids) } @@ -149,7 +146,8 @@ class Issue < ActiveRecord::Base return false unless user.can?(:admin_issue, to_project) end - !moved? && user.can?(:admin_issue, self.project) + !moved? && persisted? && + user.can?(:admin_issue, self.project) end def to_branch_name diff --git a/app/models/label.rb b/app/models/label.rb index f7ffc0b7f3..500d5a3552 100644 --- a/app/models/label.rb +++ b/app/models/label.rb @@ -97,12 +97,12 @@ class Label < ActiveRecord::Base end end - def open_issues_count - issues.opened.count + def open_issues_count(user = nil) + issues.visible_to_user(user).opened.count end - def closed_issues_count - issues.closed.count + def closed_issues_count(user = nil) + issues.visible_to_user(user).closed.count end def open_merge_requests_count diff --git a/app/models/merge_request.rb b/app/models/merge_request.rb index a015a9ef39..ef48207f95 100644 --- a/app/models/merge_request.rb +++ b/app/models/merge_request.rb @@ -131,7 +131,6 @@ class MergeRequest < ActiveRecord::Base validate :validate_branches validate :validate_fork - scope :of_group, ->(group) { where("source_project_id in (:group_project_ids) OR target_project_id in (:group_project_ids)", group_project_ids: group.projects.select(:id).reorder(nil)) } scope :by_branch, ->(branch_name) { where("(source_branch LIKE :branch) OR (target_branch LIKE :branch)", branch: branch_name) } scope :cared, ->(user) { where('assignee_id = :user OR author_id = :user', user: user.id) } scope :by_milestone, ->(milestone) { where(milestone_id: milestone) } diff --git a/app/models/milestone.rb b/app/models/milestone.rb index de7183bf6b..bbd59eab9a 100644 --- a/app/models/milestone.rb +++ b/app/models/milestone.rb @@ -83,7 +83,7 @@ class Milestone < ActiveRecord::Base end def self.upcoming - self.where('due_date > ?', Time.now).order(due_date: :asc).first + self.where('due_date > ?', Time.now).reorder(due_date: :asc).first end def to_reference(from_project = nil) diff --git a/app/models/project.rb b/app/models/project.rb index fd36dca0ca..2285063ab5 100644 --- a/app/models/project.rb +++ b/app/models/project.rb @@ -73,7 +73,7 @@ class Project < ActiveRecord::Base update_column(:last_activity_at, self.created_at) end - # update visibility_levet of forks + # update visibility_level of forks after_update :update_forks_visibility_level def update_forks_visibility_level return unless visibility_level < visibility_level_was @@ -197,6 +197,8 @@ class Project < ActiveRecord::Base validate :avatar_type, if: ->(project) { project.avatar.present? && project.avatar_changed? } validates :avatar, file_size: { maximum: 200.kilobytes.to_i } + validate :visibility_level_allowed_by_group + validate :visibility_level_allowed_as_fork add_authentication_token_field :runners_token before_save :ensure_runners_token @@ -215,8 +217,6 @@ class Project < ActiveRecord::Base scope :in_group_namespace, -> { joins(:group) } scope :personal, ->(user) { where(namespace_id: user.namespace_id) } scope :joined, ->(user) { where('namespace_id != ?', user.namespace_id) } - scope :public_only, -> { where(visibility_level: Project::PUBLIC) } - scope :public_and_internal_only, -> { where(visibility_level: Project.public_and_internal_levels) } scope :non_archived, -> { where(archived: false) } scope :for_milestones, ->(ids) { joins(:milestones).where('milestones.id' => ids).distinct } @@ -246,10 +246,6 @@ class Project < ActiveRecord::Base end class << self - def public_and_internal_levels - [Project::PUBLIC, Project::INTERNAL] - end - def abandoned where('projects.last_activity_at < ?', 6.months.ago) end @@ -308,7 +304,7 @@ class Project < ActiveRecord::Base end def find_with_namespace(id) - namespace_path, project_path = id.split('/') + namespace_path, project_path = id.split('/', 2) return nil if !namespace_path || !project_path @@ -435,6 +431,7 @@ class Project < ActiveRecord::Base def safe_import_url result = URI.parse(self.import_url) result.password = '*****' unless result.password.nil? + result.user = '*****' unless result.user.nil? || result.user == "git" #tokens or other data may be saved as user result.to_s rescue self.import_url @@ -442,10 +439,25 @@ class Project < ActiveRecord::Base def check_limit unless creator.can_create_project? or namespace.kind == 'group' - errors[:limit_reached] << ("Your project limit is #{creator.projects_limit} projects! Please contact your administrator to increase it") + self.errors.add(:limit_reached, "Your project limit is #{creator.projects_limit} projects! Please contact your administrator to increase it") end rescue - errors[:base] << ("Can't check your ability to create project") + self.errors.add(:base, "Can't check your ability to create project") + end + + def visibility_level_allowed_by_group + return if visibility_level_allowed_by_group? + + level_name = Gitlab::VisibilityLevel.level_name(self.visibility_level).downcase + group_level_name = Gitlab::VisibilityLevel.level_name(self.group.visibility_level).downcase + self.errors.add(:visibility_level, "#{level_name} is not allowed in a #{group_level_name} group.") + end + + def visibility_level_allowed_as_fork + return if visibility_level_allowed_as_fork? + + level_name = Gitlab::VisibilityLevel.level_name(self.visibility_level).downcase + self.errors.add(:visibility_level, "#{level_name} is not allowed since the fork source project has lower visibility.") end def to_param @@ -961,9 +973,25 @@ class Project < ActiveRecord::Base issues.opened.count end - def visibility_level_allowed?(level) + def visibility_level_allowed_as_fork?(level = self.visibility_level) return true unless forked? - Gitlab::VisibilityLevel.allowed_fork_levels(forked_from_project.visibility_level).include?(level.to_i) + + # self.forked_from_project will be nil before the project is saved, so + # we need to go through the relation + original_project = forked_project_link.forked_from_project + return true unless original_project + + level <= original_project.visibility_level + end + + def visibility_level_allowed_by_group?(level = self.visibility_level) + return true unless group + + level <= group.visibility_level + end + + def visibility_level_allowed?(level = self.visibility_level) + visibility_level_allowed_as_fork?(level) && visibility_level_allowed_by_group?(level) end def runners_token diff --git a/app/services/base_service.rb b/app/services/base_service.rb index 8563633816..0d55ba5a98 100644 --- a/app/services/base_service.rb +++ b/app/services/base_service.rb @@ -43,12 +43,9 @@ class BaseService def deny_visibility_level(model, denied_visibility_level = nil) denied_visibility_level ||= model.visibility_level - level_name = Gitlab::VisibilityLevel.level_name(denied_visibility_level) + level_name = Gitlab::VisibilityLevel.level_name(denied_visibility_level).downcase - model.errors.add( - :visibility_level, - "#{level_name} visibility has been restricted by your GitLab administrator" - ) + model.errors.add(:visibility_level, "#{level_name} has been restricted by your GitLab administrator") end private diff --git a/app/services/ci/create_builds_service.rb b/app/services/ci/create_builds_service.rb index 002f7ba127..2cd51a7610 100644 --- a/app/services/ci/create_builds_service.rb +++ b/app/services/ci/create_builds_service.rb @@ -1,7 +1,7 @@ module Ci class CreateBuildsService def execute(commit, stage, ref, tag, user, trigger_request, status) - builds_attrs = commit.config_processor.builds_for_stage_and_ref(stage, ref, tag) + builds_attrs = commit.config_processor.builds_for_stage_and_ref(stage, ref, tag, trigger_request) # check when to create next build builds_attrs = builds_attrs.select do |build_attrs| diff --git a/app/services/create_snippet_service.rb b/app/services/create_snippet_service.rb index 101a3df5ee..9884cb9666 100644 --- a/app/services/create_snippet_service.rb +++ b/app/services/create_snippet_service.rb @@ -6,8 +6,7 @@ class CreateSnippetService < BaseService snippet = project.snippets.build(params) end - unless Gitlab::VisibilityLevel.allowed_for?(current_user, - params[:visibility_level]) + unless Gitlab::VisibilityLevel.allowed_for?(current_user, params[:visibility_level]) deny_visibility_level(snippet) return snippet end diff --git a/app/services/groups/base_service.rb b/app/services/groups/base_service.rb new file mode 100644 index 0000000000..a8fa098246 --- /dev/null +++ b/app/services/groups/base_service.rb @@ -0,0 +1,9 @@ +module Groups + class BaseService < ::BaseService + attr_accessor :group, :current_user, :params + + def initialize(group, user, params = {}) + @group, @current_user, @params = group, user, params.dup + end + end +end diff --git a/app/services/groups/create_service.rb b/app/services/groups/create_service.rb new file mode 100644 index 0000000000..2bccd584dd --- /dev/null +++ b/app/services/groups/create_service.rb @@ -0,0 +1,21 @@ +module Groups + class CreateService < Groups::BaseService + def initialize(user, params = {}) + @current_user, @params = user, params.dup + end + + def execute + @group = Group.new(params) + + unless Gitlab::VisibilityLevel.allowed_for?(current_user, params[:visibility_level]) + deny_visibility_level(@group) + return @group + end + + @group.name ||= @group.path.dup + @group.save + @group.add_owner(current_user) + @group + end + end +end diff --git a/app/services/groups/update_service.rb b/app/services/groups/update_service.rb new file mode 100644 index 0000000000..99ad12b100 --- /dev/null +++ b/app/services/groups/update_service.rb @@ -0,0 +1,20 @@ +module Groups + class UpdateService < Groups::BaseService + def execute + # check that user is allowed to set specified visibility_level + new_visibility = params[:visibility_level] + if new_visibility && new_visibility.to_i != group.visibility_level + unless can?(current_user, :change_visibility_level, group) && + Gitlab::VisibilityLevel.allowed_for?(current_user, new_visibility) + + deny_visibility_level(group, new_visibility) + return group + end + end + + group.assign_attributes(params) + + group.save + end + end +end diff --git a/app/services/issues/move_service.rb b/app/services/issues/move_service.rb index 3cfbafe157..a5efb21fab 100644 --- a/app/services/issues/move_service.rb +++ b/app/services/issues/move_service.rb @@ -54,7 +54,8 @@ module Issues new_note = note.dup new_params = { project: @new_project, noteable: @new_issue, note: unfold_references(new_note.note), - created_at: note.created_at } + created_at: note.created_at, + updated_at: note.updated_at } new_note.update(new_params) end @@ -78,6 +79,8 @@ module Issues end def unfold_references(content) + return unless content + rewriter = Gitlab::Gfm::ReferenceRewriter.new(content, @old_project, @current_user) rewriter.rewrite(@new_project) diff --git a/app/services/notification_service.rb b/app/services/notification_service.rb index 3bdf00a829..eff0d96f93 100644 --- a/app/services/notification_service.rb +++ b/app/services/notification_service.rb @@ -162,6 +162,7 @@ class NotificationService recipients = add_subscribed_users(recipients, note.noteable) recipients = reject_unsubscribed_users(recipients, note.noteable) + recipients = reject_users_without_access(recipients, note.noteable) recipients.delete(note.author) recipients = recipients.uniq @@ -376,6 +377,14 @@ class NotificationService end end + def reject_users_without_access(recipients, target) + return recipients unless target.is_a?(Issue) + + recipients.select do |user| + user.can?(:read_issue, target) + end + end + def add_subscribed_users(recipients, target) return recipients unless target.respond_to? :subscribers @@ -464,15 +473,16 @@ class NotificationService end recipients = reject_unsubscribed_users(recipients, target) + recipients = reject_users_without_access(recipients, target) recipients.delete(current_user) - recipients.uniq end def build_relabeled_recipients(target, current_user, labels:) recipients = add_labels_subscribers([], target, labels: labels) recipients = reject_unsubscribed_users(recipients, target) + recipients = reject_users_without_access(recipients, target) recipients.delete(current_user) recipients.uniq end diff --git a/app/services/projects/create_service.rb b/app/services/projects/create_service.rb index a6820183be..501e58c140 100644 --- a/app/services/projects/create_service.rb +++ b/app/services/projects/create_service.rb @@ -9,10 +9,8 @@ module Projects @project = Project.new(params) - # Make sure that the user is allowed to use the specified visibility - # level - unless Gitlab::VisibilityLevel.allowed_for?(current_user, - params[:visibility_level]) + # Make sure that the user is allowed to use the specified visibility level + unless Gitlab::VisibilityLevel.allowed_for?(current_user, params[:visibility_level]) deny_visibility_level(@project) return @project end @@ -55,9 +53,7 @@ module Projects @project.save if @project.persisted? && !@project.import? - unless @project.create_repository - raise 'Failed to create repository' - end + raise 'Failed to create repository' unless @project.create_repository end end diff --git a/app/services/projects/update_service.rb b/app/services/projects/update_service.rb index 895e089bea..941df08995 100644 --- a/app/services/projects/update_service.rb +++ b/app/services/projects/update_service.rb @@ -3,16 +3,13 @@ module Projects def execute # check that user is allowed to set specified visibility_level new_visibility = params[:visibility_level] - if new_visibility - if new_visibility.to_i != project.visibility_level - unless can?(current_user, :change_visibility_level, project) && - Gitlab::VisibilityLevel.allowed_for?(current_user, new_visibility) - deny_visibility_level(project, new_visibility) - return project - end + if new_visibility && new_visibility.to_i != project.visibility_level + unless can?(current_user, :change_visibility_level, project) && + Gitlab::VisibilityLevel.allowed_for?(current_user, new_visibility) + + deny_visibility_level(project, new_visibility) + return project end - - return false unless visibility_level_allowed?(new_visibility) end new_branch = params[:default_branch] @@ -27,19 +24,5 @@ module Projects end end end - - private - - def visibility_level_allowed?(level) - return true if project.visibility_level_allowed?(level) - - level_name = Gitlab::VisibilityLevel.level_name(level) - project.errors.add( - :visibility_level, - "#{level_name} could not be set as visibility level of this project - parent project settings are more restrictive" - ) - - false - end end end diff --git a/app/services/update_snippet_service.rb b/app/services/update_snippet_service.rb index e9328bb732..93af8f2197 100644 --- a/app/services/update_snippet_service.rb +++ b/app/services/update_snippet_service.rb @@ -9,7 +9,6 @@ class UpdateSnippetService < BaseService def execute # check that user is allowed to set specified visibility_level new_visibility = params[:visibility_level] - if new_visibility && new_visibility.to_i != snippet.visibility_level unless Gitlab::VisibilityLevel.allowed_for?(current_user, new_visibility) deny_visibility_level(snippet, new_visibility) diff --git a/app/views/admin/application_settings/_form.html.haml b/app/views/admin/application_settings/_form.html.haml index b30dfd109e..0350995d03 100644 --- a/app/views/admin/application_settings/_form.html.haml +++ b/app/views/admin/application_settings/_form.html.haml @@ -19,6 +19,10 @@ = f.label :default_snippet_visibility, class: 'control-label col-sm-2' .col-sm-10 = render('shared/visibility_radios', model_method: :default_snippet_visibility, form: f, selected_level: @application_setting.default_snippet_visibility, form_model: ProjectSnippet.new) + .form-group.group-visibility-level-holder + = f.label :default_group_visibility, class: 'control-label col-sm-2' + .col-sm-10 + = render('shared/visibility_radios', model_method: :default_group_visibility, form: f, selected_level: @application_setting.default_group_visibility, form_model: Group.new) .form-group = f.label :restricted_visibility_levels, class: 'control-label col-sm-2' .col-sm-10 diff --git a/app/views/admin/applications/_delete_form.html.haml b/app/views/admin/applications/_delete_form.html.haml index 3147cbd659..042971e1ee 100644 --- a/app/views/admin/applications/_delete_form.html.haml +++ b/app/views/admin/applications/_delete_form.html.haml @@ -1,4 +1,4 @@ - submit_btn_css ||= 'btn btn-link btn-remove btn-sm' = form_tag admin_application_path(application) do %input{:name => "_method", :type => "hidden", :value => "delete"}/ - = submit_tag 'Destroy', onclick: "return confirm('Are you sure?')", class: submit_btn_css \ No newline at end of file + = submit_tag 'Destroy', onclick: "return confirm('Are you sure?')", class: submit_btn_css diff --git a/app/views/admin/groups/_form.html.haml b/app/views/admin/groups/_form.html.haml index 198026a1f7..7f2b1cd235 100644 --- a/app/views/admin/groups/_form.html.haml +++ b/app/views/admin/groups/_form.html.haml @@ -10,6 +10,8 @@ .col-sm-10 = render 'shared/choose_group_avatar_button', f: f + = render 'shared/visibility_level', f: f, visibility_level: @group.visibility_level, can_change_visibility_level: can_change_group_visibility_level?(@group), form_model: @group + - if @group.new_record? .form-group .col-sm-offset-2.col-sm-10 diff --git a/app/views/admin/groups/index.html.haml b/app/views/admin/groups/index.html.haml index 118d3cfea0..6bdc885a31 100644 --- a/app/views/admin/groups/index.html.haml +++ b/app/views/admin/groups/index.html.haml @@ -46,6 +46,9 @@ %h4 = link_to [:admin, group] do + %span{ class: visibility_level_color(group.visibility_level) } + = visibility_level_icon(group.visibility_level) + %i.fa.fa-folder = group.name diff --git a/app/views/admin/groups/show.html.haml b/app/views/admin/groups/show.html.haml index 264fa1bf0c..f309e80a39 100644 --- a/app/views/admin/groups/show.html.haml +++ b/app/views/admin/groups/show.html.haml @@ -27,6 +27,11 @@ %strong = @group.description + %li + %span.light Visibility level: + %strong + = visibility_level_label(@group.visibility_level) + %li %span.light Created on: %strong diff --git a/app/views/admin/projects/show.html.haml b/app/views/admin/projects/show.html.haml index d734e60682..c638c32a65 100644 --- a/app/views/admin/projects/show.html.haml +++ b/app/views/admin/projects/show.html.haml @@ -52,7 +52,7 @@ %li %span.light fs: %strong - = @repository.path_to_repo + = @project.repository.path_to_repo %li %span.light Size diff --git a/app/views/dashboard/issues.html.haml b/app/views/dashboard/issues.html.haml index dfa5f80eef..1eec4db45a 100644 --- a/app/views/dashboard/issues.html.haml +++ b/app/views/dashboard/issues.html.haml @@ -10,6 +10,8 @@ - if current_user = link_to issues_dashboard_url(format: :atom, private_token: current_user.private_token), class: 'btn' do = icon('rss') + %span.icon-label + Subscribe = render 'shared/new_project_item_select', path: 'issues/new', label: "New Issue" = render 'shared/issuable/filter', type: :issues diff --git a/app/views/devise/sessions/_new_crowd.html.haml b/app/views/devise/sessions/_new_crowd.html.haml index 4974bb7f7f..8e81671b7e 100644 --- a/app/views/devise/sessions/_new_crowd.html.haml +++ b/app/views/devise/sessions/_new_crowd.html.haml @@ -6,4 +6,4 @@ %label{for: "remember_me"} = check_box_tag :remember_me, '1', false, id: 'remember_me' %span Remember me - = button_tag "Sign in", class: "btn-save btn" \ No newline at end of file + = button_tag "Sign in", class: "btn-save btn" diff --git a/app/views/doorkeeper/applications/index.html.haml b/app/views/doorkeeper/applications/index.html.haml index ea0b66c932..55f4a6f287 100644 --- a/app/views/doorkeeper/applications/index.html.haml +++ b/app/views/doorkeeper/applications/index.html.haml @@ -77,7 +77,7 @@ %em Authorization was granted by entering your username and password in the application. %td= token.created_at %td= token.scopes - %td= render 'delete_form', token: token + %td= render 'doorkeeper/authorized_applications/delete_form', token: token - else .profile-settings-message.text-center You don't have any authorized applications diff --git a/app/views/doorkeeper/applications/new.html.haml b/app/views/doorkeeper/applications/new.html.haml index fd32a468b4..d3692d1f75 100644 --- a/app/views/doorkeeper/applications/new.html.haml +++ b/app/views/doorkeeper/applications/new.html.haml @@ -4,4 +4,4 @@ %hr -= render 'form', application: @application \ No newline at end of file += render 'form', application: @application diff --git a/app/views/doorkeeper/authorizations/error.html.haml b/app/views/doorkeeper/authorizations/error.html.haml index 7561ec85ed..a4c607cea6 100644 --- a/app/views/doorkeeper/authorizations/error.html.haml +++ b/app/views/doorkeeper/authorizations/error.html.haml @@ -1,3 +1,3 @@ %h3.page-title An error has occurred %main{:role => "main"} - %pre= @pre_auth.error_response.body[:error_description] \ No newline at end of file + %pre= @pre_auth.error_response.body[:error_description] diff --git a/app/views/doorkeeper/authorizations/show.html.haml b/app/views/doorkeeper/authorizations/show.html.haml index 9a40200719..01f9e46f14 100644 --- a/app/views/doorkeeper/authorizations/show.html.haml +++ b/app/views/doorkeeper/authorizations/show.html.haml @@ -1,3 +1,3 @@ %h3.page-title Authorization code: %main{:role => "main"} - %code#authorization_code= params[:code] \ No newline at end of file + %code#authorization_code= params[:code] diff --git a/app/views/events/event/_common.html.haml b/app/views/events/event/_common.html.haml index e9e16a7646..c994e3b997 100644 --- a/app/views/events/event/_common.html.haml +++ b/app/views/events/event/_common.html.haml @@ -4,7 +4,7 @@ = event_action_name(event) - if event.target - %strong= link_to event.target.to_reference, [event.project.namespace.becomes(Namespace), event.project, event.target] + %strong= link_to event.target.reference_link_text, [event.project.namespace.becomes(Namespace), event.project, event.target] = event_preposition(event) diff --git a/app/views/groups/edit.html.haml b/app/views/groups/edit.html.haml index 83936d39b1..ea5a035839 100644 --- a/app/views/groups/edit.html.haml +++ b/app/views/groups/edit.html.haml @@ -23,6 +23,8 @@ %hr = link_to 'Remove avatar', group_avatar_path(@group.to_param), data: { confirm: "Group avatar will be removed. Are you sure?"}, method: :delete, class: "btn btn-remove btn-sm remove-avatar" + = render 'shared/visibility_level', f: f, visibility_level: @group.visibility_level, can_change_visibility_level: can_change_group_visibility_level?(@group), form_model: @group + .form-group %hr = f.label :share_with_group_lock, class: 'control-label' do @@ -32,6 +34,7 @@ = f.check_box :share_with_group_lock %span.descr Prevent sharing a project with another group within this group + .form-actions = f.submit 'Save group', class: "btn btn-save" diff --git a/app/views/groups/issues.html.haml b/app/views/groups/issues.html.haml index b0805593fd..aea35c5086 100644 --- a/app/views/groups/issues.html.haml +++ b/app/views/groups/issues.html.haml @@ -10,6 +10,8 @@ - if current_user = link_to issues_group_url(@group, format: :atom, private_token: current_user.private_token), class: 'btn' do = icon('rss') + %span.icon-label + Subscribe = render 'shared/new_project_item_select', path: 'issues/new', label: "New Issue" = render 'shared/issuable/filter', type: :issues diff --git a/app/views/groups/new.html.haml b/app/views/groups/new.html.haml index 4bc31cabea..30ab8aeba1 100644 --- a/app/views/groups/new.html.haml +++ b/app/views/groups/new.html.haml @@ -17,6 +17,8 @@ .col-sm-10 = render 'shared/choose_group_avatar_button', f: f + = render 'shared/visibility_level', f: f, visibility_level: default_group_visibility, can_change_visibility_level: true, form_model: @group + .form-group .col-sm-offset-2.col-sm-10 = render 'shared/group_tips' diff --git a/app/views/groups/show.html.haml b/app/views/groups/show.html.haml index 23a34ac36d..3d16ecb097 100644 --- a/app/views/groups/show.html.haml +++ b/app/views/groups/show.html.haml @@ -1,8 +1,5 @@ - @no_container = true -- unless can?(current_user, :read_group, @group) - - @disable_search_panel = true - = content_for :meta_tags do - if current_user = auto_discovery_link_tag(:atom, group_url(@group, format: :atom, private_token: current_user.private_token), title: "#{@group.name} activity") @@ -18,7 +15,10 @@ = link_to group_icon(@group), target: '_blank' do = image_tag group_icon(@group), class: "avatar group-avatar s90" .cover-title - = @group.name + %h1 + = @group.name + %span.visibility-icon.has-tooltip{ data: { container: 'body' }, title: visibility_icon_description(@group) } + = visibility_level_icon(@group.visibility_level, fw: false) .cover-desc.username @#{@group.path} @@ -27,34 +27,29 @@ .cover-desc.description = markdown(@group.description, pipeline: :description) -- if can?(current_user, :read_group, @group) - %div{ class: container_class } - .top-area - %ul.nav-links - %li.active - = link_to "#projects", 'data-toggle' => 'tab' do - All Projects - - if @shared_projects.present? - %li - = link_to "#shared", 'data-toggle' => 'tab' do - Shared Projects - .nav-controls - = form_tag request.original_url, method: :get, class: 'project-filter-form', id: 'project-filter-form' do |f| - = search_field_tag :filter_projects, nil, placeholder: 'Filter by name', class: 'projects-list-filter form-control', spellcheck: false - = render 'shared/projects/dropdown' - - if can? current_user, :create_projects, @group - = link_to new_project_path(namespace_id: @group.id), class: 'btn btn-new pull-right' do - = icon('plus') - New Project - - .tab-content - .tab-pane.active#projects - = render "projects", projects: @projects - +%div{ class: container_class } + .top-area + %ul.nav-links + %li.active + = link_to "#projects", 'data-toggle' => 'tab' do + All Projects - if @shared_projects.present? - .tab-pane#shared - = render "shared_projects", projects: @shared_projects + %li + = link_to "#shared", 'data-toggle' => 'tab' do + Shared Projects + .nav-controls + = form_tag request.original_url, method: :get, class: 'project-filter-form', id: 'project-filter-form' do |f| + = search_field_tag :filter_projects, nil, placeholder: 'Filter by name', class: 'projects-list-filter form-control', spellcheck: false + = render 'shared/projects/dropdown' + - if can? current_user, :create_projects, @group + = link_to new_project_path(namespace_id: @group.id), class: 'btn btn-new pull-right' do + = icon('plus') + New Project -- else - %p.nav-links.no-top - No projects to show + .tab-content + .tab-pane.active#projects + = render "projects", projects: @projects + + - if @shared_projects.present? + .tab-pane#shared + = render "shared_projects", projects: @shared_projects diff --git a/app/views/layouts/header/_default.html.haml b/app/views/layouts/header/_default.html.haml index f3090b9670..0f3b811937 100644 --- a/app/views/layouts/header/_default.html.haml +++ b/app/views/layouts/header/_default.html.haml @@ -6,10 +6,9 @@ = icon('bars') .navbar-collapse.collapse - %ul.nav.navbar-nav.pull-right - - unless @disable_search_panel - %li.hidden-sm.hidden-xs - = render 'layouts/search' + %ul.nav.navbar-nav + %li.hidden-sm.hidden-xs + = render 'layouts/search' %li.visible-sm.visible-xs = link_to search_path, title: 'Search', data: {toggle: 'tooltip', placement: 'bottom', container: 'body'} do = icon('search') @@ -39,8 +38,9 @@ = link_to destroy_user_session_path, class: 'logout', method: :delete, title: 'Sign out', data: {toggle: 'tooltip', placement: 'bottom', container: 'body'} do = icon('sign-out') - else - .pull-right - = link_to "Sign in", new_session_path(:user, redirect_to_referer: 'yes'), class: 'btn btn-sign-in btn-success' + %li + %div + = link_to "Sign in", new_session_path(:user, redirect_to_referer: 'yes'), class: 'btn btn-sign-in btn-success' %h1.title= title diff --git a/app/views/layouts/nav/_dashboard.html.haml b/app/views/layouts/nav/_dashboard.html.haml index db0cf39392..4a0069f18f 100644 --- a/app/views/layouts/nav/_dashboard.html.haml +++ b/app/views/layouts/nav/_dashboard.html.haml @@ -1,7 +1,7 @@ %ul.nav.nav-sidebar = nav_link(path: ['root#index', 'projects#trending', 'projects#starred', 'dashboard/projects#index'], html_options: {class: 'home'}) do = link_to dashboard_projects_path, title: 'Projects' do - = icon('home fw') + = icon('bookmark fw') %span Projects = nav_link(controller: :todos) do diff --git a/app/views/layouts/nav/_explore.html.haml b/app/views/layouts/nav/_explore.html.haml index 48039ca291..f08c5edf99 100644 --- a/app/views/layouts/nav/_explore.html.haml +++ b/app/views/layouts/nav/_explore.html.haml @@ -1,7 +1,7 @@ %ul.nav.nav-sidebar = nav_link(path: ['dashboard#show', 'root#show', 'projects#trending', 'projects#starred', 'projects#index'], html_options: {class: 'home'}) do = link_to explore_root_path, title: 'Projects' do - = icon('home fw') + = icon('bookmark fw') %span Projects = nav_link(controller: :groups) do diff --git a/app/views/layouts/nav/_group.html.haml b/app/views/layouts/nav/_group.html.haml index 59411ae1da..55940741dc 100644 --- a/app/views/layouts/nav/_group.html.haml +++ b/app/views/layouts/nav/_group.html.haml @@ -12,40 +12,38 @@ = icon('group fw') %span Group - - if can?(current_user, :read_group, @group) - = nav_link(path: 'groups#activity') do - = link_to activity_group_path(@group), title: 'Activity' do - = icon('dashboard fw') + = nav_link(path: 'groups#activity') do + = link_to activity_group_path(@group), title: 'Activity' do + = icon('dashboard fw') + %span + Activity + = nav_link(controller: [:group, :milestones]) do + = link_to group_milestones_path(@group), title: 'Milestones' do + = icon('clock-o fw') + %span + Milestones + = nav_link(path: 'groups#issues') do + = link_to issues_group_path(@group), title: 'Issues' do + = icon('exclamation-circle fw') + %span + Issues + - issues = IssuesFinder.new(current_user, group_id: @group.id, state: 'opened').execute + %span.count= number_with_delimiter(issues.count) + = nav_link(path: 'groups#merge_requests') do + = link_to merge_requests_group_path(@group), title: 'Merge Requests' do + = icon('tasks fw') + %span + Merge Requests + - merge_requests = MergeRequestsFinder.new(current_user, group_id: @group.id, state: 'opened').execute + %span.count= number_with_delimiter(merge_requests.count) + = nav_link(controller: [:group_members]) do + = link_to group_group_members_path(@group), title: 'Members' do + = icon('users fw') + %span + Members + - if can?(current_user, :admin_group, @group) + = nav_link(html_options: { class: "separate-item" }) do + = link_to edit_group_path(@group), title: 'Settings' do + = icon ('cogs fw') %span - Activity - - if current_user - = nav_link(controller: [:group, :milestones]) do - = link_to group_milestones_path(@group), title: 'Milestones' do - = icon('clock-o fw') - %span - Milestones - = nav_link(path: 'groups#issues') do - = link_to issues_group_path(@group), title: 'Issues' do - = icon('exclamation-circle fw') - %span - Issues - - if current_user - %span.count= number_with_delimiter(Issue.opened.of_group(@group).count) - = nav_link(path: 'groups#merge_requests') do - = link_to merge_requests_group_path(@group), title: 'Merge Requests' do - = icon('tasks fw') - %span - Merge Requests - - if current_user - %span.count= number_with_delimiter(MergeRequest.opened.of_group(@group).count) - = nav_link(controller: [:group_members]) do - = link_to group_group_members_path(@group), title: 'Members' do - = icon('users fw') - %span - Members - - if can?(current_user, :admin_group, @group) - = nav_link(html_options: { class: "separate-item" }) do - = link_to edit_group_path(@group), title: 'Settings' do - = icon ('cogs fw') - %span - Settings + Settings diff --git a/app/views/profiles/keys/_key.html.haml b/app/views/profiles/keys/_key.html.haml index 25e9e8ff00..4dbaa662b6 100644 --- a/app/views/profiles/keys/_key.html.haml +++ b/app/views/profiles/keys/_key.html.haml @@ -8,7 +8,7 @@ = key.fingerprint .pull-right %span.key-created-at - created #{time_ago_with_tooltip(key.created_at)} ago + created #{time_ago_with_tooltip(key.created_at)} = link_to path_to_key(key, is_admin), data: { confirm: 'Are you sure?'}, method: :delete, class: "btn btn-transparent prepend-left-10" do %span.sr-only Remove = icon('trash') diff --git a/app/views/profiles/show.html.haml b/app/views/profiles/show.html.haml index cd582ba706..dcb3be9585 100644 --- a/app/views/profiles/show.html.haml +++ b/app/views/profiles/show.html.haml @@ -26,7 +26,7 @@ %a.btn.js-choose-user-avatar-button Browse file... %span.avatar-file-name.prepend-left-default.js-avatar-filename No file chosen - = f.file_field :avatar, class: "js-user-avatar-input hidden" + = f.file_field :avatar, class: "js-user-avatar-input hidden", accept: "image/*" .help-block The maximum file size allowed is 200KB. - if @user.avatar? @@ -94,3 +94,25 @@ .prepend-top-default.append-bottom-default = f.submit 'Update profile settings', class: "btn btn-success" = link_to "Cancel", user_path(current_user), class: "btn btn-cancel" + +.modal.modal-profile-crop + .modal-dialog + .modal-content + .modal-header + %button.close{:type => "button", :'data-dismiss' => "modal"} + %span + × + %h4.modal-title + Position and size your new avatar + .modal-body + .profile-crop-image-container + %img.modal-profile-crop-image + .crop-controls + .btn-group + %button.btn.btn-primary{ data: { method: "zoom", option: "0.1" } } + %span.fa.fa-search-plus + %button.btn.btn-primary{ data: { method: "zoom", option: "-0.1" } } + %span.fa.fa-search-minus + .modal-footer + %button.btn.btn-primary.js-upload-user-avatar{:type => "button"} + Set new profile picture diff --git a/app/views/projects/_home_panel.html.haml b/app/views/projects/_home_panel.html.haml index b45df44f27..9b5de17dd3 100644 --- a/app/views/projects/_home_panel.html.haml +++ b/app/views/projects/_home_panel.html.haml @@ -2,21 +2,21 @@ .project-home-panel.cover-block.clearfix{:class => ("empty-project" if empty_repo)} .project-identicon-holder = project_icon(@project, alt: '', class: 'project-avatar avatar s90') - .project-home-desc + .cover-title.project-home-desc %h1 = @project.name - %span.visibility-icon.has_tooltip{data: { container: 'body' }, - title: "#{visibility_level_label(@project.visibility_level)} - #{project_visibility_level_description(@project.visibility_level)}"} + %span.visibility-icon.has-tooltip{data: { container: 'body' }, title: visibility_icon_description(@project)} = visibility_level_icon(@project.visibility_level, fw: false) - - if @project.description.present? + - if @project.description.present? + .cover-desc.project-home-desc = markdown(@project.description, pipeline: :description) - - if forked_from_project = @project.forked_from_project - %p - Forked from - = link_to project_path(forked_from_project) do - = forked_from_project.namespace.try(:name) + - if forked_from_project = @project.forked_from_project + .cover-desc + Forked from + = link_to project_path(forked_from_project) do + = forked_from_project.namespace.try(:name) .cover-controls - if current_user diff --git a/app/views/projects/branches/_branch.html.haml b/app/views/projects/branches/_branch.html.haml index 76a823d382..57e507e68c 100644 --- a/app/views/projects/branches/_branch.html.haml +++ b/app/views/projects/branches/_branch.html.haml @@ -11,7 +11,7 @@ - if branch.name == @repository.root_ref %span.label.label-primary default - elsif @repository.merged_to_root_ref? branch.name - %span.label.label-info.has_tooltip(title="Merged into #{@repository.root_ref}") + %span.label.label-info.has-tooltip(title="Merged into #{@repository.root_ref}") merged - if @project.protected_branch? branch.name @@ -30,7 +30,7 @@ Compare - if can_remove_branch?(@project, branch.name) - = link_to namespace_project_branch_path(@project.namespace, @project, branch.name), class: 'btn btn-grouped btn-xs btn-remove remove-row has_tooltip', title: "Delete branch", method: :delete, data: { confirm: "Deleting the '#{branch.name}' branch cannot be undone. Are you sure?", container: 'body' }, remote: true do + = link_to namespace_project_branch_path(@project.namespace, @project, branch.name), class: 'btn btn-grouped btn-xs btn-remove remove-row has-tooltip', title: "Delete branch", method: :delete, data: { confirm: "Deleting the '#{branch.name}' branch cannot be undone. Are you sure?", container: 'body' }, remote: true do = icon("trash-o") - if branch.name != @repository.root_ref diff --git a/app/views/projects/branches/index.html.haml b/app/views/projects/branches/index.html.haml index 7afea5a504..88266e2123 100644 --- a/app/views/projects/branches/index.html.haml +++ b/app/views/projects/branches/index.html.haml @@ -16,7 +16,7 @@ - else Name %b.caret - %ul.dropdown-menu + %ul.dropdown-menu.dropdown-menu-align-right %li = link_to namespace_project_branches_path(sort: nil) do Name diff --git a/app/views/projects/buttons/_download.html.haml b/app/views/projects/buttons/_download.html.haml index 6a60cfeff7..58f43ecb5d 100644 --- a/app/views/projects/buttons/_download.html.haml +++ b/app/views/projects/buttons/_download.html.haml @@ -1,4 +1,4 @@ - unless @project.empty_repo? - if can? current_user, :download_code, @project - = link_to archive_namespace_project_repository_path(@project.namespace, @project, ref: @ref, format: 'zip'), class: 'btn has_tooltip', data: {container: "body"}, rel: 'nofollow', title: "Download ZIP" do + = link_to archive_namespace_project_repository_path(@project.namespace, @project, ref: @ref, format: 'zip'), class: 'btn has-tooltip', data: {container: "body"}, rel: 'nofollow', title: "Download ZIP" do = icon('download') diff --git a/app/views/projects/buttons/_fork.html.haml b/app/views/projects/buttons/_fork.html.haml index 133531887a..88cbb7c03c 100644 --- a/app/views/projects/buttons/_fork.html.haml +++ b/app/views/projects/buttons/_fork.html.haml @@ -1,7 +1,7 @@ - unless @project.empty_repo? - if current_user && can?(current_user, :fork_project, @project) - if current_user.already_forked?(@project) && current_user.manageable_namespaces.size < 2 - = link_to namespace_project_path(current_user, current_user.fork_of(@project)), title: 'Go to your fork', class: 'btn has_tooltip' do + = link_to namespace_project_path(current_user, current_user.fork_of(@project)), title: 'Go to your fork', class: 'btn has-tooltip' do = icon('code-fork fw') Fork %div.count-with-arrow @@ -9,7 +9,7 @@ %span.count = @project.forks_count - else - = link_to new_namespace_project_fork_path(@project.namespace, @project), title: "Fork project", class: 'btn has_tooltip' do + = link_to new_namespace_project_fork_path(@project.namespace, @project), title: "Fork project", class: 'btn has-tooltip' do = icon('code-fork fw') Fork %div.count-with-arrow diff --git a/app/views/projects/buttons/_notifications.html.haml b/app/views/projects/buttons/_notifications.html.haml index 3e83ec3912..a3786c35a1 100644 --- a/app/views/projects/buttons/_notifications.html.haml +++ b/app/views/projects/buttons/_notifications.html.haml @@ -14,7 +14,7 @@ = notification_list_item(level, @membership) - when GroupMember - .btn.disabled.notifications-btn.has_tooltip{title: "To change the notification level, you need to be a member of the project itself, not only its group."} + .btn.disabled.notifications-btn.has-tooltip{title: "To change the notification level, you need to be a member of the project itself, not only its group."} = icon('bell') = notification_label(@membership) = icon('angle-down') diff --git a/app/views/projects/buttons/_star.html.haml b/app/views/projects/buttons/_star.html.haml index 21ba426aaa..02dbb2985a 100644 --- a/app/views/projects/buttons/_star.html.haml +++ b/app/views/projects/buttons/_star.html.haml @@ -1,5 +1,5 @@ - if current_user - = link_to toggle_star_namespace_project_path(@project.namespace, @project), class: 'btn star-btn toggle-star has_tooltip', method: :post, remote: true, title: "Star project" do + = link_to toggle_star_namespace_project_path(@project.namespace, @project), class: 'btn star-btn toggle-star has-tooltip', method: :post, remote: true, title: "Star project" do - if current_user.starred?(@project) = icon('star fw') %span.starred Unstar @@ -12,7 +12,7 @@ = @project.star_count - else - = link_to new_user_session_path, class: 'btn has_tooltip star-btn', title: 'You must sign in to star a project' do + = link_to new_user_session_path, class: 'btn has-tooltip star-btn', title: 'You must sign in to star a project' do = icon('star fw') Star %div.count-with-arrow diff --git a/app/views/projects/compare/_form.html.haml b/app/views/projects/compare/_form.html.haml index 4ab81f3635..dd590a4b8e 100644 --- a/app/views/projects/compare/_form.html.haml +++ b/app/views/projects/compare/_form.html.haml @@ -1,7 +1,7 @@ = form_tag namespace_project_compare_index_path(@project.namespace, @project), method: :post, class: 'form-inline js-requires-input' do .clearfix - if params[:to] && params[:from] - = link_to 'switch', {from: params[:to], to: params[:from]}, {class: 'commits-compare-switch has_tooltip', title: 'Switch base of comparison'} + = link_to 'switch', {from: params[:to], to: params[:from]}, {class: 'commits-compare-switch has-tooltip', title: 'Switch base of comparison'} .form-group .input-group.inline-input-group %span.input-group-addon from diff --git a/app/views/projects/diffs/_file.html.haml b/app/views/projects/diffs/_file.html.haml index 3898bb202c..698ed02ea0 100644 --- a/app/views/projects/diffs/_file.html.haml +++ b/app/views/projects/diffs/_file.html.haml @@ -28,7 +28,7 @@ .file-actions.hidden-xs - if blob_text_viewable?(blob) - = link_to '#', class: 'js-toggle-diff-comments btn active has_tooltip', title: "Toggle comments for this file" do + = link_to '#', class: 'js-toggle-diff-comments btn active has-tooltip', title: "Toggle comments for this file" do = icon('comments') \ diff --git a/app/views/projects/forks/new.html.haml b/app/views/projects/forks/new.html.haml index edabc2d3b4..73a7fc0e1a 100644 --- a/app/views/projects/forks/new.html.haml +++ b/app/views/projects/forks/new.html.haml @@ -12,7 +12,7 @@ .col-md-2.col-sm-3 - if fork = namespace.find_fork_of(@project) .fork-thumbnail - = link_to project_path(fork), title: "Visit project fork", class: 'has_tooltip' do + = link_to project_path(fork), title: "Visit project fork", class: 'has-tooltip' do = image_tag namespace_icon(namespace, 100) .caption %strong @@ -22,7 +22,7 @@ - else .fork-thumbnail - = link_to namespace_project_forks_path(@project.namespace, @project, namespace_key: namespace.id), title: "Fork here", method: "POST", class: 'has_tooltip' do + = link_to namespace_project_forks_path(@project.namespace, @project, namespace_key: namespace.id), title: "Fork here", method: "POST", class: 'has-tooltip' do = image_tag namespace_icon(namespace, 100) .caption %strong diff --git a/app/views/projects/issues/index.html.haml b/app/views/projects/issues/index.html.haml index fde9304c0f..efa7642b2d 100644 --- a/app/views/projects/issues/index.html.haml +++ b/app/views/projects/issues/index.html.haml @@ -11,6 +11,8 @@ - if current_user = link_to namespace_project_issues_path(@project.namespace, @project, :atom, { private_token: current_user.private_token }), class: 'btn append-right-10' do = icon('rss') + %span.icon-label + Subscribe = render 'shared/issuable/search_form', path: namespace_project_issues_path(@project.namespace, @project) - if can? current_user, :create_issue, @project = link_to new_namespace_project_issue_path(@project.namespace, @project, issue: { assignee_id: @issuable_finder.assignee.try(:id), milestone_id: @issuable_finder.milestones.try(:first).try(:id) }), class: "btn btn-new", title: "New Issue", id: "new_issue_link" do diff --git a/app/views/projects/issues/show.html.haml b/app/views/projects/issues/show.html.haml index 52df3de8a2..6fa059cbe6 100644 --- a/app/views/projects/issues/show.html.haml +++ b/app/views/projects/issues/show.html.haml @@ -45,7 +45,6 @@ - if can?(current_user, :update_issue, @issue) = link_to 'Reopen issue', issue_path(@issue, issue: {state_event: :reopen}, status_only: true, format: 'json'), data: {no_turbolink: true}, class: "btn btn-nr btn-grouped btn-reopen #{issue_button_visibility(@issue, false)}", title: 'Reopen issue' = link_to 'Close issue', issue_path(@issue, issue: {state_event: :close}, status_only: true, format: 'json'), data: {no_turbolink: true}, class: "btn btn-nr btn-grouped btn-close #{issue_button_visibility(@issue, true)}", title: 'Close issue' - = link_to edit_namespace_project_issue_path(@project.namespace, @project, @issue), class: 'btn btn-nr btn-grouped issuable-edit' do = icon('pencil-square-o') Edit diff --git a/app/views/projects/labels/_label.html.haml b/app/views/projects/labels/_label.html.haml index 4927d239c1..0612863296 100644 --- a/app/views/projects/labels/_label.html.haml +++ b/app/views/projects/labels/_label.html.haml @@ -8,7 +8,7 @@ %strong.append-right-20 = link_to_label(label) do - = pluralize label.open_issues_count, 'open issue' + = pluralize label.open_issues_count(current_user), 'open issue' - if current_user .label-subscription{data: {url: toggle_subscription_namespace_project_label_path(@project.namespace, @project, label)}} diff --git a/app/views/projects/merge_requests/_merge_request.html.haml b/app/views/projects/merge_requests/_merge_request.html.haml index 13d0cbdde1..391193eed6 100644 --- a/app/views/projects/merge_requests/_merge_request.html.haml +++ b/app/views/projects/merge_requests/_merge_request.html.haml @@ -17,7 +17,7 @@ - if merge_request.open? && merge_request.broken? %li - = link_to merge_request_path(merge_request), class: "has_tooltip", title: "Cannot be merged automatically", data: { container: 'body' } do + = link_to merge_request_path(merge_request), class: "has-tooltip", title: "Cannot be merged automatically", data: { container: 'body' } do = icon('exclamation-triangle') - if merge_request.assignee diff --git a/app/views/projects/merge_requests/show/_mr_title.html.haml b/app/views/projects/merge_requests/show/_mr_title.html.haml index eeb605e2dc..ab4b1f14be 100644 --- a/app/views/projects/merge_requests/show/_mr_title.html.haml +++ b/app/views/projects/merge_requests/show/_mr_title.html.haml @@ -29,7 +29,7 @@ - if @merge_request.open? = link_to 'Close', merge_request_path(@merge_request, merge_request: { state_event: :close }), method: :put, class: 'btn btn-nr btn-grouped btn-close', title: 'Close merge request' = link_to edit_namespace_project_merge_request_path(@project.namespace, @project, @merge_request), class: 'btn btn-nr btn-grouped issuable-edit', id: 'edit_merge_request' do - %i.fa.fa-pencil-square-o + = icon('pencil-square-o') Edit - if @merge_request.closed? = link_to 'Reopen', merge_request_path(@merge_request, merge_request: {state_event: :reopen }), method: :put, class: 'btn btn-nr btn-grouped btn-reopen reopen-mr-link', title: 'Reopen merge request' diff --git a/app/views/projects/tags/_download.html.haml b/app/views/projects/tags/_download.html.haml index 667057ef2d..093d1d1bb0 100644 --- a/app/views/projects/tags/_download.html.haml +++ b/app/views/projects/tags/_download.html.haml @@ -6,7 +6,7 @@ %span.caret %span.sr-only Select Archive Format - %ul.col-xs-10.dropdown-menu{ role: 'menu' } + %ul.dropdown-menu.dropdown-menu-align-right{ role: 'menu' } %li = link_to archive_namespace_project_repository_path(project.namespace, project, ref: ref, format: 'zip'), rel: 'nofollow' do %i.fa.fa-download diff --git a/app/views/projects/tags/_tag.html.haml b/app/views/projects/tags/_tag.html.haml index 399782273d..dbc35c16fe 100644 --- a/app/views/projects/tags/_tag.html.haml +++ b/app/views/projects/tags/_tag.html.haml @@ -15,11 +15,11 @@ = render 'projects/tags/download', ref: tag.name, project: @project - if can?(current_user, :push_code, @project) - = link_to edit_namespace_project_tag_release_path(@project.namespace, @project, tag.name), class: 'btn-grouped btn has_tooltip', title: "Edit release notes" do + = link_to edit_namespace_project_tag_release_path(@project.namespace, @project, tag.name), class: 'btn-grouped btn has-tooltip', title: "Edit release notes" do = icon("pencil") - if can?(current_user, :admin_project, @project) - = link_to namespace_project_tag_path(@project.namespace, @project, tag.name), class: 'btn btn-grouped btn-xs btn-remove remove-row has_tooltip', title: "Delete tag", method: :delete, data: { confirm: "Deleting the '#{tag.name}' tag cannot be undone. Are you sure?", container: 'body' }, remote: true do + = link_to namespace_project_tag_path(@project.namespace, @project, tag.name), class: 'btn btn-grouped btn-xs btn-remove remove-row has-tooltip', title: "Delete tag", method: :delete, data: { confirm: "Deleting the '#{tag.name}' tag cannot be undone. Are you sure?", container: 'body' }, remote: true do = icon("trash-o") - if commit diff --git a/app/views/projects/tags/show.html.haml b/app/views/projects/tags/show.html.haml index 8c7f93f93b..1dc9b799a9 100644 --- a/app/views/projects/tags/show.html.haml +++ b/app/views/projects/tags/show.html.haml @@ -5,17 +5,17 @@ .gray-content-block .pull-right - if can?(current_user, :push_code, @project) - = link_to edit_namespace_project_tag_release_path(@project.namespace, @project, @tag.name), class: 'btn-grouped btn has_tooltip', title: 'Edit release notes' do + = link_to edit_namespace_project_tag_release_path(@project.namespace, @project, @tag.name), class: 'btn-grouped btn has-tooltip', title: 'Edit release notes' do = icon("pencil") - = link_to namespace_project_tree_path(@project.namespace, @project, @tag.name), class: 'btn btn-grouped has_tooltip', title: 'Browse files' do + = link_to namespace_project_tree_path(@project.namespace, @project, @tag.name), class: 'btn btn-grouped has-tooltip', title: 'Browse files' do = icon('files-o') - = link_to namespace_project_commits_path(@project.namespace, @project, @tag.name), class: 'btn btn-grouped has_tooltip', title: 'Browse commits' do + = link_to namespace_project_commits_path(@project.namespace, @project, @tag.name), class: 'btn btn-grouped has-tooltip', title: 'Browse commits' do = icon('history') - if can? current_user, :download_code, @project = render 'projects/tags/download', ref: @tag.name, project: @project - if can?(current_user, :admin_project, @project) .pull-right - = link_to namespace_project_tag_path(@project.namespace, @project, @tag.name), class: 'btn btn-remove remove-row grouped has_tooltip', title: "Delete tag", method: :delete, data: { confirm: "Deleting the '#{@tag.name}' tag cannot be undone. Are you sure?" } do + = link_to namespace_project_tag_path(@project.namespace, @project, @tag.name), class: 'btn btn-remove remove-row grouped has-tooltip', title: "Delete tag", method: :delete, data: { confirm: "Deleting the '#{@tag.name}' tag cannot be undone. Are you sure?" } do %i.fa.fa-trash-o .title %span.item-title= @tag.name diff --git a/app/views/projects/tree/_tree_header.html.haml b/app/views/projects/tree/_tree_header.html.haml index 3eb626e6dc..ba69569b1e 100644 --- a/app/views/projects/tree/_tree_header.html.haml +++ b/app/views/projects/tree/_tree_header.html.haml @@ -15,7 +15,7 @@ - if current_user %li - if !on_top_of_branch? - %span.btn.btn-sm.add-to-tree.disabled.has_tooltip{title: "You can only add files when you are on a branch", data: { container: 'body' }} + %span.btn.btn-sm.add-to-tree.disabled.has-tooltip{title: "You can only add files when you are on a branch", data: { container: 'body' }} = icon('plus') - else %span.dropdown diff --git a/app/views/search/results/_milestone.html.haml b/app/views/search/results/_milestone.html.haml index e0b18733d7..b31595d8d1 100644 --- a/app/views/search/results/_milestone.html.haml +++ b/app/views/search/results/_milestone.html.haml @@ -6,4 +6,4 @@ - if milestone.description.present? .description.term = preserve do - = search_md_sanitize(markdown(milestone.description)) \ No newline at end of file + = search_md_sanitize(markdown(milestone.description)) diff --git a/app/views/shared/_group_tips.html.haml b/app/views/shared/_group_tips.html.haml index e5cf783beb..46e4340511 100644 --- a/app/views/shared/_group_tips.html.haml +++ b/app/views/shared/_group_tips.html.haml @@ -1,6 +1,5 @@ %ul %li A group is a collection of several projects - %li Groups are private by default %li Members of a group may only view projects they have permission to access %li Group project URLs are prefixed with the group namespace %li Existing projects may be moved into a group diff --git a/app/views/shared/groups/_group.html.haml b/app/views/shared/groups/_group.html.haml index f172350f5f..40c6eb9be4 100644 --- a/app/views/shared/groups/_group.html.haml +++ b/app/views/shared/groups/_group.html.haml @@ -14,13 +14,16 @@ .stats %span - = icon('home') + = icon('bookmark') = number_with_delimiter(group.projects.count) %span = icon('users') = number_with_delimiter(group.users.count) + %span.visibility-icon.has-tooltip{data: { container: 'body', placement: 'left' }, title: visibility_icon_description(group)} + = visibility_level_icon(group.visibility_level, fw: false) + = image_tag group_icon(group), class: "avatar s40 hidden-xs" .title = link_to group, class: 'group-name' do diff --git a/app/views/shared/issuable/_filter.html.haml b/app/views/shared/issuable/_filter.html.haml index ac20f7d1f7..f91ff0e369 100644 --- a/app/views/shared/issuable/_filter.html.haml +++ b/app/views/shared/issuable/_filter.html.haml @@ -31,18 +31,18 @@ .issues_bulk_update.hide = form_tag bulk_update_namespace_project_issues_path(@project.namespace, @project), method: :post do .filter-item.inline - = dropdown_tag("Status", options: { toggle_class: "js-issue-status", title: "Change status", dropdown_class: "dropdown-menu-selectable", data: { field_name: "update[state_event]" } } ) do + = dropdown_tag("Status", options: { toggle_class: "js-issue-status", title: "Change status", dropdown_class: "dropdown-menu-status dropdown-menu-selectable", data: { field_name: "update[state_event]" } } ) do %ul %li %a{href: "#", data: {id: "reopen"}} Open %li %a{href: "#", data: {id: "close"}} Closed .filter-item.inline - = dropdown_tag("Assignee", options: { toggle_class: "js-user-search", title: "Assign to", filter: true, dropdown_class: "dropdown-menu-user dropdown-menu-selectable", + = dropdown_tag("Assignee", options: { toggle_class: "js-user-search js-update-assignee", title: "Assign to", filter: true, dropdown_class: "dropdown-menu-user dropdown-menu-selectable", placeholder: "Search authors", data: { first_user: (current_user.username if current_user), null_user: true, current_user: true, project_id: @project.id, field_name: "update[assignee_id]" } }) .filter-item.inline - = dropdown_tag("Milestone", options: { title: "Assign milestone", toggle_class: 'js-milestone-select', filter: true, dropdown_class: "dropdown-menu-selectable", - placeholder: "Search milestones", data: { show_no: true, field_name: "update[milestone_id]", project_id: @project.id, milestones: namespace_project_milestones_path(@project.namespace, @project, :js), use_id: true } }) + = dropdown_tag("Milestone", options: { title: "Assign milestone", toggle_class: 'js-milestone-select', filter: true, dropdown_class: "dropdown-menu-selectable dropdown-menu-milestone", + placeholder: "Search milestones", data: { show_no: true, field_name: "update[milestone_id]", project_id: @project.id, milestones: namespace_project_milestones_path(@project.namespace, @project, :json), use_id: true } }) = hidden_field_tag 'update[issues_ids]', [] = hidden_field_tag :state_event, params[:state_event] .filter-item.inline diff --git a/app/views/shared/issuable/_form.html.haml b/app/views/shared/issuable/_form.html.haml index 1740b128ee..b01a36265f 100644 --- a/app/views/shared/issuable/_form.html.haml +++ b/app/views/shared/issuable/_form.html.haml @@ -127,7 +127,12 @@ for this project. - if issuable.new_record? - - cancel_project = issuable.source_project + = link_to 'Cancel', namespace_project_issues_path(@project.namespace, @project), class: 'btn btn-cancel' - else - - cancel_project = issuable.project - = link_to 'Cancel', [cancel_project.namespace.becomes(Namespace), cancel_project, issuable], class: 'btn btn-cancel' + .pull-right + - if current_user.can?(:"destroy_#{issuable.to_ability_name}", @project) + = link_to polymorphic_path([@project.namespace.becomes(Namespace), @project, issuable]), data: { confirm: "#{issuable.class.name.titleize} will be removed! Are you sure?" }, + method: :delete, class: 'btn btn-grouped' do + = icon('trash-o') + Delete + = link_to 'Cancel', namespace_project_issue_path(@project.namespace, @project, issuable), class: 'btn btn-grouped btn-cancel' diff --git a/app/views/shared/issuable/_label_dropdown.html.haml b/app/views/shared/issuable/_label_dropdown.html.haml index 8761731518..006a34a11e 100644 --- a/app/views/shared/issuable/_label_dropdown.html.haml +++ b/app/views/shared/issuable/_label_dropdown.html.haml @@ -24,16 +24,21 @@ - else View labels - if can? current_user, :admin_label, @project and @project - .dropdown-page-two + .dropdown-page-two.dropdown-new-label = dropdown_title("Create new label", back: true) = dropdown_content do - %input#new_label_color{type: "hidden"} + .dropdown-labels-error.js-label-error %input#new_label_name.dropdown-input-field{type: "text", placeholder: "Name new label"} - .dropdown-label-color-preview.js-dropdown-label-color-preview .suggest-colors.suggest-colors-dropdown - suggested_colors.each do |color| = link_to '#', style: "background-color: #{color}", data: { color: color } do   - %button.btn.btn-primary.js-new-label-btn{type: "button"} - Create + .dropdown-label-color-input + .dropdown-label-color-preview.js-dropdown-label-color-preview + %input#new_label_color.dropdown-input-field{ type: "text" } + .clearfix + %button.btn.btn-primary.pull-left.js-new-label-btn{type: "button"} + Create + %button.btn.btn-default.pull-right.js-cancel-label-btn{type: "button"} + Cancel = dropdown_loading diff --git a/app/views/shared/issuable/_participants.html.haml b/app/views/shared/issuable/_participants.html.haml index 3fb409ff72..33a9a49485 100644 --- a/app/views/shared/issuable/_participants.html.haml +++ b/app/views/shared/issuable/_participants.html.haml @@ -17,4 +17,4 @@ %a.js-participants-more{href: "#", data: {original_text: "+ #{participants_size - 7} more", less_text: "- show less"}} + #{participants_extra} more :javascript - Issue.prototype.PARTICIPANTS_ROW_COUNT = #{participants_row}; + IssuableContext.prototype.PARTICIPANTS_ROW_COUNT = #{participants_row}; diff --git a/app/views/shared/issuable/_sidebar.html.haml b/app/views/shared/issuable/_sidebar.html.haml index 2b95b19fac..5b2772de3f 100644 --- a/app/views/shared/issuable/_sidebar.html.haml +++ b/app/views/shared/issuable/_sidebar.html.haml @@ -33,11 +33,11 @@ .value.bold.hide-collapsed - if issuable.assignee = link_to_member(@project, issuable.assignee, size: 32) do + - if issuable.instance_of?(MergeRequest) && !issuable.can_be_merged_by?(issuable.assignee) + %span.pull-right.cannot-be-merged{ data: { toggle: 'tooltip', placement: 'left' }, title: 'Not allowed to merge' } + = icon('exclamation-triangle') %span.username = issuable.assignee.to_reference - - if issuable.instance_of?(MergeRequest) && !issuable.can_be_merged_by?(issuable.assignee) - %a.pull-right.cannot-be-merged{href: '#', data: {toggle: 'tooltip'}, title: 'Not allowed to merge'} - = icon('exclamation-triangle') - else .light None diff --git a/app/views/shared/milestones/_issuable.html.haml b/app/views/shared/milestones/_issuable.html.haml index 8588809672..e1127b2311 100644 --- a/app/views/shared/milestones/_issuable.html.haml +++ b/app/views/shared/milestones/_issuable.html.haml @@ -23,5 +23,5 @@ - if assignee = link_to polymorphic_path(base_url_args, { milestone_title: @milestone.title, assignee_id: issuable.assignee_id, state: 'all' }), - class: 'has_tooltip', data: { 'original-title' => "Assigned to #{sanitize(assignee.name)}", container: 'body' } do + class: 'has-tooltip', data: { 'original-title' => "Assigned to #{sanitize(assignee.name)}", container: 'body' } do - image_tag(avatar_icon(issuable.assignee, 16), class: "avatar s16", alt: '') diff --git a/app/views/shared/projects/_project.html.haml b/app/views/shared/projects/_project.html.haml index 872d2bdf46..53ff8959bc 100644 --- a/app/views/shared/projects/_project.html.haml +++ b/app/views/shared/projects/_project.html.haml @@ -27,8 +27,7 @@ %span = icon('star') = project.star_count - %span.visibility-icon.has_tooltip{data: { container: 'body', placement: 'left' }, - title: "#{visibility_level_label(project.visibility_level)} - #{project_visibility_level_description(project.visibility_level)}"} + %span.visibility-icon.has-tooltip{data: { container: 'body', placement: 'left' }, title: visibility_icon_description(project)} = visibility_level_icon(project.visibility_level, fw: false) .title diff --git a/app/views/shared/snippets/_header.html.haml b/app/views/shared/snippets/_header.html.haml index aa5acee9c1..3c445f6723 100644 --- a/app/views/shared/snippets/_header.html.haml +++ b/app/views/shared/snippets/_header.html.haml @@ -1,5 +1,5 @@ .detail-page-header - .snippet-box.has_tooltip{class: visibility_level_color(@snippet.visibility_level), title: snippet_visibility_level_description(@snippet.visibility_level, @snippet), data: { container: 'body' }} + .snippet-box.has-tooltip{class: visibility_level_color(@snippet.visibility_level), title: snippet_visibility_level_description(@snippet.visibility_level, @snippet), data: { container: 'body' }} = visibility_level_icon(@snippet.visibility_level, fw: false) = visibility_level_label(@snippet.visibility_level) %span.identifier diff --git a/app/views/votes/_votes_block.html.haml b/app/views/votes/_votes_block.html.haml index 20d2d5f317..0264722977 100644 --- a/app/views/votes/_votes_block.html.haml +++ b/app/views/votes/_votes_block.html.haml @@ -1,6 +1,6 @@ .awards.votes-block - awards_sort(votable.notes.awards.grouped_awards).each do |emoji, notes| - %button.btn.award-control.js-emoji-btn.has_tooltip{class: (note_active_class(notes, current_user)), title: emoji_author_list(notes, current_user), data: {placement: "top"}} + %button.btn.award-control.js-emoji-btn.has-tooltip{class: (note_active_class(notes, current_user)), title: emoji_author_list(notes, current_user), data: {placement: "top"}} = emoji_icon(emoji) %span.award-control-text.js-counter = notes.count diff --git a/config/routes.rb b/config/routes.rb index 561987322b..6bf22fb445 100644 --- a/config/routes.rb +++ b/config/routes.rb @@ -16,6 +16,18 @@ Rails.application.routes.draw do end end + # Make the built-in Rails routes available in development, otherwise they'd + # get swallowed by the `namespace/project` route matcher below. + # + # See https://git.io/va79N + if Rails.env.development? + get '/rails/mailers' => 'rails/mailers#index' + get '/rails/mailers/:path' => 'rails/mailers#preview' + get '/rails/info/properties' => 'rails/info#properties' + get '/rails/info/routes' => 'rails/info#routes' + get '/rails/info' => 'rails/info#index' + end + namespace :ci do # CI API Ci::API::API.logger Rails.logger @@ -351,11 +363,10 @@ Rails.application.routes.draw do get :issues get :merge_requests get :activity - get :labels - get :milestones scope module: :dashboard do resources :milestones, only: [:index, :show] + resources :labels, only: [:index] resources :groups, only: [:index] resources :snippets, only: [:index] @@ -613,7 +624,7 @@ Rails.application.routes.draw do end end - resources :merge_requests, constraints: { id: /\d+/ }, except: [:destroy] do + resources :merge_requests, constraints: { id: /\d+/ } do member do get :commits get :diffs @@ -684,7 +695,7 @@ Rails.application.routes.draw do end end - resources :issues, constraints: { id: /\d+/ }, except: [:destroy] do + resources :issues, constraints: { id: /\d+/ } do member do post :toggle_subscription end diff --git a/db/migrate/20160225090018_add_delete_at_to_issues.rb b/db/migrate/20160225090018_add_delete_at_to_issues.rb new file mode 100644 index 0000000000..3ddbef9297 --- /dev/null +++ b/db/migrate/20160225090018_add_delete_at_to_issues.rb @@ -0,0 +1,6 @@ +class AddDeleteAtToIssues < ActiveRecord::Migration + def change + add_column :issues, :deleted_at, :datetime + add_index :issues, :deleted_at + end +end diff --git a/db/migrate/20160225101956_add_delete_at_to_merge_requests.rb b/db/migrate/20160225101956_add_delete_at_to_merge_requests.rb new file mode 100644 index 0000000000..9d09105f17 --- /dev/null +++ b/db/migrate/20160225101956_add_delete_at_to_merge_requests.rb @@ -0,0 +1,6 @@ +class AddDeleteAtToMergeRequests < ActiveRecord::Migration + def change + add_column :merge_requests, :deleted_at, :datetime + add_index :merge_requests, :deleted_at + end +end diff --git a/db/migrate/20160301124843_add_visibility_level_to_groups.rb b/db/migrate/20160301124843_add_visibility_level_to_groups.rb new file mode 100644 index 0000000000..d1b921bb20 --- /dev/null +++ b/db/migrate/20160301124843_add_visibility_level_to_groups.rb @@ -0,0 +1,29 @@ +class AddVisibilityLevelToGroups < ActiveRecord::Migration + def up + add_column :namespaces, :visibility_level, :integer, null: false, default: Gitlab::VisibilityLevel::PUBLIC + add_index :namespaces, :visibility_level + + # Unfortunately, this is needed on top of the `default`, since we don't want the configuration specific + # `allowed_visibility_level` to end up in schema.rb + if allowed_visibility_level < Gitlab::VisibilityLevel::PUBLIC + execute("UPDATE namespaces SET visibility_level = #{allowed_visibility_level}") + end + end + + def down + remove_column :namespaces, :visibility_level + end + + private + + def allowed_visibility_level + application_settings = select_one("SELECT restricted_visibility_levels FROM application_settings ORDER BY id DESC LIMIT 1") + if application_settings + restricted_visibility_levels = YAML.safe_load(application_settings["restricted_visibility_levels"]) rescue nil + end + restricted_visibility_levels ||= [] + + allowed_levels = Gitlab::VisibilityLevel.values - restricted_visibility_levels + allowed_levels.max + end +end diff --git a/db/migrate/20160308212903_add_default_group_visibility_to_application_settings.rb b/db/migrate/20160308212903_add_default_group_visibility_to_application_settings.rb new file mode 100644 index 0000000000..75de5f70fa --- /dev/null +++ b/db/migrate/20160308212903_add_default_group_visibility_to_application_settings.rb @@ -0,0 +1,29 @@ +# Create visibility level field on DB +# Sets default_visibility_level to value on settings if not restricted +# If value is restricted takes higher visibility level allowed + +class AddDefaultGroupVisibilityToApplicationSettings < ActiveRecord::Migration + def up + add_column :application_settings, :default_group_visibility, :integer + # Unfortunately, this can't be a `default`, since we don't want the configuration specific + # `allowed_visibility_level` to end up in schema.rb + execute("UPDATE application_settings SET default_group_visibility = #{allowed_visibility_level}") + end + + def down + remove_column :application_settings, :default_group_visibility + end + + private + + def allowed_visibility_level + application_settings = select_one("SELECT restricted_visibility_levels FROM application_settings ORDER BY id DESC LIMIT 1") + if application_settings + restricted_visibility_levels = YAML.safe_load(application_settings["restricted_visibility_levels"]) rescue nil + end + restricted_visibility_levels ||= [] + + allowed_levels = Gitlab::VisibilityLevel.values - restricted_visibility_levels + allowed_levels.max + end +end diff --git a/db/migrate/20160320204112_index_namespaces_on_visibility_level.rb b/db/migrate/20160320204112_index_namespaces_on_visibility_level.rb new file mode 100644 index 0000000000..370b339d45 --- /dev/null +++ b/db/migrate/20160320204112_index_namespaces_on_visibility_level.rb @@ -0,0 +1,7 @@ +class IndexNamespacesOnVisibilityLevel < ActiveRecord::Migration + def change + unless index_exists?(:namespaces, :visibility_level) + add_index :namespaces, :visibility_level + end + end +end diff --git a/db/schema.rb b/db/schema.rb index 36b37d3944..dce2bfe62c 100644 --- a/db/schema.rb +++ b/db/schema.rb @@ -11,7 +11,7 @@ # # It's strongly recommended that you check this file into your version control system. -ActiveRecord::Schema.define(version: 20160317092222) do +ActiveRecord::Schema.define(version: 20160320204112) do # These are extensions that must be enabled in order to support this database enable_extension "plpgsql" @@ -77,6 +77,7 @@ ActiveRecord::Schema.define(version: 20160317092222) do t.boolean "akismet_enabled", default: false t.string "akismet_api_key" t.boolean "email_author_in_body", default: false + t.integer "default_group_visibility" end create_table "audit_events", force: :cascade do |t| @@ -418,6 +419,7 @@ ActiveRecord::Schema.define(version: 20160317092222) do t.integer "updated_by_id" t.integer "moved_to_id" t.boolean "confidential", default: false + t.datetime "deleted_at" end add_index "issues", ["assignee_id"], name: "index_issues_on_assignee_id", using: :btree @@ -425,6 +427,7 @@ ActiveRecord::Schema.define(version: 20160317092222) do add_index "issues", ["confidential"], name: "index_issues_on_confidential", using: :btree add_index "issues", ["created_at", "id"], name: "index_issues_on_created_at_and_id", using: :btree add_index "issues", ["created_at"], name: "index_issues_on_created_at", using: :btree + add_index "issues", ["deleted_at"], name: "index_issues_on_deleted_at", using: :btree add_index "issues", ["description"], name: "index_issues_on_description_trigram", using: :gin, opclasses: {"description"=>"gin_trgm_ops"} add_index "issues", ["milestone_id"], name: "index_issues_on_milestone_id", using: :btree add_index "issues", ["project_id", "iid"], name: "index_issues_on_project_id_and_iid", unique: true, using: :btree @@ -547,12 +550,14 @@ ActiveRecord::Schema.define(version: 20160317092222) do t.boolean "merge_when_build_succeeds", default: false, null: false t.integer "merge_user_id" t.string "merge_commit_sha" + t.datetime "deleted_at" end add_index "merge_requests", ["assignee_id"], name: "index_merge_requests_on_assignee_id", using: :btree add_index "merge_requests", ["author_id"], name: "index_merge_requests_on_author_id", using: :btree add_index "merge_requests", ["created_at", "id"], name: "index_merge_requests_on_created_at_and_id", using: :btree add_index "merge_requests", ["created_at"], name: "index_merge_requests_on_created_at", using: :btree + add_index "merge_requests", ["deleted_at"], name: "index_merge_requests_on_deleted_at", using: :btree add_index "merge_requests", ["description"], name: "index_merge_requests_on_description_trigram", using: :gin, opclasses: {"description"=>"gin_trgm_ops"} add_index "merge_requests", ["milestone_id"], name: "index_merge_requests_on_milestone_id", using: :btree add_index "merge_requests", ["source_branch"], name: "index_merge_requests_on_source_branch", using: :btree @@ -591,6 +596,7 @@ ActiveRecord::Schema.define(version: 20160317092222) do t.string "description", default: "", null: false t.string "avatar" t.boolean "share_with_group_lock", default: false + t.integer "visibility_level", default: 20, null: false end add_index "namespaces", ["created_at", "id"], name: "index_namespaces_on_created_at_and_id", using: :btree @@ -600,6 +606,7 @@ ActiveRecord::Schema.define(version: 20160317092222) do add_index "namespaces", ["path"], name: "index_namespaces_on_path", unique: true, using: :btree add_index "namespaces", ["path"], name: "index_namespaces_on_path_trigram", using: :gin, opclasses: {"path"=>"gin_trgm_ops"} add_index "namespaces", ["type"], name: "index_namespaces_on_type", using: :btree + add_index "namespaces", ["visibility_level"], name: "index_namespaces_on_visibility_level", using: :btree create_table "notes", force: :cascade do |t| t.text "note" diff --git a/doc/api/groups.md b/doc/api/groups.md index d47e79ba47..d1b5c9f5f0 100644 --- a/doc/api/groups.md +++ b/doc/api/groups.md @@ -111,6 +111,7 @@ Parameters: - `name` (required) - The name of the group - `path` (required) - The path of the group - `description` (optional) - The group's description +- `visibility_level` (optional) - The group's visibility. 0 for private, 10 for internal, 20 for public. ## Transfer project to group diff --git a/doc/api/issues.md b/doc/api/issues.md index 9e704648b2..18d64c4198 100644 --- a/doc/api/issues.md +++ b/doc/api/issues.md @@ -326,17 +326,25 @@ Example response: } ``` -## Delete existing issue (**Deprecated**) +## Delete an issue -This call is deprecated and returns a `405 Method Not Allowed` error if called. -An issue gets now closed and is done by calling -`PUT /projects/:id/issues/:issue_id` with the parameter `state_event` set to -`close`. See [edit issue](#edit-issue) for more details. +Only for admins and project owners. Soft deletes the issue in question. +If the operation is successful, a status code `200` is returned. In case you cannot +destroy this issue, or it is not present, code `404` is given. ``` DELETE /projects/:id/issues/:issue_id ``` +| Attribute | Type | Required | Description | +| --------- | ---- | -------- | ----------- | +| `id` | integer | yes | The ID of a project | +| `issue_id` | integer | yes | The ID of a project's issue | + +```bash +curl -X DELETE -H "PRIVATE-TOKEN: 9koXpg98eAheJpvBs5tK" https://gitlab.example.com/api/v3/projects/4/issues/85 +``` + ## Comments on issues Comments are done via the [notes](notes.md) resource. diff --git a/doc/api/merge_requests.md b/doc/api/merge_requests.md index 5c527d5548..b20a6300b7 100644 --- a/doc/api/merge_requests.md +++ b/doc/api/merge_requests.md @@ -380,6 +380,25 @@ Parameters: If the operation is successful, 200 and the updated merge request is returned. If an error occurs, an error number and a message explaining the reason is returned. +## Delete a merge request + +Only for admins and project owners. Soft deletes the merge request in question. +If the operation is successful, a status code `200` is returned. In case you cannot +destroy this merge request, or it is not present, code `404` is given. + +``` +DELETE /projects/:id/merge_requests/:merge_request_id +``` + +| Attribute | Type | Required | Description | +| --------- | ---- | -------- | ----------- | +| `id` | integer | yes | The ID of a project | +| `merge_request_id` | integer | yes | The ID of a project's merge request | + +```bash +curl -X DELETE -H "PRIVATE-TOKEN: 9koXpg98eAheJpvBs5tK" https://gitlab.example.com/api/v3/projects/4/merge_request/85 +``` + ## Accept MR Merge changes submitted with MR using this API. diff --git a/doc/ci/yaml/README.md b/doc/ci/yaml/README.md index 762b35859b..4316f3c1f6 100644 --- a/doc/ci/yaml/README.md +++ b/doc/ci/yaml/README.md @@ -331,7 +331,7 @@ There are a few rules that apply to the usage of refs policy: * `only` and `except` are inclusive. If both `only` and `except` are defined in a job specification, the ref is filtered by `only` and `except`. * `only` and `except` allow the use of regular expressions. -* `only` and `except` allow the use of special keywords: `branches` and `tags`. +* `only` and `except` allow the use of special keywords: `branches`, `tags`, and `triggers`. * `only` and `except` allow to specify a repository path to filter jobs for forks. @@ -348,6 +348,17 @@ job: - branches ``` +In this example, `job` will run only for refs that are tagged, or if a build is explicitly requested +via an API trigger. + +```yaml +job: + # use special keywords + only: + - tags + - triggers +``` + The repository path can be used to have jobs executed only for the parent repository and not forks: diff --git a/doc/development/scss_styleguide.md b/doc/development/scss_styleguide.md index 6c48c25448..a79f4073cd 100644 --- a/doc/development/scss_styleguide.md +++ b/doc/development/scss_styleguide.md @@ -72,9 +72,9 @@ p { margin: 0; padding: 0; } ### Colors -HEX (hexadecimal) colors short-form should use shortform where possible, and -should use lower case letters to differenciate between letters and numbers, e. -g. `#E3E3E3` vs. `#e3e3e3`. +HEX (hexadecimal) colors should use shorthand where possible, and should use +lower case letters to differentiate between letters and numbers, e.g. `#E3E3E3` +vs. `#e3e3e3`. ```scss // Bad @@ -160,6 +160,7 @@ is slightly more performant. ``` ### Selectors with a `js-` Prefix + Do not use any selector prefixed with `js-` for styling purposes. These selectors are intended for use only with JavaScript to allow for removal or renaming without breaking styling. @@ -187,8 +188,28 @@ CSSComb globally (system-wide). Run it in the GitLab directory with Note that this won't fix every problem, but it should fix a majority. +### Ignoring issues + +If you want a line or set of lines to be ignored by the linter, you can use +`// scss-lint:disable RuleName` ([more info][disabling-linters]): + +```scss +// This lint rule is disabled because the class name comes from a gem. +// scss-lint:disable SelectorFormat +.ui_charcoal { + background-color: #333; +} +// scss-lint:enable SelectorFormat +``` + +Make sure a comment is added on the line above the `disable` rule, otherwise the +linter will throw a warning. `DisableLinterReason` is enabled to make sure the +style guide isn't being ignored, and to communicate to others why the style +guide is ignored in this instance. + [csscomb]: https://github.com/csscomb/csscomb.js [node]: https://github.com/nodejs/node [npm]: https://www.npmjs.com/ [scss-lint]: https://github.com/brigade/scss-lint [scss-lint-documentation]: https://github.com/brigade/scss-lint/blob/master/lib/scss_lint/linter/README.md +[disabling-linters]: https://github.com/brigade/scss-lint#disabling-linters-via-source diff --git a/doc/gitlab-basics/README.md b/doc/gitlab-basics/README.md index 493e1d1b09..3aa83975ac 100644 --- a/doc/gitlab-basics/README.md +++ b/doc/gitlab-basics/README.md @@ -2,26 +2,14 @@ Step-by-step guides on the basics of working with Git and GitLab. -* [Start using Git on the command line](start-using-git.md) - -* [Create and add your SSH Keys](create-your-ssh-keys.md) - -* [Command Line basic commands](command-line-commands.md) - -* [Basic Git commands](basic-git-commands.md) - -* [Create a project](create-project.md) - -* [Create a group](create-group.md) - -* [Create a branch](create-branch.md) - -* [Fork a project](fork-project.md) - -* [Add a file](add-file.md) - -* [Add an image](add-image.md) - -* [Create a Merge Request](add-merge-request.md) - -* [Create an Issue](create-issue.md) +- [Start using Git on the command line](start-using-git.md) +- [Create and add your SSH Keys](create-your-ssh-keys.md) +- [Command Line basics](command-line-commands.md) +- [Create a project](create-project.md) +- [Create a group](create-group.md) +- [Create a branch](create-branch.md) +- [Fork a project](fork-project.md) +- [Add a file](add-file.md) +- [Add an image](add-image.md) +- [Create a Merge Request](add-merge-request.md) +- [Create an Issue](create-issue.md) diff --git a/doc/gitlab-basics/basic-git-commands.md b/doc/gitlab-basics/basic-git-commands.md index 2b5767dd2d..c2a3415cbc 100644 --- a/doc/gitlab-basics/basic-git-commands.md +++ b/doc/gitlab-basics/basic-git-commands.md @@ -1,59 +1,3 @@ # Basic Git commands -### Go to the master branch to pull the latest changes from there -``` -git checkout master -``` - -### Download the latest changes in the project -This is for you to work on an up-to-date copy (it is important to do every time you work on a project), while you setup tracking branches. -``` -git pull REMOTE NAME-OF-BRANCH -u -``` -(REMOTE: origin) (NAME-OF-BRANCH: could be "master" or an existing branch) - -### Create a branch -Spaces won't be recognized, so you need to use a hyphen or underscore. -``` -git checkout -b NAME-OF-BRANCH -``` - -### Work on a branch that has already been created -``` -git checkout NAME-OF-BRANCH -``` - -### View the changes you've made -It's important to be aware of what's happening and what's the status of your changes. -``` -git status -``` - -### Add changes to commit -You'll see your changes in red when you type "git status". -``` -git add CHANGES IN RED -git commit -m "DESCRIBE THE INTENTION OF THE COMMIT" -``` - -### Send changes to gitlab.com -``` -git push REMOTE NAME-OF-BRANCH -``` - -### Delete all changes in the Git repository, but leave unstaged things -``` -git checkout . -``` - -### Delete all changes in the Git repository, including untracked files -``` -git clean -f -``` - -### Merge created branch with master branch -You need to be in the created branch. -``` -git checkout NAME-OF-BRANCH -git merge master -``` +This section is now merged into [Start using Git](start-using-git.md). diff --git a/doc/gitlab-basics/start-using-git.md b/doc/gitlab-basics/start-using-git.md index b2ceda025c..89ce8bcc3e 100644 --- a/doc/gitlab-basics/start-using-git.md +++ b/doc/gitlab-basics/start-using-git.md @@ -1,6 +1,7 @@ # Start using Git on the command line -If you want to start using a Git and GitLab, make sure that you have created an account on GitLab. +If you want to start using a Git and GitLab, make sure that you have created an +account on GitLab. ## Open a shell @@ -59,3 +60,63 @@ To view the information that you entered, type: ``` git config --global --list ``` +## Basic Git commands + +### Go to the master branch to pull the latest changes from there + +``` +git checkout master +``` + +### Download the latest changes in the project +This is for you to work on an up-to-date copy (it is important to do every time you work on a project), while you setup tracking branches. +``` +git pull REMOTE NAME-OF-BRANCH -u +``` +(REMOTE: origin) (NAME-OF-BRANCH: could be "master" or an existing branch) + +### Create a branch +Spaces won't be recognized, so you need to use a hyphen or underscore. +``` +git checkout -b NAME-OF-BRANCH +``` + +### Work on a branch that has already been created +``` +git checkout NAME-OF-BRANCH +``` + +### View the changes you've made +It's important to be aware of what's happening and what's the status of your changes. +``` +git status +``` + +### Add changes to commit +You'll see your changes in red when you type "git status". +``` +git add CHANGES IN RED +git commit -m "DESCRIBE THE INTENTION OF THE COMMIT" +``` + +### Send changes to gitlab.com +``` +git push REMOTE NAME-OF-BRANCH +``` + +### Delete all changes in the Git repository, but leave unstaged things +``` +git checkout . +``` + +### Delete all changes in the Git repository, including untracked files +``` +git clean -f +``` + +### Merge created branch with master branch +You need to be in the created branch. +``` +git checkout NAME-OF-BRANCH +git merge master +``` diff --git a/doc/intro/README.md b/doc/intro/README.md new file mode 100644 index 0000000000..fecbbe6317 --- /dev/null +++ b/doc/intro/README.md @@ -0,0 +1,41 @@ +# Get started with GitLab + +## Organize + +Create projects and groups. + +- [Create a new project](../gitlab-basics/create-project.md) +- [Create a new group](../gitlab-basics/create-group.md) + +## Prioritize + +Create issues, labels, milestones, cast your vote, and review issues. + +- [Create a new issue](../gitlab-basics/create-issue.md) +- [Assign labels to issues](../workflow/labels.md) +- [Use milestones as an overview of your project's tracker](../workflow/milestones.md) +- [Use voting to express your like/dislike to issues and merge requests](../workflow/award_emoji.md) + +## Collaborate + +Create merge requests and review code. + +- [Fork a project and contribute to it](../workflow/forking_workflow.md) +- [Create a new merge request](../gitlab-basics/add-merge-request.md) +- [Automatically close issues from merge requests](../customization/issue_closing.md) +- [Automatically merge when your builds succeed](../workflow/merge_when_build_succeeds.md) +- [Revert any commit](../workflow/revert_changes.md) + +## Test and Deploy + +Use the built-in continuous integration in GitLab. + +- [Get started with GitLab CI](../ci/quick_start/README.md) + +## Install and Update + +Install and update your GitLab installation. + +- [Install GitLab](https://about.gitlab.com/installation/) +- [Update GitLab](https://about.gitlab.com/update/) +- [Explore Omnibus GitLab configuration options](http://doc.gitlab.com/omnibus/settings/configuration.html) diff --git a/doc/monitoring/performance/grafana_configuration.md b/doc/monitoring/performance/grafana_configuration.md new file mode 100644 index 0000000000..416c9870aa --- /dev/null +++ b/doc/monitoring/performance/grafana_configuration.md @@ -0,0 +1,118 @@ +# Grafana Configuration + +[Grafana](http://grafana.org/) is a tool that allows you to visualize time +series metrics through graphs and dashboards. It supports several backend +data stores, including InfluxDB. GitLab writes performance data to InfluxDB +and Grafana will allow you to query InfluxDB to display useful graphs. + +For the easiest installation and configuration, install Grafana on the same +server as InfluxDB. For larger installations, you may want to split out these +services. + +## Installation + +Grafana supplies package repositories (Yum/Apt) for easy installation. +See [Grafana installation documentation](http://docs.grafana.org/installation/) +for detailed steps. + +> **Note**: Before starting Grafana for the first time, set the admin user +and password in `/etc/grafana/grafana.ini`. Otherwise, the default password +will be `admin`. + +## Configuration + +Login as the admin user. Expand the menu by clicking the Grafana logo in the +top left corner. Choose 'Data Sources' from the menu. Then, click 'Add new' +in the top bar. + +![Grafana empty data source page](img/grafana_data_source_empty.png) + +Fill in the configuration details for the InfluxDB data source. Save and +Test Connection to ensure the configuration is correct. + +- **Name**: InfluxDB +- **Default**: Checked +- **Type**: InfluxDB 0.9.x (Even if you're using InfluxDB 0.10.x) +- **Url**: https://localhost:8086 (Or the remote URL if you've installed InfluxDB +on a separate server) +- **Access**: proxy +- **Database**: gitlab +- **User**: admin (Or the username configured when setting up InfluxDB) +- **Password**: The password configured when you set up InfluxDB + +![Grafana data source configurations](img/grafana_data_source_configuration.png) + +## Apply retention policies and create continuous queries + +If you intend to import the GitLab provided Grafana dashboards, you will need +to copy and run a set of queries against InfluxDB to create the needed data +sets. + +On the InfluxDB server, run the following command, substituting your InfluxDB +user and password: + +```bash +influxdb --username admin -password super_secret +``` + +This will drop you in to an InfluxDB interactive session. Copy the entire +contents below and paste it in to the interactive session: + +``` +CREATE RETENTION POLICY gitlab_30d ON gitlab DURATION 30d REPLICATION 1 DEFAULT +CREATE RETENTION POLICY seven_days ON gitlab DURATION 7d REPLICATION 1 +CREATE CONTINUOUS QUERY rails_transaction_timings_seven_days ON gitlab BEGIN SELECT percentile("duration", 95.000) AS "duration_95th", percentile("duration", 99.000) AS "duration_99th", mean("duration") AS "duration_mean", percentile(sql_duration, 95.000) AS "sql_duration_95th", percentile(sql_duration, 99.000) AS "sql_duration_99th", mean(sql_duration) AS "sql_duration_mean", percentile(view_duration, 95.000) AS "view_duration_95th", percentile(view_duration, 99.000) AS "view_duration_99th", mean(view_duration) AS "view_duration_mean" INTO gitlab.seven_days.rails_transaction_timings FROM gitlab.gitlab_30d.rails_transactions GROUP BY time(1m) END +CREATE CONTINUOUS QUERY sidekiq_transaction_timings_seven_days ON gitlab BEGIN SELECT percentile("duration", 95.000) AS "duration_95th", percentile("duration", 99.000) AS "duration_99th", mean("duration") AS "duration_mean", percentile(sql_duration, 95.000) AS "sql_duration_95th", percentile(sql_duration, 99.000) AS "sql_duration_99th", mean(sql_duration) AS "sql_duration_mean", percentile(view_duration, 95.000) AS "view_duration_95th", percentile(view_duration, 99.000) AS "view_duration_99th", mean(view_duration) AS "view_duration_mean" INTO gitlab.seven_days.sidekiq_transaction_timings FROM gitlab.gitlab_30d.sidekiq_transactions GROUP BY time(1m) END +CREATE CONTINUOUS QUERY rails_transaction_counts_seven_days ON gitlab BEGIN SELECT count("duration") AS "count" INTO gitlab.seven_days.rails_transaction_counts FROM gitlab.gitlab_30d.rails_transactions GROUP BY time(1m) END +CREATE CONTINUOUS QUERY sidekiq_transaction_counts_seven_days ON gitlab BEGIN SELECT count("duration") AS "count" INTO gitlab.seven_days.sidekiq_transaction_counts FROM gitlab.gitlab_30d.sidekiq_transactions GROUP BY time(1m) END +CREATE CONTINUOUS QUERY rails_method_call_timings_seven_days ON gitlab BEGIN SELECT percentile("duration", 95.000) AS "duration_95th", percentile("duration", 99.000) AS "duration_99th", mean("duration") AS "duration_mean" INTO gitlab.seven_days.rails_method_call_timings FROM gitlab.gitlab_30d.rails_method_calls GROUP BY time(1m) END +CREATE CONTINUOUS QUERY sidekiq_method_call_timings_seven_days ON gitlab BEGIN SELECT percentile("duration", 95.000) AS "duration_95th", percentile("duration", 99.000) AS "duration_99th", mean("duration") AS "duration_mean" INTO gitlab.seven_days.sidekiq_method_call_timings FROM gitlab.gitlab_30d.sidekiq_method_calls GROUP BY time(1m) END +CREATE CONTINUOUS QUERY rails_method_call_timings_per_method_seven_days ON gitlab BEGIN SELECT percentile("duration", 95.000) AS duration_95th, percentile("duration", 99.000) AS duration_99th, mean("duration") AS duration_mean INTO gitlab.seven_days.rails_method_call_timings_per_method FROM gitlab.gitlab_30d.rails_method_calls GROUP BY time(1m), method END +CREATE CONTINUOUS QUERY sidekiq_method_call_timings_per_method_seven_days ON gitlab BEGIN SELECT percentile("duration", 95.000) AS duration_95th, percentile("duration", 99.000) AS duration_99th, mean("duration") AS duration_mean INTO gitlab.seven_days.sidekiq_method_call_timings_per_method FROM gitlab.gitlab_30d.sidekiq_method_calls GROUP BY time(1m), method END +CREATE CONTINUOUS QUERY rails_memory_usage_per_minute ON gitlab BEGIN SELECT percentile(value, 95.000) AS memory_95th, percentile(value, 99.000) AS memory_99th, mean(value) AS memory_mean INTO gitlab.seven_days.rails_memory_usage_per_minute FROM gitlab.gitlab_30d.rails_memory_usage GROUP BY time(1m) END +CREATE CONTINUOUS QUERY sidekiq_memory_usage_per_minute ON gitlab BEGIN SELECT percentile(value, 95.000) AS memory_95th, percentile(value, 99.000) AS memory_99th, mean(value) AS memory_mean INTO gitlab.seven_days.sidekiq_memory_usage_per_minute FROM gitlab.gitlab_30d.sidekiq_memory_usage GROUP BY time(1m) END +CREATE CONTINUOUS QUERY sidekiq_file_descriptors_per_minute ON gitlab BEGIN SELECT sum(value) AS value INTO gitlab.seven_days.sidekiq_file_descriptors_per_minute FROM gitlab.gitlab_30d.sidekiq_file_descriptors GROUP BY time(1m) END +CREATE CONTINUOUS QUERY rails_file_descriptors_per_minute ON gitlab BEGIN SELECT sum(value) AS value INTO gitlab.seven_days.rails_file_descriptors_per_minute FROM gitlab.gitlab_30d.rails_file_descriptors GROUP BY time(1m) END +CREATE CONTINUOUS QUERY rails_gc_counts_per_minute ON gitlab BEGIN SELECT sum(count) AS count INTO gitlab.seven_days.rails_gc_counts_per_minute FROM gitlab.gitlab_30d.rails_gc_statistics GROUP BY time(1m) END +CREATE CONTINUOUS QUERY sidekiq_gc_counts_per_minute ON gitlab BEGIN SELECT sum(count) AS count INTO gitlab.seven_days.sidekiq_gc_counts_per_minute FROM gitlab.gitlab_30d.sidekiq_gc_statistics GROUP BY time(1m) END +CREATE CONTINUOUS QUERY rails_gc_timings_per_minute ON gitlab BEGIN SELECT percentile(total_time, 95.000) AS duration_95th, percentile(total_time, 99.000) AS duration_99th, mean(total_time) AS duration_mean INTO gitlab.seven_days.rails_gc_timings_per_minute FROM gitlab.gitlab_30d.rails_gc_statistics GROUP BY time(1m) END +CREATE CONTINUOUS QUERY sidekiq_gc_timings_per_minute ON gitlab BEGIN SELECT percentile(total_time, 95.000) AS duration_95th, percentile(total_time, 99.000) AS duration_99th, mean(total_time) AS duration_mean INTO gitlab.seven_days.sidekiq_gc_timings_per_minute FROM gitlab.gitlab_30d.sidekiq_gc_statistics GROUP BY time(1m) END +CREATE CONTINUOUS QUERY rails_gc_major_minor_per_minute ON gitlab BEGIN SELECT sum(major_gc_count) AS major, sum(minor_gc_count) AS minor INTO gitlab.seven_days.rails_gc_major_minor_per_minute FROM gitlab.gitlab_30d.rails_gc_statistics GROUP BY time(1m) END +CREATE CONTINUOUS QUERY sidekiq_gc_major_minor_per_minute ON gitlab BEGIN SELECT sum(major_gc_count) AS major, sum(minor_gc_count) AS minor INTO gitlab.seven_days.sidekiq_gc_major_minor_per_minute FROM gitlab.gitlab_30d.sidekiq_gc_statistics GROUP BY time(1m) END +``` + +## Import Dashboards + +You can now import a set of default dashboards that will give you a good +start on displaying useful information. GitLab has published a set of default +[Grafana dashboards][grafana-dashboards] to get you started. Clone the +repository or download a zip/tarball, then follow these steps to import each +JSON file. + +Open the dashboard dropdown menu and click 'Import' + +![Grafana dashboard dropdown](/img/grafana_dashboard_dropdown.png) + +Click 'Choose file' and browse to the location where you downloaded or cloned +the dashboard repository. Pick one of the JSON files to import. + +![Grafana dashboard import](/img/grafana_dashboard_import.png) + +Once the dashboard is imported, be sure to click save icon in the top bar. If +you do not save the dashboard after importing it will be removed when you +navigate away. + +![Grafana save icon](/img/grafana_save_icon.png) + +Repeat this process for each dashboard you wish to import. + +[grafana-dashboards]: https://gitlab.com/gitlab-org/grafana-dashboards + +--- + +Read more on: + +- [Introduction to GitLab Performance Monitoring](introduction.md) +- [GitLab Configuration](gitlab_configuration.md) +- [InfluxDB Installation/Configuration](influxdb_configuration.md) +- [InfluxDB Schema](influxdb_schema.md) diff --git a/doc/monitoring/performance/img/grafana_dashboard_dropdown.png b/doc/monitoring/performance/img/grafana_dashboard_dropdown.png new file mode 100644 index 0000000000..b4448c7a09 Binary files /dev/null and b/doc/monitoring/performance/img/grafana_dashboard_dropdown.png differ diff --git a/doc/monitoring/performance/img/grafana_dashboard_import.png b/doc/monitoring/performance/img/grafana_dashboard_import.png new file mode 100644 index 0000000000..5a2d3c0937 Binary files /dev/null and b/doc/monitoring/performance/img/grafana_dashboard_import.png differ diff --git a/doc/monitoring/performance/img/grafana_data_source_configuration.png b/doc/monitoring/performance/img/grafana_data_source_configuration.png new file mode 100644 index 0000000000..7e2e111f57 Binary files /dev/null and b/doc/monitoring/performance/img/grafana_data_source_configuration.png differ diff --git a/doc/monitoring/performance/img/grafana_data_source_empty.png b/doc/monitoring/performance/img/grafana_data_source_empty.png new file mode 100644 index 0000000000..11e27571e6 Binary files /dev/null and b/doc/monitoring/performance/img/grafana_data_source_empty.png differ diff --git a/doc/monitoring/performance/img/grafana_save_icon.png b/doc/monitoring/performance/img/grafana_save_icon.png new file mode 100644 index 0000000000..3d4265bee8 Binary files /dev/null and b/doc/monitoring/performance/img/grafana_save_icon.png differ diff --git a/doc/monitoring/performance/introduction.md b/doc/monitoring/performance/introduction.md index f2460d3130..79904916b7 100644 --- a/doc/monitoring/performance/introduction.md +++ b/doc/monitoring/performance/introduction.md @@ -8,8 +8,9 @@ Apart from this introduction, you are advised to read through the following documents in order to understand and properly configure GitLab Performance Monitoring: - [GitLab Configuration](gitlab_configuration.md) -- [InfluxDB Configuration](influxdb_configuration.md) +- [InfluxDB Install/Configuration](influxdb_configuration.md) - [InfluxDB Schema](influxdb_schema.md) +- [Grafana Install/Configuration](grafana_configuration.md) ## Introduction to GitLab Performance Monitoring diff --git a/doc/public_access/public_access.md b/doc/public_access/public_access.md index 6e22ea7b72..20aa90f0d6 100644 --- a/doc/public_access/public_access.md +++ b/doc/public_access/public_access.md @@ -35,6 +35,21 @@ the repository. 1. Go to your project's **Settings** 1. Change "Visibility Level" to either Public, Internal or Private +## Visibility of groups + +>**Note:** +[Starting with][3323] GitLab 8.6, the group visibility has changed and can be +configured the same way as projects. In previous versions, a group's page was +always visible to all users. + +Like with projects, the visibility of a group can be set to dictate whether +anonymous users, all signed in users, or only explicit group members can view +it. The restriction for visibility levels on the application setting level also +applies to groups, so if that's set to internal, the explore page will be empty +for anonymous users. The group page now has a visibility level icon. + +[3323]: https://gitlab.com/gitlab-org/gitlab-ce/merge_requests/3323 + ## Visibility of users The public page of a user, located at `/u/username`, is always visible whether @@ -43,14 +58,6 @@ you are logged in or not. When visiting the public page of a user, you can only see the projects which you are privileged to. -## Visibility of groups - -The public page of a group, located at `/groups/groupname`, is always visible -to everyone. - -Logged out users will be able to see the description and the avatar of the -group as well as all public projects belonging to that group. - ## Restricting the use of public or internal projects In the Admin area under **Settings** (`/admin/application_settings`), you can diff --git a/doc/raketasks/backup_restore.md b/doc/raketasks/backup_restore.md index f6d1234ac4..4329ac30a1 100644 --- a/doc/raketasks/backup_restore.md +++ b/doc/raketasks/backup_restore.md @@ -249,6 +249,9 @@ reconfigure` after changing `gitlab-secrets.json`. ### Installation from source ``` +# Stop processes that are connected to the database +sudo service gitlab stop + bundle exec rake gitlab:backup:restore RAILS_ENV=production ``` diff --git a/doc/update/README.md b/doc/update/README.md index 109d5de3fa..0241f03683 100644 --- a/doc/update/README.md +++ b/doc/update/README.md @@ -15,3 +15,4 @@ Depending on the installation method and your GitLab version, there are multiple - [MySQL to PostgreSQL](mysql_to_postgresql.md) guides you through migrating your database from MySQL to PostgreSQL. - [MySQL installation guide](https://gitlab.com/gitlab-org/gitlab-ce/blob/master/doc/install/database_mysql.md) contains additional information about configuring GitLab to work with a MySQL database. +- [Restoring from backup after a failed upgrade](restore_after_failure.md) diff --git a/doc/update/restore_after_failure.md b/doc/update/restore_after_failure.md new file mode 100644 index 0000000000..01c52aae7f --- /dev/null +++ b/doc/update/restore_after_failure.md @@ -0,0 +1,83 @@ +# Restoring from backup after a failed upgrade + +Upgrades are usually smooth and restoring from backup is a rare occurrence. +However, it's important to know how to recover when problems do arise. + +## Roll back to an earlier version and restore a backup + +In some cases after a failed upgrade, the fastest solution is to roll back to +the previous version you were using. + +First, roll back the code or package. For source installations this involves +checking out the older version (branch or tag). For Omnibus installations this +means installing the older .deb or .rpm package. Then, restore from a backup. +Follow the instructions in the +[Backup and Restore](../raketasks/backup_restore.md#restore-a-previously-created-backup) +documentation. + +## Potential problems on the next upgrade + +When a rollback is necessary it can produce problems on subsequent upgrade +attempts. This is because some tables may have been added during the failed +upgrade. If these tables are still present after you restore from the +older backup it can lead to migration failures on future upgrades. + +Starting in GitLab 8.6 we drop all tables prior to importing the backup to +prevent this problem. If you've restored a backup to a version prior to 8.6 you +may need to manually correct the problem next time you upgrade. + +Example error: + +``` +== 20151103134857 CreateLfsObjects: migrating ================================= +-- create_table(:lfs_objects) +rake aborted! +StandardError: An error has occurred, this and all later migrations canceled: + +PG::DuplicateTable: ERROR: relation "lfs_objects" already exists +``` + +Copy the version from the error. In this case the version number is +`20151103134857`. + +>**WARNING:** Use the following steps only if you are certain this is what you +need to do. + +### GitLab 8.6+ + +Pass the version to a database rake task to manually mark the migration as +complete. + +``` +# Source install +sudo -u git -H bundle exec rake gitlab:db:mark_migration_complete[20151103134857] RAILS_ENV=production + +# Omnibus install +sudo gitlab-rake gitlab:db:mark_migration_complete[20151103134857] +``` + +Once the migration is successfully marked, run the rake `db:migrate` task again. +You will likely have to repeat this process several times until all failed +migrations are marked complete. + +### GitLab < 8.6 + +``` +# Source install +sudo -u git -H bundle exec rails console production + +# Omnibus install +sudo gitlab-rails console +``` + +At the Rails console, type the following commands: + +``` +ActiveRecord::Base.connection.execute("INSERT INTO schema_migrations (version) VALUES('20151103134857')") +exit +``` + +Once the migration is successfully marked, run the rake `db:migrate` task again. +You will likely have to repeat this process several times until all failed +migrations are marked complete. + diff --git a/doc/workflow/award_emoji.md b/doc/workflow/award_emoji.md new file mode 100644 index 0000000000..70b35c58be --- /dev/null +++ b/doc/workflow/award_emoji.md @@ -0,0 +1,48 @@ +# Award emojis + +>**Note:** +This feature was [introduced][1825] in GitLab 8.2. + +When you're collaborating online, you get fewer opportunities for high-fives +and thumbs-ups. In order to make virtual celebrations easier, you can now vote +on issues and merge requests using emoji! + +![Award emoji](img/award_emoji_select.png) + +This makes it much easier to give and receive feedback, without a long comment +thread. Any comment that contains only the thumbs up or down emojis is +converted to a vote and depicted in the emoji area. + +You can then use that functionality to sort issues and merge requests based on +popularity. + +## Sort issues and merge requests on vote count + +>**Note:** +This feature was [introduced][2871] in GitLab 8.5. + +You can quickly sort the issues or merge requests by the number of votes they +have received. The sort option can be found in the right dropdown menu. + +![Votes sort options](img/award_emoji_votes_sort_options.png) + +--- + +Sort by most popular issues/merge requests. + +![Votes sort by most popular](img/award_emoji_votes_most_popular.png) + +--- + +Sort by least popular issues/merge requests. + +![Votes sort by least popular](img/award_emoji_votes_least_popular.png) + +--- + +The number of upvotes and downvotes is not summed up. That means that an issue +with 18 upvotes and 5 downvotes is considered more popular than an issue with +17 upvotes and no downvotes. + +[2871]: https://gitlab.com/gitlab-org/gitlab-ce/merge_requests/2781 +[1825]: https://gitlab.com/gitlab-org/gitlab-ce/merge_requests/1825 diff --git a/doc/workflow/img/award_emoji_select.png b/doc/workflow/img/award_emoji_select.png new file mode 100644 index 0000000000..fffdfedda5 Binary files /dev/null and b/doc/workflow/img/award_emoji_select.png differ diff --git a/doc/workflow/img/award_emoji_votes_least_popular.png b/doc/workflow/img/award_emoji_votes_least_popular.png new file mode 100644 index 0000000000..2ef5be7154 Binary files /dev/null and b/doc/workflow/img/award_emoji_votes_least_popular.png differ diff --git a/doc/workflow/img/award_emoji_votes_most_popular.png b/doc/workflow/img/award_emoji_votes_most_popular.png new file mode 100644 index 0000000000..5b089730d9 Binary files /dev/null and b/doc/workflow/img/award_emoji_votes_most_popular.png differ diff --git a/doc/workflow/img/award_emoji_votes_sort_options.png b/doc/workflow/img/award_emoji_votes_sort_options.png new file mode 100644 index 0000000000..9bbf3f82a0 Binary files /dev/null and b/doc/workflow/img/award_emoji_votes_sort_options.png differ diff --git a/features/steps/dashboard/issues.rb b/features/steps/dashboard/issues.rb index f4a5686553..93aa77589b 100644 --- a/features/steps/dashboard/issues.rb +++ b/features/steps/dashboard/issues.rb @@ -43,10 +43,10 @@ class Spinach::Features::DashboardIssues < Spinach::FeatureSteps step 'I click "All" link' do find('.js-author-search').click - find('.dropdown-menu-user-full-name', match: :first).click + find('.dropdown-content a', match: :first).click find('.js-assignee-search').click - find('.dropdown-menu-user-full-name', match: :first).click + find('.dropdown-content a', match: :first).click end def should_see(issue) diff --git a/lib/api/entities.rb b/lib/api/entities.rb index 71197205f3..197e826e5b 100644 --- a/lib/api/entities.rb +++ b/lib/api/entities.rb @@ -85,7 +85,7 @@ module API end class Group < Grape::Entity - expose :id, :name, :path, :description + expose :id, :name, :path, :description, :visibility_level expose :avatar_url expose :web_url do |group, options| @@ -340,6 +340,7 @@ module API expose :session_expire_delay expose :default_project_visibility expose :default_snippet_visibility + expose :default_group_visibility expose :restricted_signup_domains expose :user_oauth_applications expose :after_sign_out_path diff --git a/lib/api/groups.rb b/lib/api/groups.rb index 1a14d870a4..c165de21a7 100644 --- a/lib/api/groups.rb +++ b/lib/api/groups.rb @@ -31,7 +31,7 @@ module API authorize! :create_group, current_user required_attributes! [:name, :path] - attrs = attributes_for_keys [:name, :path, :description] + attrs = attributes_for_keys [:name, :path, :description, :visibility_level] @group = Group.new(attrs) if @group.save diff --git a/lib/api/helpers.rb b/lib/api/helpers.rb index a72044e805..4921ae99e7 100644 --- a/lib/api/helpers.rb +++ b/lib/api/helpers.rb @@ -118,9 +118,7 @@ module API end def authorize!(action, subject) - unless abilities.allowed?(current_user, action, subject) - forbidden! - end + forbidden! unless abilities.allowed?(current_user, action, subject) end def authorize_push_project diff --git a/lib/api/issues.rb b/lib/api/issues.rb index fda6f84143..e5ae88eb96 100644 --- a/lib/api/issues.rb +++ b/lib/api/issues.rb @@ -191,7 +191,7 @@ module API end end - # Delete a project issue (deprecated) + # Delete a project issue # # Parameters: # id (required) - The ID of a project @@ -199,7 +199,10 @@ module API # Example Request: # DELETE /projects/:id/issues/:issue_id delete ":id/issues/:issue_id" do - not_allowed! + issue = user_project.issues.find_by(id: params[:issue_id]) + + authorize!(:destroy_issue, issue) + issue.destroy end end end diff --git a/lib/api/merge_requests.rb b/lib/api/merge_requests.rb index c5e5d57ed4..93052fba06 100644 --- a/lib/api/merge_requests.rb +++ b/lib/api/merge_requests.rb @@ -100,6 +100,18 @@ module API end end + # Delete a MR + # + # Parameters: + # id (required) - The ID of the project + # merge_request_id (required) - The MR id + delete ":id/merge_requests/:merge_request_id" do + merge_request = user_project.merge_requests.find_by(id: params[:merge_request_id]) + + authorize!(:destroy_merge_request, merge_request) + merge_request.destroy + end + # Routing "merge_request/:merge_request_id/..." is DEPRECATED and WILL BE REMOVED in version 9.0 # Use "merge_requests/:merge_request_id/..." instead. # diff --git a/lib/ci/gitlab_ci_yaml_processor.rb b/lib/ci/gitlab_ci_yaml_processor.rb index c89e1b5101..b7209c1414 100644 --- a/lib/ci/gitlab_ci_yaml_processor.rb +++ b/lib/ci/gitlab_ci_yaml_processor.rb @@ -26,8 +26,8 @@ module Ci validate! end - def builds_for_stage_and_ref(stage, ref, tag = false) - builds.select{|build| build[:stage] == stage && process?(build[:only], build[:except], ref, tag)} + def builds_for_stage_and_ref(stage, ref, tag = false, trigger_request = nil) + builds.select{|build| build[:stage] == stage && process?(build[:only], build[:except], ref, tag, trigger_request)} end def builds @@ -242,9 +242,9 @@ module Ci stage_index = stages.index(job[:stage]) job[:dependencies].each do |dependency| - raise ValidationError, "#{name} job: undefined dependency: #{dependency}" unless @jobs[dependency] + raise ValidationError, "#{name} job: undefined dependency: #{dependency}" unless @jobs[dependency.to_sym] - unless stages.index(@jobs[dependency][:stage]) < stage_index + unless stages.index(@jobs[dependency.to_sym][:stage]) < stage_index raise ValidationError, "#{name} job: dependency #{dependency} is not defined in prior stages" end end @@ -266,29 +266,30 @@ module Ci value.in?([true, false]) end - def process?(only_params, except_params, ref, tag) + def process?(only_params, except_params, ref, tag, trigger_request) if only_params.present? - return false unless matching?(only_params, ref, tag) + return false unless matching?(only_params, ref, tag, trigger_request) end if except_params.present? - return false if matching?(except_params, ref, tag) + return false if matching?(except_params, ref, tag, trigger_request) end true end - def matching?(patterns, ref, tag) + def matching?(patterns, ref, tag, trigger_request) patterns.any? do |pattern| - match_ref?(pattern, ref, tag) + match_ref?(pattern, ref, tag, trigger_request) end end - def match_ref?(pattern, ref, tag) + def match_ref?(pattern, ref, tag, trigger_request) pattern, path = pattern.split('@', 2) return false if path && path != self.path return true if tag && pattern == 'tags' return true if !tag && pattern == 'branches' + return true if trigger_request.present? && pattern == 'triggers' if pattern.first == "/" && pattern.last == "/" Regexp.new(pattern[1...-1]) =~ ref diff --git a/lib/gitlab/email/receiver.rb b/lib/gitlab/email/receiver.rb index 2ca21af5bc..d4b6f6d120 100644 --- a/lib/gitlab/email/receiver.rb +++ b/lib/gitlab/email/receiver.rb @@ -45,12 +45,12 @@ module Gitlab note = create_note(reply) unless note.persisted? - message = "The comment could not be created for the following reasons:" + msg = "The comment could not be created for the following reasons:" note.errors.full_messages.each do |error| - message << "\n\n- #{error}" + msg << "\n\n- #{error}" end - raise InvalidNoteError, message + raise InvalidNoteError, msg end end @@ -63,13 +63,13 @@ module Gitlab end def reply_key - reply_key = nil + key = nil message.to.each do |address| - reply_key = Gitlab::IncomingEmail.key_from_address(address) - break if reply_key + key = Gitlab::IncomingEmail.key_from_address(address) + break if key end - reply_key + key end def sent_notification diff --git a/lib/gitlab/visibility_level.rb b/lib/gitlab/visibility_level.rb index 3160a3c758..a1ee1cba21 100644 --- a/lib/gitlab/visibility_level.rb +++ b/lib/gitlab/visibility_level.rb @@ -6,6 +6,14 @@ module Gitlab module VisibilityLevel extend CurrentSettings + extend ActiveSupport::Concern + + included do + scope :public_only, -> { where(visibility_level: PUBLIC) } + scope :public_and_internal_only, -> { where(visibility_level: [PUBLIC, INTERNAL] ) } + + scope :public_to_user, -> (user) { user && !user.external ? public_and_internal_only : public_only } + end PRIVATE = 0 unless const_defined?(:PRIVATE) INTERNAL = 10 unless const_defined?(:INTERNAL) @@ -48,10 +56,6 @@ module Gitlab options.has_value?(level) end - def allowed_fork_levels(origin_level) - [PRIVATE, INTERNAL, PUBLIC].select{ |level| level <= origin_level } - end - def level_name(level) level_name = 'Unknown' options.each do |name, lvl| diff --git a/lib/tasks/gitlab/backup.rake b/lib/tasks/gitlab/backup.rake index cb4abe1379..402bb338f2 100644 --- a/lib/tasks/gitlab/backup.rake +++ b/lib/tasks/gitlab/backup.rake @@ -22,7 +22,7 @@ namespace :gitlab do end # Restore backup of GitLab system - desc "GitLab | Restore a previously created backup" + desc 'GitLab | Restore a previously created backup' task restore: :environment do warn_user_is_not_gitlab configure_cron_mode @@ -30,13 +30,31 @@ namespace :gitlab do backup = Backup::Manager.new backup.unpack - Rake::Task["gitlab:backup:db:restore"].invoke unless backup.skipped?("db") - Rake::Task["gitlab:backup:repo:restore"].invoke unless backup.skipped?("repositories") - Rake::Task["gitlab:backup:uploads:restore"].invoke unless backup.skipped?("uploads") - Rake::Task["gitlab:backup:builds:restore"].invoke unless backup.skipped?("builds") - Rake::Task["gitlab:backup:artifacts:restore"].invoke unless backup.skipped?("artifacts") - Rake::Task["gitlab:backup:lfs:restore"].invoke unless backup.skipped?("lfs") - Rake::Task["gitlab:shell:setup"].invoke + unless backup.skipped?('db') + unless ENV['force'] == 'yes' + warning = warning = <<-MSG.strip_heredoc + Before restoring the database we recommend removing all existing + tables to avoid future upgrade problems. Be aware that if you have + custom tables in the GitLab database these tables and all data will be + removed. + MSG + ask_to_continue + puts 'Removing all tables. Press `Ctrl-C` within 5 seconds to abort'.yellow + sleep(5) + end + # Drop all tables Load the schema to ensure we don't have any newer tables + # hanging out from a failed upgrade + $progress.puts 'Cleaning the database ... '.blue + Rake::Task['gitlab:db:drop_tables'].invoke + $progress.puts 'done'.green + Rake::Task['gitlab:backup:db:restore'].invoke + end + Rake::Task['gitlab:backup:repo:restore'].invoke unless backup.skipped?('repositories') + Rake::Task['gitlab:backup:uploads:restore'].invoke unless backup.skipped?('uploads') + Rake::Task['gitlab:backup:builds:restore'].invoke unless backup.skipped?('builds') + Rake::Task['gitlab:backup:artifacts:restore'].invoke unless backup.skipped?('artifacts') + Rake::Task['gitlab:backup:lfs:restore'].invoke unless backup.skipped?('lfs') + Rake::Task['gitlab:shell:setup'].invoke backup.cleanup end diff --git a/lib/tasks/gitlab/db.rake b/lib/tasks/gitlab/db.rake new file mode 100644 index 0000000000..4921c6e0bc --- /dev/null +++ b/lib/tasks/gitlab/db.rake @@ -0,0 +1,35 @@ +namespace :gitlab do + namespace :db do + desc 'GitLab | Manually insert schema migration version' + task :mark_migration_complete, [:version] => :environment do |_, args| + unless args[:version] + puts "Must specify a migration version as an argument".red + exit 1 + end + + version = args[:version].to_i + if version == 0 + puts "Version '#{args[:version]}' must be a non-zero integer".red + exit 1 + end + + sql = "INSERT INTO schema_migrations (version) VALUES (#{version})" + begin + ActiveRecord::Base.connection.execute(sql) + puts "Successfully marked '#{version}' as complete".green + rescue ActiveRecord::RecordNotUnique + puts "Migration version '#{version}' is already marked complete".yellow + end + end + + desc 'Drop all tables' + task :drop_tables => :environment do + connection = ActiveRecord::Base.connection + tables = connection.tables + tables.delete 'schema_migrations' + # Truncate schema_migrations to ensure migrations re-run + connection.execute('TRUNCATE schema_migrations') + tables.each { |t| connection.execute("DROP TABLE #{t}") } + end + end +end diff --git a/spec/controllers/application_controller_spec.rb b/spec/controllers/application_controller_spec.rb index 55851befc8..186239d309 100644 --- a/spec/controllers/application_controller_spec.rb +++ b/spec/controllers/application_controller_spec.rb @@ -30,44 +30,4 @@ describe ApplicationController do controller.send(:check_password_expiration) end end - - describe 'check labels authorization' do - let(:project) { create(:project) } - let(:user) { create(:user) } - let(:controller) { ApplicationController.new } - - before do - project.team << [user, :guest] - allow(controller).to receive(:current_user).and_return(user) - allow(controller).to receive(:project).and_return(project) - end - - it 'should succeed if issues and MRs are enabled' do - project.issues_enabled = true - project.merge_requests_enabled = true - controller.send(:authorize_read_label!) - expect(response.status).to eq(200) - end - - it 'should succeed if issues are enabled, MRs are disabled' do - project.issues_enabled = true - project.merge_requests_enabled = false - controller.send(:authorize_read_label!) - expect(response.status).to eq(200) - end - - it 'should succeed if issues are disabled, MRs are enabled' do - project.issues_enabled = false - project.merge_requests_enabled = true - controller.send(:authorize_read_label!) - expect(response.status).to eq(200) - end - - it 'should fail if issues and MRs are disabled' do - project.issues_enabled = false - project.merge_requests_enabled = false - expect(controller).to receive(:access_denied!) - controller.send(:authorize_read_label!) - end - end end diff --git a/spec/controllers/groups/avatars_controller_spec.rb b/spec/controllers/groups/avatars_controller_spec.rb index 3dac134a73..91d639218e 100644 --- a/spec/controllers/groups/avatars_controller_spec.rb +++ b/spec/controllers/groups/avatars_controller_spec.rb @@ -2,9 +2,10 @@ require 'spec_helper' describe Groups::AvatarsController do let(:user) { create(:user) } - let(:group) { create(:group, owner: user, avatar: fixture_file_upload(Rails.root + "spec/fixtures/dk.png", "image/png")) } + let(:group) { create(:group, avatar: fixture_file_upload(Rails.root + "spec/fixtures/dk.png", "image/png")) } before do + group.add_owner(user) sign_in(user) end diff --git a/spec/controllers/groups_controller_spec.rb b/spec/controllers/groups_controller_spec.rb index 938e97298b..465531b2b3 100644 --- a/spec/controllers/groups_controller_spec.rb +++ b/spec/controllers/groups_controller_spec.rb @@ -1,10 +1,15 @@ require 'rails_helper' describe GroupsController do - describe 'GET index' do + let(:user) { create(:user) } + let(:group) { create(:group) } + let(:project) { create(:project, namespace: group) } + let!(:group_member) { create(:group_member, group: group, user: user) } + + describe 'GET #index' do context 'as a user' do it 'redirects to Groups Dashboard' do - sign_in(create(:user)) + sign_in(user) get :index @@ -20,4 +25,54 @@ describe GroupsController do end end end + + describe 'GET #issues' do + let(:issue_1) { create(:issue, project: project) } + let(:issue_2) { create(:issue, project: project) } + + before do + create_list(:upvote_note, 3, project: project, noteable: issue_2) + create_list(:upvote_note, 2, project: project, noteable: issue_1) + create_list(:downvote_note, 2, project: project, noteable: issue_2) + + sign_in(user) + end + + context 'sorting by votes' do + it 'sorts most popular issues' do + get :issues, id: group.to_param, sort: 'upvotes_desc' + expect(assigns(:issues)).to eq [issue_2, issue_1] + end + + it 'sorts least popular issues' do + get :issues, id: group.to_param, sort: 'downvotes_desc' + expect(assigns(:issues)).to eq [issue_2, issue_1] + end + end + end + + describe 'GET #merge_requests' do + let(:merge_request_1) { create(:merge_request, source_project: project) } + let(:merge_request_2) { create(:merge_request, :simple, source_project: project) } + + before do + create_list(:upvote_note, 3, project: project, noteable: merge_request_2) + create_list(:upvote_note, 2, project: project, noteable: merge_request_1) + create_list(:downvote_note, 2, project: project, noteable: merge_request_2) + + sign_in(user) + end + + context 'sorting by votes' do + it 'sorts most popular merge requests' do + get :merge_requests, id: group.to_param, sort: 'upvotes_desc' + expect(assigns(:merge_requests)).to eq [merge_request_2, merge_request_1] + end + + it 'sorts least popular merge requests' do + get :merge_requests, id: group.to_param, sort: 'downvotes_desc' + expect(assigns(:merge_requests)).to eq [merge_request_2, merge_request_1] + end + end + end end diff --git a/spec/controllers/namespaces_controller_spec.rb b/spec/controllers/namespaces_controller_spec.rb index 7743695871..27e9afe582 100644 --- a/spec/controllers/namespaces_controller_spec.rb +++ b/spec/controllers/namespaces_controller_spec.rb @@ -15,14 +15,9 @@ describe NamespacesController do end context "when the namespace belongs to a group" do - let!(:group) { create(:group) } - let!(:project) { create(:project, namespace: group) } - - context "when the group has public projects" do - before do - project.update_attribute(:visibility_level, Project::PUBLIC) - end + let!(:group) { create(:group) } + context "when the group is public" do context "when not signed in" do it "redirects to the group's page" do get :show, id: group.path @@ -44,27 +39,31 @@ describe NamespacesController do end end - context "when the project doesn't have public projects" do + context "when the group is private" do + before do + group.update_attribute(:visibility_level, Group::PRIVATE) + end + context "when not signed in" do - it "does not redirect to the sign in page" do + it "redirects to the sign in page" do get :show, id: group.path - expect(response).not_to redirect_to(new_user_session_path) + expect(response).to redirect_to(new_user_session_path) end end + context "when signed in" do before do sign_in(user) end - context "when the user has access to the project" do + context "when the user has access to the group" do before do - project.team << [user, :master] + group.add_developer(user) end context "when the user is blocked" do before do user.block - project.team << [user, :master] end it "redirects to the sign in page" do @@ -83,11 +82,11 @@ describe NamespacesController do end end - context "when the user doesn't have access to the project" do - it "redirects to the group's page" do + context "when the user doesn't have access to the group" do + it "responds with status 404" do get :show, id: group.path - expect(response).to redirect_to(group_path(group)) + expect(response.status).to eq(404) end end end diff --git a/spec/controllers/projects/avatars_controller_spec.rb b/spec/controllers/projects/avatars_controller_spec.rb index e79b46a350..4d724ca9ed 100644 --- a/spec/controllers/projects/avatars_controller_spec.rb +++ b/spec/controllers/projects/avatars_controller_spec.rb @@ -6,7 +6,7 @@ describe Projects::AvatarsController do before do sign_in(user) - project.team << [user, :developer] + project.team << [user, :master] controller.instance_variable_set(:@project, project) end diff --git a/spec/controllers/projects/issues_controller_spec.rb b/spec/controllers/projects/issues_controller_spec.rb index a49bd8960e..d6e4cd71ce 100644 --- a/spec/controllers/projects/issues_controller_spec.rb +++ b/spec/controllers/projects/issues_controller_spec.rb @@ -1,11 +1,11 @@ require('spec_helper') describe Projects::IssuesController do - describe "GET #index" do - let(:project) { create(:project_empty_repo) } - let(:user) { create(:user) } - let(:issue) { create(:issue, project: project) } + let(:project) { create(:project_empty_repo) } + let(:user) { create(:user) } + let(:issue) { create(:issue, project: project) } + describe "GET #index" do before do sign_in(user) project.team << [user, :developer] @@ -186,4 +186,29 @@ describe Projects::IssuesController do end end end + + describe "DELETE #destroy" do + context "when the user is a developer" do + before { sign_in(user) } + it "rejects a developer to destroy an issue" do + delete :destroy, namespace_id: project.namespace.path, project_id: project.path, id: issue.iid + expect(response.status).to eq(404) + end + end + + context "when the user is owner" do + let(:owner) { create(:user) } + let(:namespace) { create(:namespace, owner: owner) } + let(:project) { create(:project, namespace: namespace) } + + before { sign_in(owner) } + + it "deletes the issue" do + delete :destroy, namespace_id: project.namespace.path, project_id: project.path, id: issue.iid + + expect(response.status).to eq(302) + expect(controller).to set_flash[:notice].to(/The issue was successfully deleted\./).now + end + end + end end diff --git a/spec/controllers/projects/merge_requests_controller_spec.rb b/spec/controllers/projects/merge_requests_controller_spec.rb index e82fe26c7a..c5b034dc06 100644 --- a/spec/controllers/projects/merge_requests_controller_spec.rb +++ b/spec/controllers/projects/merge_requests_controller_spec.rb @@ -157,6 +157,29 @@ describe Projects::MergeRequestsController do end end + describe "DELETE #destroy" do + it "denies access to users unless they're admin or project owner" do + delete :destroy, namespace_id: project.namespace.path, project_id: project.path, id: merge_request.iid + + expect(response.status).to eq(404) + end + + context "when the user is owner" do + let(:owner) { create(:user) } + let(:namespace) { create(:namespace, owner: owner) } + let(:project) { create(:project, namespace: namespace) } + + before { sign_in owner } + + it "deletes the merge request" do + delete :destroy, namespace_id: project.namespace.path, project_id: project.path, id: merge_request.iid + + expect(response.status).to eq(302) + expect(controller).to set_flash[:notice].to(/The merge request was successfully deleted\./).now + end + end + end + describe 'GET diffs' do def go(format: 'html') get :diffs, diff --git a/spec/controllers/uploads_controller_spec.rb b/spec/controllers/uploads_controller_spec.rb index af5d043cf0..73858e6f06 100644 --- a/spec/controllers/uploads_controller_spec.rb +++ b/spec/controllers/uploads_controller_spec.rb @@ -30,7 +30,7 @@ describe UploadsController do end end end - + context "when not signed in" do it "responds with status 200" do get :show, model: "user", mounted_as: "avatar", id: user.id, filename: "image.png" @@ -126,14 +126,9 @@ describe UploadsController do end context "when viewing a group avatar" do - let!(:group) { create(:group, avatar: fixture_file_upload(Rails.root + "spec/fixtures/dk.png", "image/png")) } - let!(:project) { create(:project, namespace: group) } - - context "when the group has public projects" do - before do - project.update_attribute(:visibility_level, Project::PUBLIC) - end + let!(:group) { create(:group, avatar: fixture_file_upload(Rails.root + "spec/fixtures/dk.png", "image/png")) } + context "when the group is public" do context "when not signed in" do it "responds with status 200" do get :show, model: "group", mounted_as: "avatar", id: group.id, filename: "image.png" @@ -155,7 +150,11 @@ describe UploadsController do end end - context "when the project doesn't have public projects" do + context "when the group is private" do + before do + group.update_attribute(:visibility_level, Gitlab::VisibilityLevel::PRIVATE) + end + context "when signed in" do before do sign_in(user) @@ -163,13 +162,12 @@ describe UploadsController do context "when the user has access to the project" do before do - project.team << [user, :master] + group.add_developer(user) end context "when the user is blocked" do before do user.block - project.team << [user, :master] end it "redirects to the sign in page" do diff --git a/spec/factories/broadcast_messages.rb b/spec/factories/broadcast_messages.rb index 373ca75467..c80e736655 100644 --- a/spec/factories/broadcast_messages.rb +++ b/spec/factories/broadcast_messages.rb @@ -15,7 +15,7 @@ FactoryGirl.define do factory :broadcast_message do message "MyText" - starts_at Date.today + starts_at Date.yesterday ends_at Date.tomorrow trait :expired do diff --git a/spec/factories/groups.rb b/spec/factories/groups.rb index 4a3a155d7f..2d47a6f6c4 100644 --- a/spec/factories/groups.rb +++ b/spec/factories/groups.rb @@ -3,5 +3,17 @@ FactoryGirl.define do sequence(:name) { |n| "group#{n}" } path { name.downcase.gsub(/\s/, '_') } type 'Group' + + trait :public do + visibility_level Gitlab::VisibilityLevel::PUBLIC + end + + trait :internal do + visibility_level Gitlab::VisibilityLevel::INTERNAL + end + + trait :private do + visibility_level Gitlab::VisibilityLevel::PRIVATE + end end end diff --git a/spec/features/dashboard_milestones_spec.rb b/spec/features/dashboard_milestones_spec.rb new file mode 100644 index 0000000000..f32fddbc9f --- /dev/null +++ b/spec/features/dashboard_milestones_spec.rb @@ -0,0 +1,29 @@ +require 'spec_helper' + +feature 'Dashboard > Milestones', feature: true do + describe 'as anonymous user' do + before do + visit dashboard_milestones_path + end + + it 'is redirected to sign-in page' do + expect(current_path).to eq new_user_session_path + end + end + + describe 'as logged-in user' do + let(:user) { create(:user) } + let(:project) { create(:empty_project, namespace: user.namespace) } + let!(:milestone) { create(:milestone, project: project) } + before do + project.team << [user, :master] + login_with(user) + visit dashboard_milestones_path + end + + it 'sees milestones' do + expect(current_path).to eq dashboard_milestones_path + expect(page).to have_content(milestone.title) + end + end +end diff --git a/spec/features/issues/update_issues_spec.rb b/spec/features/issues/update_issues_spec.rb new file mode 100644 index 0000000000..121954fabc --- /dev/null +++ b/spec/features/issues/update_issues_spec.rb @@ -0,0 +1,117 @@ +require 'rails_helper' + +feature 'Multiple issue updating from issues#index', feature: true do + let!(:project) { create(:project) } + let!(:issue) { create(:issue, project: project) } + let!(:user) { create(:user)} + + before do + project.team << [user, :master] + login_as(user) + end + + context 'status', js: true do + it 'should be set to closed' do + visit namespace_project_issues_path(project.namespace, project) + + find('#check_all_issues').click + find('.js-issue-status').click + + find('.dropdown-menu-status a', text: 'Closed').click + click_update_issues_button + expect(page).to have_selector('.issue', count: 0) + end + + it 'should be set to open' do + create_closed + visit namespace_project_issues_path(project.namespace, project) + + find('.issues-state-filters a', text: 'Closed').click + + find('#check_all_issues').click + find('.js-issue-status').click + + find('.dropdown-menu-status a', text: 'Open').click + click_update_issues_button + expect(page).to have_selector('.issue', count: 0) + end + end + + context 'assignee', js: true do + it 'should update to current user' do + visit namespace_project_issues_path(project.namespace, project) + + find('#check_all_issues').click + find('.js-update-assignee').click + + find('.dropdown-menu-user-link', text: user.username).click + click_update_issues_button + + page.within('.issue .controls') do + expect(find('.author_link')["data-original-title"]).to have_content(user.name) + end + end + + it 'should update to unassigned' do + create_assigned + visit namespace_project_issues_path(project.namespace, project) + + find('#check_all_issues').click + find('.js-update-assignee').click + + find('.dropdown-menu-user-link', text: "Unassigned").click + click_update_issues_button + + within first('.issue .controls') do + expect(page).to have_no_selector('.author_link') + end + end + end + + context 'milestone', js: true do + let(:milestone) { create(:milestone, project: project) } + + it 'should update milestone' do + visit namespace_project_issues_path(project.namespace, project) + + find('#check_all_issues').click + find('.issues_bulk_update .js-milestone-select').click + + find('.dropdown-menu-milestone a', text: milestone.title).click + click_update_issues_button + + expect(find('.issue')).to have_content milestone.title + end + + it 'should set to no milestone' do + create_with_milestone + visit namespace_project_issues_path(project.namespace, project) + + expect(first('.issue')).to have_content milestone.title + + find('#check_all_issues').click + find('.issues_bulk_update .js-milestone-select').click + + find('.dropdown-menu-milestone a', text: "No Milestone").click + click_update_issues_button + + expect(first('.issue')).to_not have_content milestone.title + end + end + + def create_closed + create(:issue, project: project, state: :closed) + end + + def create_assigned + create(:issue, project: project, assignee: user) + end + + def create_with_milestone + create(:issue, project: project, milestone: milestone) + end + + def click_update_issues_button + find('.update_selected_issues').click + end +end diff --git a/spec/features/security/group/internal_access_spec.rb b/spec/features/security/group/internal_access_spec.rb new file mode 100644 index 0000000000..71b783b727 --- /dev/null +++ b/spec/features/security/group/internal_access_spec.rb @@ -0,0 +1,109 @@ +require 'rails_helper' + +describe 'Internal Group access', feature: true do + include AccessMatchers + + let(:group) { create(:group, :internal) } + let(:project) { create(:project, :internal, group: group) } + + let(:owner) { create(:user) } + let(:master) { create(:user) } + let(:developer) { create(:user) } + let(:reporter) { create(:user) } + let(:guest) { create(:user) } + + let(:project_guest) { create(:user) } + + before do + group.add_owner(owner) + group.add_master(master) + group.add_developer(developer) + group.add_reporter(reporter) + group.add_guest(guest) + + project.team << [project_guest, :guest] + end + + describe "Group should be internal" do + describe '#internal?' do + subject { group.internal? } + it { is_expected.to be_truthy } + end + end + + describe 'GET /groups/:path' do + subject { group_path(group) } + + it { is_expected.to be_allowed_for :admin } + it { is_expected.to be_allowed_for owner } + it { is_expected.to be_allowed_for master } + it { is_expected.to be_allowed_for developer } + it { is_expected.to be_allowed_for reporter } + it { is_expected.to be_allowed_for guest } + it { is_expected.to be_allowed_for project_guest } + it { is_expected.to be_allowed_for :user } + it { is_expected.to be_denied_for :external } + it { is_expected.to be_denied_for :visitor } + end + + describe 'GET /groups/:path/issues' do + subject { issues_group_path(group) } + + it { is_expected.to be_allowed_for :admin } + it { is_expected.to be_allowed_for owner } + it { is_expected.to be_allowed_for master } + it { is_expected.to be_allowed_for developer } + it { is_expected.to be_allowed_for reporter } + it { is_expected.to be_allowed_for guest } + it { is_expected.to be_allowed_for project_guest } + it { is_expected.to be_allowed_for :user } + it { is_expected.to be_denied_for :external } + it { is_expected.to be_denied_for :visitor } + end + + describe 'GET /groups/:path/merge_requests' do + subject { merge_requests_group_path(group) } + + it { is_expected.to be_allowed_for :admin } + it { is_expected.to be_allowed_for owner } + it { is_expected.to be_allowed_for master } + it { is_expected.to be_allowed_for developer } + it { is_expected.to be_allowed_for reporter } + it { is_expected.to be_allowed_for guest } + it { is_expected.to be_allowed_for project_guest } + it { is_expected.to be_allowed_for :user } + it { is_expected.to be_denied_for :external } + it { is_expected.to be_denied_for :visitor } + end + + + describe 'GET /groups/:path/group_members' do + subject { group_group_members_path(group) } + + it { is_expected.to be_allowed_for :admin } + it { is_expected.to be_allowed_for owner } + it { is_expected.to be_allowed_for master } + it { is_expected.to be_allowed_for developer } + it { is_expected.to be_allowed_for reporter } + it { is_expected.to be_allowed_for guest } + it { is_expected.to be_allowed_for project_guest } + it { is_expected.to be_allowed_for :user } + it { is_expected.to be_denied_for :external } + it { is_expected.to be_denied_for :visitor } + end + + describe 'GET /groups/:path/edit' do + subject { edit_group_path(group) } + + it { is_expected.to be_allowed_for :admin } + it { is_expected.to be_allowed_for owner } + it { is_expected.to be_denied_for master } + it { is_expected.to be_denied_for developer } + it { is_expected.to be_denied_for reporter } + it { is_expected.to be_denied_for guest } + it { is_expected.to be_denied_for project_guest } + it { is_expected.to be_denied_for :user } + it { is_expected.to be_denied_for :visitor } + it { is_expected.to be_denied_for :external } + end +end diff --git a/spec/features/security/group/private_access_spec.rb b/spec/features/security/group/private_access_spec.rb new file mode 100644 index 0000000000..cc9aee802f --- /dev/null +++ b/spec/features/security/group/private_access_spec.rb @@ -0,0 +1,109 @@ +require 'rails_helper' + +describe 'Private Group access', feature: true do + include AccessMatchers + + let(:group) { create(:group, :private) } + let(:project) { create(:project, :private, group: group) } + + let(:owner) { create(:user) } + let(:master) { create(:user) } + let(:developer) { create(:user) } + let(:reporter) { create(:user) } + let(:guest) { create(:user) } + + let(:project_guest) { create(:user) } + + before do + group.add_owner(owner) + group.add_master(master) + group.add_developer(developer) + group.add_reporter(reporter) + group.add_guest(guest) + + project.team << [project_guest, :guest] + end + + describe "Group should be private" do + describe '#private?' do + subject { group.private? } + it { is_expected.to be_truthy } + end + end + + describe 'GET /groups/:path' do + subject { group_path(group) } + + it { is_expected.to be_allowed_for :admin } + it { is_expected.to be_allowed_for owner } + it { is_expected.to be_allowed_for master } + it { is_expected.to be_allowed_for developer } + it { is_expected.to be_allowed_for reporter } + it { is_expected.to be_allowed_for guest } + it { is_expected.to be_allowed_for project_guest } + it { is_expected.to be_denied_for :user } + it { is_expected.to be_denied_for :external } + it { is_expected.to be_denied_for :visitor } + end + + describe 'GET /groups/:path/issues' do + subject { issues_group_path(group) } + + it { is_expected.to be_allowed_for :admin } + it { is_expected.to be_allowed_for owner } + it { is_expected.to be_allowed_for master } + it { is_expected.to be_allowed_for developer } + it { is_expected.to be_allowed_for reporter } + it { is_expected.to be_allowed_for guest } + it { is_expected.to be_allowed_for project_guest } + it { is_expected.to be_denied_for :user } + it { is_expected.to be_denied_for :external } + it { is_expected.to be_denied_for :visitor } + end + + describe 'GET /groups/:path/merge_requests' do + subject { merge_requests_group_path(group) } + + it { is_expected.to be_allowed_for :admin } + it { is_expected.to be_allowed_for owner } + it { is_expected.to be_allowed_for master } + it { is_expected.to be_allowed_for developer } + it { is_expected.to be_allowed_for reporter } + it { is_expected.to be_allowed_for guest } + it { is_expected.to be_allowed_for project_guest } + it { is_expected.to be_denied_for :user } + it { is_expected.to be_denied_for :external } + it { is_expected.to be_denied_for :visitor } + end + + + describe 'GET /groups/:path/group_members' do + subject { group_group_members_path(group) } + + it { is_expected.to be_allowed_for :admin } + it { is_expected.to be_allowed_for owner } + it { is_expected.to be_allowed_for master } + it { is_expected.to be_allowed_for developer } + it { is_expected.to be_allowed_for reporter } + it { is_expected.to be_allowed_for guest } + it { is_expected.to be_allowed_for project_guest } + it { is_expected.to be_denied_for :user } + it { is_expected.to be_denied_for :external } + it { is_expected.to be_denied_for :visitor } + end + + describe 'GET /groups/:path/edit' do + subject { edit_group_path(group) } + + it { is_expected.to be_allowed_for :admin } + it { is_expected.to be_allowed_for owner } + it { is_expected.to be_denied_for master } + it { is_expected.to be_denied_for developer } + it { is_expected.to be_denied_for reporter } + it { is_expected.to be_denied_for guest } + it { is_expected.to be_denied_for project_guest } + it { is_expected.to be_denied_for :user } + it { is_expected.to be_denied_for :visitor } + it { is_expected.to be_denied_for :external } + end +end diff --git a/spec/features/security/group/public_access_spec.rb b/spec/features/security/group/public_access_spec.rb new file mode 100644 index 0000000000..db986683db --- /dev/null +++ b/spec/features/security/group/public_access_spec.rb @@ -0,0 +1,109 @@ +require 'rails_helper' + +describe 'Public Group access', feature: true do + include AccessMatchers + + let(:group) { create(:group, :public) } + let(:project) { create(:project, :public, group: group) } + + let(:owner) { create(:user) } + let(:master) { create(:user) } + let(:developer) { create(:user) } + let(:reporter) { create(:user) } + let(:guest) { create(:user) } + + let(:project_guest) { create(:user) } + + before do + group.add_owner(owner) + group.add_master(master) + group.add_developer(developer) + group.add_reporter(reporter) + group.add_guest(guest) + + project.team << [project_guest, :guest] + end + + describe "Group should be public" do + describe '#public?' do + subject { group.public? } + it { is_expected.to be_truthy } + end + end + + describe 'GET /groups/:path' do + subject { group_path(group) } + + it { is_expected.to be_allowed_for :admin } + it { is_expected.to be_allowed_for owner } + it { is_expected.to be_allowed_for master } + it { is_expected.to be_allowed_for developer } + it { is_expected.to be_allowed_for reporter } + it { is_expected.to be_allowed_for guest } + it { is_expected.to be_allowed_for project_guest } + it { is_expected.to be_allowed_for :user } + it { is_expected.to be_allowed_for :external } + it { is_expected.to be_allowed_for :visitor } + end + + describe 'GET /groups/:path/issues' do + subject { issues_group_path(group) } + + it { is_expected.to be_allowed_for :admin } + it { is_expected.to be_allowed_for owner } + it { is_expected.to be_allowed_for master } + it { is_expected.to be_allowed_for developer } + it { is_expected.to be_allowed_for reporter } + it { is_expected.to be_allowed_for guest } + it { is_expected.to be_allowed_for project_guest } + it { is_expected.to be_allowed_for :user } + it { is_expected.to be_allowed_for :external } + it { is_expected.to be_allowed_for :visitor } + end + + describe 'GET /groups/:path/merge_requests' do + subject { merge_requests_group_path(group) } + + it { is_expected.to be_allowed_for :admin } + it { is_expected.to be_allowed_for owner } + it { is_expected.to be_allowed_for master } + it { is_expected.to be_allowed_for developer } + it { is_expected.to be_allowed_for reporter } + it { is_expected.to be_allowed_for guest } + it { is_expected.to be_allowed_for project_guest } + it { is_expected.to be_allowed_for :user } + it { is_expected.to be_allowed_for :external } + it { is_expected.to be_allowed_for :visitor } + end + + + describe 'GET /groups/:path/group_members' do + subject { group_group_members_path(group) } + + it { is_expected.to be_allowed_for :admin } + it { is_expected.to be_allowed_for owner } + it { is_expected.to be_allowed_for master } + it { is_expected.to be_allowed_for developer } + it { is_expected.to be_allowed_for reporter } + it { is_expected.to be_allowed_for guest } + it { is_expected.to be_allowed_for project_guest } + it { is_expected.to be_allowed_for :user } + it { is_expected.to be_allowed_for :external } + it { is_expected.to be_allowed_for :visitor } + end + + describe 'GET /groups/:path/edit' do + subject { edit_group_path(group) } + + it { is_expected.to be_allowed_for :admin } + it { is_expected.to be_allowed_for owner } + it { is_expected.to be_denied_for master } + it { is_expected.to be_denied_for developer } + it { is_expected.to be_denied_for reporter } + it { is_expected.to be_denied_for guest } + it { is_expected.to be_denied_for project_guest } + it { is_expected.to be_denied_for :user } + it { is_expected.to be_denied_for :visitor } + it { is_expected.to be_denied_for :external } + end +end diff --git a/spec/features/security/group_access_spec.rb b/spec/features/security/group_access_spec.rb deleted file mode 100644 index 65f8073c69..0000000000 --- a/spec/features/security/group_access_spec.rb +++ /dev/null @@ -1,284 +0,0 @@ -require 'rails_helper' - -describe 'Group access', feature: true do - include AccessMatchers - - def group - @group ||= create(:group) - end - - def create_project(access_level) - if access_level == :mixed - create(:empty_project, :public, group: group) - create(:empty_project, :internal, group: group) - else - create(:empty_project, access_level, group: group) - end - end - - def group_member(access_level, grp = group()) - level = Object.const_get("Gitlab::Access::#{access_level.upcase}") - - create(:user).tap do |user| - grp.add_user(user, level) - end - end - - describe 'GET /groups/new' do - subject { new_group_path } - - it { is_expected.to be_allowed_for :admin } - it { is_expected.to be_allowed_for :user } - it { is_expected.to be_denied_for :visitor } - end - - describe 'GET /groups/:path' do - subject { group_path(group) } - - context 'with public projects' do - let!(:project) { create_project(:public) } - - it { is_expected.to be_allowed_for group_member(:owner) } - it { is_expected.to be_allowed_for group_member(:master) } - it { is_expected.to be_allowed_for group_member(:reporter) } - it { is_expected.to be_allowed_for group_member(:guest) } - it { is_expected.to be_allowed_for :admin } - it { is_expected.to be_allowed_for :user } - it { is_expected.to be_allowed_for :visitor } - end - - context 'with mixed projects' do - let!(:project) { create_project(:mixed) } - - it { is_expected.to be_allowed_for group_member(:owner) } - it { is_expected.to be_allowed_for group_member(:master) } - it { is_expected.to be_allowed_for group_member(:reporter) } - it { is_expected.to be_allowed_for group_member(:guest) } - it { is_expected.to be_allowed_for :admin } - it { is_expected.to be_allowed_for :user } - it { is_expected.to be_allowed_for :visitor } - end - - context 'with internal projects' do - let!(:project) { create_project(:internal) } - - it { is_expected.to be_allowed_for group_member(:owner) } - it { is_expected.to be_allowed_for group_member(:master) } - it { is_expected.to be_allowed_for group_member(:reporter) } - it { is_expected.to be_allowed_for group_member(:guest) } - it { is_expected.to be_allowed_for :admin } - it { is_expected.to be_allowed_for :user } - it { is_expected.to be_allowed_for :visitor } - end - - context 'with no projects' do - it { is_expected.to be_allowed_for group_member(:owner) } - it { is_expected.to be_allowed_for group_member(:master) } - it { is_expected.to be_allowed_for group_member(:reporter) } - it { is_expected.to be_allowed_for group_member(:guest) } - it { is_expected.to be_allowed_for :admin } - it { is_expected.to be_allowed_for :user } - it { is_expected.to be_allowed_for :visitor } - end - end - - describe 'GET /groups/:path/issues' do - subject { issues_group_path(group) } - - context 'with public projects' do - let!(:project) { create_project(:public) } - - it { is_expected.to be_allowed_for group_member(:owner) } - it { is_expected.to be_allowed_for group_member(:master) } - it { is_expected.to be_allowed_for group_member(:reporter) } - it { is_expected.to be_allowed_for group_member(:guest) } - it { is_expected.to be_allowed_for :admin } - it { is_expected.to be_allowed_for :user } - it { is_expected.to be_allowed_for :visitor } - end - - context 'with mixed projects' do - let!(:project) { create_project(:mixed) } - - it { is_expected.to be_allowed_for group_member(:owner) } - it { is_expected.to be_allowed_for group_member(:master) } - it { is_expected.to be_allowed_for group_member(:reporter) } - it { is_expected.to be_allowed_for group_member(:guest) } - it { is_expected.to be_allowed_for :admin } - it { is_expected.to be_allowed_for :user } - it { is_expected.to be_allowed_for :visitor } - end - - context 'with internal projects' do - let!(:project) { create_project(:internal) } - - it { is_expected.to be_allowed_for group_member(:owner) } - it { is_expected.to be_allowed_for group_member(:master) } - it { is_expected.to be_allowed_for group_member(:reporter) } - it { is_expected.to be_allowed_for group_member(:guest) } - it { is_expected.to be_allowed_for :admin } - it { is_expected.to be_allowed_for :user } - it { is_expected.to be_denied_for :visitor } - end - - context 'with no projects' do - it { is_expected.to be_allowed_for group_member(:owner) } - it { is_expected.to be_allowed_for group_member(:master) } - it { is_expected.to be_allowed_for group_member(:reporter) } - it { is_expected.to be_allowed_for group_member(:guest) } - it { is_expected.to be_allowed_for :admin } - it { is_expected.to be_denied_for :user } - it { is_expected.to be_denied_for :visitor } - end - end - - describe 'GET /groups/:path/merge_requests' do - subject { merge_requests_group_path(group) } - - context 'with public projects' do - let!(:project) { create_project(:public) } - - it { is_expected.to be_allowed_for group_member(:owner) } - it { is_expected.to be_allowed_for group_member(:master) } - it { is_expected.to be_allowed_for group_member(:reporter) } - it { is_expected.to be_allowed_for group_member(:guest) } - it { is_expected.to be_allowed_for :admin } - it { is_expected.to be_allowed_for :user } - it { is_expected.to be_allowed_for :visitor } - end - - context 'with mixed projects' do - let!(:project) { create_project(:mixed) } - - it { is_expected.to be_allowed_for group_member(:owner) } - it { is_expected.to be_allowed_for group_member(:master) } - it { is_expected.to be_allowed_for group_member(:reporter) } - it { is_expected.to be_allowed_for group_member(:guest) } - it { is_expected.to be_allowed_for :admin } - it { is_expected.to be_allowed_for :user } - it { is_expected.to be_allowed_for :visitor } - end - - context 'with internal projects' do - let!(:project) { create_project(:internal) } - - it { is_expected.to be_allowed_for group_member(:owner) } - it { is_expected.to be_allowed_for group_member(:master) } - it { is_expected.to be_allowed_for group_member(:reporter) } - it { is_expected.to be_allowed_for group_member(:guest) } - it { is_expected.to be_allowed_for :admin } - it { is_expected.to be_allowed_for :user } - it { is_expected.to be_denied_for :visitor } - end - - context 'with no projects' do - it { is_expected.to be_allowed_for group_member(:owner) } - it { is_expected.to be_allowed_for group_member(:master) } - it { is_expected.to be_allowed_for group_member(:reporter) } - it { is_expected.to be_allowed_for group_member(:guest) } - it { is_expected.to be_allowed_for :admin } - it { is_expected.to be_denied_for :user } - it { is_expected.to be_denied_for :visitor } - end - end - - describe 'GET /groups/:path/group_members' do - subject { group_group_members_path(group) } - - context 'with public projects' do - let!(:project) { create_project(:public) } - - it { is_expected.to be_allowed_for group_member(:owner) } - it { is_expected.to be_allowed_for group_member(:master) } - it { is_expected.to be_allowed_for group_member(:reporter) } - it { is_expected.to be_allowed_for group_member(:guest) } - it { is_expected.to be_allowed_for :admin } - it { is_expected.to be_allowed_for :user } - it { is_expected.to be_allowed_for :visitor } - end - - context 'with mixed projects' do - let!(:project) { create_project(:mixed) } - - it { is_expected.to be_allowed_for group_member(:owner) } - it { is_expected.to be_allowed_for group_member(:master) } - it { is_expected.to be_allowed_for group_member(:reporter) } - it { is_expected.to be_allowed_for group_member(:guest) } - it { is_expected.to be_allowed_for :admin } - it { is_expected.to be_allowed_for :user } - it { is_expected.to be_allowed_for :visitor } - end - - context 'with internal projects' do - let!(:project) { create_project(:internal) } - - it { is_expected.to be_allowed_for group_member(:owner) } - it { is_expected.to be_allowed_for group_member(:master) } - it { is_expected.to be_allowed_for group_member(:reporter) } - it { is_expected.to be_allowed_for group_member(:guest) } - it { is_expected.to be_allowed_for :admin } - it { is_expected.to be_allowed_for :user } - it { is_expected.to be_denied_for :visitor } - end - - context 'with no projects' do - it { is_expected.to be_allowed_for group_member(:owner) } - it { is_expected.to be_allowed_for group_member(:master) } - it { is_expected.to be_allowed_for group_member(:reporter) } - it { is_expected.to be_allowed_for group_member(:guest) } - it { is_expected.to be_allowed_for :admin } - it { is_expected.to be_denied_for :user } - it { is_expected.to be_denied_for :visitor } - end - end - - describe 'GET /groups/:path/edit' do - subject { edit_group_path(group) } - - context 'with public projects' do - let!(:project) { create_project(:public) } - - it { is_expected.to be_allowed_for group_member(:owner) } - it { is_expected.to be_denied_for group_member(:master) } - it { is_expected.to be_denied_for group_member(:reporter) } - it { is_expected.to be_denied_for group_member(:guest) } - it { is_expected.to be_allowed_for :admin } - it { is_expected.to be_denied_for :user } - it { is_expected.to be_denied_for :visitor } - end - - context 'with mixed projects' do - let!(:project) { create_project(:mixed) } - - it { is_expected.to be_allowed_for group_member(:owner) } - it { is_expected.to be_denied_for group_member(:master) } - it { is_expected.to be_denied_for group_member(:reporter) } - it { is_expected.to be_denied_for group_member(:guest) } - it { is_expected.to be_allowed_for :admin } - it { is_expected.to be_denied_for :user } - it { is_expected.to be_denied_for :visitor } - end - - context 'with internal projects' do - let!(:project) { create_project(:internal) } - - it { is_expected.to be_allowed_for group_member(:owner) } - it { is_expected.to be_denied_for group_member(:master) } - it { is_expected.to be_denied_for group_member(:reporter) } - it { is_expected.to be_denied_for group_member(:guest) } - it { is_expected.to be_allowed_for :admin } - it { is_expected.to be_denied_for :user } - it { is_expected.to be_denied_for :visitor } - end - - context 'with no projects' do - it { is_expected.to be_allowed_for group_member(:owner) } - it { is_expected.to be_denied_for group_member(:master) } - it { is_expected.to be_denied_for group_member(:reporter) } - it { is_expected.to be_denied_for group_member(:guest) } - it { is_expected.to be_allowed_for :admin } - it { is_expected.to be_denied_for :user } - it { is_expected.to be_denied_for :visitor } - end - end -end diff --git a/spec/features/security/project/internal_access_spec.rb b/spec/features/security/project/internal_access_spec.rb index f88c591d89..79d5bf4cf0 100644 --- a/spec/features/security/project/internal_access_spec.rb +++ b/spec/features/security/project/internal_access_spec.rb @@ -5,25 +5,22 @@ describe "Internal Project Access", feature: true do let(:project) { create(:project, :internal) } - let(:master) { create(:user) } - let(:guest) { create(:user) } - let(:reporter) { create(:user) } - let(:external_team_member) { create(:user, external: true) } + let(:owner) { project.owner } + let(:master) { create(:user) } + let(:developer) { create(:user) } + let(:reporter) { create(:user) } + let(:guest) { create(:user) } before do - # full access project.team << [master, :master] - project.team << [external_team_member, :master] - - # readonly + project.team << [developer, :developer] project.team << [reporter, :reporter] + project.team << [guest, :guest] end describe "Project should be internal" do - subject { project } - describe '#internal?' do - subject { super().internal? } + subject { project.internal? } it { is_expected.to be_truthy } end end @@ -31,78 +28,84 @@ describe "Internal Project Access", feature: true do describe "GET /:project_path" do subject { namespace_project_path(project.namespace, project) } - it { is_expected.to be_allowed_for master } - it { is_expected.to be_allowed_for reporter } it { is_expected.to be_allowed_for :admin } + it { is_expected.to be_allowed_for owner } + it { is_expected.to be_allowed_for master } + it { is_expected.to be_allowed_for developer } + it { is_expected.to be_allowed_for reporter } it { is_expected.to be_allowed_for guest } it { is_expected.to be_allowed_for :user } it { is_expected.to be_denied_for :external } - it { is_expected.to be_allowed_for external_team_member } it { is_expected.to be_denied_for :visitor } end describe "GET /:project_path/tree/master" do subject { namespace_project_tree_path(project.namespace, project, project.repository.root_ref) } - it { is_expected.to be_allowed_for master } - it { is_expected.to be_allowed_for reporter } it { is_expected.to be_allowed_for :admin } + it { is_expected.to be_allowed_for owner } + it { is_expected.to be_allowed_for master } + it { is_expected.to be_allowed_for developer } + it { is_expected.to be_allowed_for reporter } it { is_expected.to be_allowed_for guest } it { is_expected.to be_allowed_for :user } it { is_expected.to be_denied_for :external } - it { is_expected.to be_allowed_for external_team_member } it { is_expected.to be_denied_for :visitor } end describe "GET /:project_path/commits/master" do subject { namespace_project_commits_path(project.namespace, project, project.repository.root_ref, limit: 1) } - it { is_expected.to be_allowed_for master } - it { is_expected.to be_allowed_for reporter } it { is_expected.to be_allowed_for :admin } + it { is_expected.to be_allowed_for owner } + it { is_expected.to be_allowed_for master } + it { is_expected.to be_allowed_for developer } + it { is_expected.to be_allowed_for reporter } it { is_expected.to be_allowed_for guest } it { is_expected.to be_allowed_for :user } it { is_expected.to be_denied_for :external } - it { is_expected.to be_allowed_for external_team_member } it { is_expected.to be_denied_for :visitor } end describe "GET /:project_path/commit/:sha" do subject { namespace_project_commit_path(project.namespace, project, project.repository.commit) } - it { is_expected.to be_allowed_for master } - it { is_expected.to be_allowed_for reporter } it { is_expected.to be_allowed_for :admin } + it { is_expected.to be_allowed_for owner } + it { is_expected.to be_allowed_for master } + it { is_expected.to be_allowed_for developer } + it { is_expected.to be_allowed_for reporter } it { is_expected.to be_allowed_for guest } it { is_expected.to be_allowed_for :user } it { is_expected.to be_denied_for :external } - it { is_expected.to be_allowed_for external_team_member } it { is_expected.to be_denied_for :visitor } end describe "GET /:project_path/compare" do subject { namespace_project_compare_index_path(project.namespace, project) } - it { is_expected.to be_allowed_for master } - it { is_expected.to be_allowed_for reporter } it { is_expected.to be_allowed_for :admin } + it { is_expected.to be_allowed_for owner } + it { is_expected.to be_allowed_for master } + it { is_expected.to be_allowed_for developer } + it { is_expected.to be_allowed_for reporter } it { is_expected.to be_allowed_for guest } it { is_expected.to be_allowed_for :user } it { is_expected.to be_denied_for :external } - it { is_expected.to be_allowed_for external_team_member } it { is_expected.to be_denied_for :visitor } end describe "GET /:project_path/project_members" do subject { namespace_project_project_members_path(project.namespace, project) } - it { is_expected.to be_allowed_for master } - it { is_expected.to be_denied_for reporter } it { is_expected.to be_allowed_for :admin } + it { is_expected.to be_allowed_for owner } + it { is_expected.to be_allowed_for master } + it { is_expected.to be_denied_for developer } + it { is_expected.to be_denied_for reporter } it { is_expected.to be_denied_for guest } it { is_expected.to be_denied_for :user } it { is_expected.to be_denied_for :external } - it { is_expected.to be_allowed_for external_team_member } it { is_expected.to be_denied_for :visitor } end @@ -110,52 +113,56 @@ describe "Internal Project Access", feature: true do let(:commit) { project.repository.commit } subject { namespace_project_blob_path(project.namespace, project, File.join(commit.id, '.gitignore')) } - it { is_expected.to be_allowed_for master } - it { is_expected.to be_allowed_for reporter } it { is_expected.to be_allowed_for :admin } + it { is_expected.to be_allowed_for owner } + it { is_expected.to be_allowed_for master } + it { is_expected.to be_allowed_for developer } + it { is_expected.to be_allowed_for reporter } it { is_expected.to be_allowed_for guest } it { is_expected.to be_allowed_for :user } it { is_expected.to be_denied_for :external } - it { is_expected.to be_allowed_for external_team_member } it { is_expected.to be_denied_for :visitor } end describe "GET /:project_path/edit" do subject { edit_namespace_project_path(project.namespace, project) } - it { is_expected.to be_allowed_for master } - it { is_expected.to be_denied_for reporter } it { is_expected.to be_allowed_for :admin } + it { is_expected.to be_allowed_for owner } + it { is_expected.to be_allowed_for master } + it { is_expected.to be_denied_for developer } + it { is_expected.to be_denied_for reporter } it { is_expected.to be_denied_for guest } it { is_expected.to be_denied_for :user } it { is_expected.to be_denied_for :external } - it { is_expected.to be_allowed_for external_team_member } it { is_expected.to be_denied_for :visitor } end describe "GET /:project_path/deploy_keys" do subject { namespace_project_deploy_keys_path(project.namespace, project) } - it { is_expected.to be_allowed_for master } - it { is_expected.to be_denied_for reporter } it { is_expected.to be_allowed_for :admin } + it { is_expected.to be_allowed_for owner } + it { is_expected.to be_allowed_for master } + it { is_expected.to be_denied_for developer } + it { is_expected.to be_denied_for reporter } it { is_expected.to be_denied_for guest } it { is_expected.to be_denied_for :user } it { is_expected.to be_denied_for :external } - it { is_expected.to be_allowed_for external_team_member } it { is_expected.to be_denied_for :visitor } end describe "GET /:project_path/issues" do subject { namespace_project_issues_path(project.namespace, project) } - it { is_expected.to be_allowed_for master } - it { is_expected.to be_allowed_for reporter } it { is_expected.to be_allowed_for :admin } + it { is_expected.to be_allowed_for owner } + it { is_expected.to be_allowed_for master } + it { is_expected.to be_allowed_for developer } + it { is_expected.to be_allowed_for reporter } it { is_expected.to be_allowed_for guest } it { is_expected.to be_allowed_for :user } it { is_expected.to be_denied_for :external } - it { is_expected.to be_allowed_for external_team_member } it { is_expected.to be_denied_for :visitor } end @@ -163,65 +170,70 @@ describe "Internal Project Access", feature: true do let(:issue) { create(:issue, project: project) } subject { edit_namespace_project_issue_path(project.namespace, project, issue) } - it { is_expected.to be_allowed_for master } - it { is_expected.to be_allowed_for reporter } it { is_expected.to be_allowed_for :admin } + it { is_expected.to be_allowed_for owner } + it { is_expected.to be_allowed_for master } + it { is_expected.to be_allowed_for developer } + it { is_expected.to be_allowed_for reporter } it { is_expected.to be_denied_for guest } it { is_expected.to be_denied_for :user } it { is_expected.to be_denied_for :external } - it { is_expected.to be_allowed_for external_team_member } it { is_expected.to be_denied_for :visitor } end describe "GET /:project_path/snippets" do subject { namespace_project_snippets_path(project.namespace, project) } - it { is_expected.to be_allowed_for master } - it { is_expected.to be_allowed_for reporter } it { is_expected.to be_allowed_for :admin } + it { is_expected.to be_allowed_for owner } + it { is_expected.to be_allowed_for master } + it { is_expected.to be_allowed_for developer } + it { is_expected.to be_allowed_for reporter } it { is_expected.to be_allowed_for guest } it { is_expected.to be_allowed_for :user } it { is_expected.to be_denied_for :external } - it { is_expected.to be_allowed_for external_team_member } it { is_expected.to be_denied_for :visitor } end describe "GET /:project_path/snippets/new" do subject { new_namespace_project_snippet_path(project.namespace, project) } - it { is_expected.to be_allowed_for master } - it { is_expected.to be_allowed_for reporter } it { is_expected.to be_allowed_for :admin } + it { is_expected.to be_allowed_for owner } + it { is_expected.to be_allowed_for master } + it { is_expected.to be_allowed_for developer } + it { is_expected.to be_allowed_for reporter } it { is_expected.to be_denied_for guest } it { is_expected.to be_denied_for :user } it { is_expected.to be_denied_for :external } - it { is_expected.to be_allowed_for external_team_member } it { is_expected.to be_denied_for :visitor } end describe "GET /:project_path/merge_requests" do subject { namespace_project_merge_requests_path(project.namespace, project) } - it { is_expected.to be_allowed_for master } - it { is_expected.to be_allowed_for reporter } it { is_expected.to be_allowed_for :admin } + it { is_expected.to be_allowed_for owner } + it { is_expected.to be_allowed_for master } + it { is_expected.to be_allowed_for developer } + it { is_expected.to be_allowed_for reporter } it { is_expected.to be_allowed_for guest } it { is_expected.to be_allowed_for :user } it { is_expected.to be_denied_for :external } - it { is_expected.to be_allowed_for external_team_member } it { is_expected.to be_denied_for :visitor } end describe "GET /:project_path/merge_requests/new" do subject { new_namespace_project_merge_request_path(project.namespace, project) } - it { is_expected.to be_allowed_for master } - it { is_expected.to be_denied_for reporter } it { is_expected.to be_allowed_for :admin } + it { is_expected.to be_allowed_for owner } + it { is_expected.to be_allowed_for master } + it { is_expected.to be_allowed_for developer } + it { is_expected.to be_denied_for reporter } it { is_expected.to be_denied_for guest } it { is_expected.to be_denied_for :user } it { is_expected.to be_denied_for :external } - it { is_expected.to be_allowed_for external_team_member } it { is_expected.to be_denied_for :visitor } end @@ -233,13 +245,14 @@ describe "Internal Project Access", feature: true do allow_any_instance_of(Project).to receive(:branches).and_return([]) end - it { is_expected.to be_allowed_for master } - it { is_expected.to be_allowed_for reporter } it { is_expected.to be_allowed_for :admin } + it { is_expected.to be_allowed_for owner } + it { is_expected.to be_allowed_for master } + it { is_expected.to be_allowed_for developer } + it { is_expected.to be_allowed_for reporter } it { is_expected.to be_allowed_for guest } it { is_expected.to be_allowed_for :user } it { is_expected.to be_denied_for :external } - it { is_expected.to be_allowed_for external_team_member } it { is_expected.to be_denied_for :visitor } end @@ -251,26 +264,28 @@ describe "Internal Project Access", feature: true do allow_any_instance_of(Project).to receive(:tags).and_return([]) end - it { is_expected.to be_allowed_for master } - it { is_expected.to be_allowed_for reporter } it { is_expected.to be_allowed_for :admin } + it { is_expected.to be_allowed_for owner } + it { is_expected.to be_allowed_for master } + it { is_expected.to be_allowed_for developer } + it { is_expected.to be_allowed_for reporter } it { is_expected.to be_allowed_for guest } it { is_expected.to be_allowed_for :user } it { is_expected.to be_denied_for :external } - it { is_expected.to be_allowed_for external_team_member } it { is_expected.to be_denied_for :visitor } end describe "GET /:project_path/hooks" do subject { namespace_project_hooks_path(project.namespace, project) } - it { is_expected.to be_allowed_for master } - it { is_expected.to be_denied_for reporter } it { is_expected.to be_allowed_for :admin } + it { is_expected.to be_allowed_for owner } + it { is_expected.to be_allowed_for master } + it { is_expected.to be_denied_for developer } + it { is_expected.to be_denied_for reporter } it { is_expected.to be_denied_for guest } it { is_expected.to be_denied_for :user } it { is_expected.to be_denied_for :external } - it { is_expected.to be_allowed_for external_team_member } it { is_expected.to be_denied_for :visitor } end end diff --git a/spec/features/security/project/private_access_spec.rb b/spec/features/security/project/private_access_spec.rb index 19f287ce7a..0a89193eb6 100644 --- a/spec/features/security/project/private_access_spec.rb +++ b/spec/features/security/project/private_access_spec.rb @@ -3,27 +3,24 @@ require 'spec_helper' describe "Private Project Access", feature: true do include AccessMatchers - let(:project) { create(:project) } + let(:project) { create(:project, :private) } - let(:master) { create(:user) } - let(:guest) { create(:user) } - let(:reporter) { create(:user) } - let(:external_team_member) { create(:user, external: true) } + let(:owner) { project.owner } + let(:master) { create(:user) } + let(:developer) { create(:user) } + let(:reporter) { create(:user) } + let(:guest) { create(:user) } before do - # full access project.team << [master, :master] - project.team << [external_team_member, :master] - - # readonly + project.team << [developer, :developer] project.team << [reporter, :reporter] + project.team << [guest, :guest] end describe "Project should be private" do - subject { project } - describe '#private?' do - subject { super().private? } + subject { project.private? } it { is_expected.to be_truthy } end end @@ -31,77 +28,84 @@ describe "Private Project Access", feature: true do describe "GET /:project_path" do subject { namespace_project_path(project.namespace, project) } - it { is_expected.to be_allowed_for master } - it { is_expected.to be_allowed_for reporter } it { is_expected.to be_allowed_for :admin } - it { is_expected.to be_denied_for guest } + it { is_expected.to be_allowed_for owner } + it { is_expected.to be_allowed_for master } + it { is_expected.to be_allowed_for developer } + it { is_expected.to be_allowed_for reporter } + it { is_expected.to be_allowed_for guest } it { is_expected.to be_denied_for :user } it { is_expected.to be_denied_for :external } - it { is_expected.to be_allowed_for external_team_member } it { is_expected.to be_denied_for :visitor } end describe "GET /:project_path/tree/master" do subject { namespace_project_tree_path(project.namespace, project, project.repository.root_ref) } - it { is_expected.to be_allowed_for master } - it { is_expected.to be_allowed_for reporter } it { is_expected.to be_allowed_for :admin } + it { is_expected.to be_allowed_for owner } + it { is_expected.to be_allowed_for master } + it { is_expected.to be_allowed_for developer } + it { is_expected.to be_allowed_for reporter } it { is_expected.to be_denied_for guest } it { is_expected.to be_denied_for :user } it { is_expected.to be_denied_for :external } - it { is_expected.to be_allowed_for external_team_member } it { is_expected.to be_denied_for :visitor } end describe "GET /:project_path/commits/master" do subject { namespace_project_commits_path(project.namespace, project, project.repository.root_ref, limit: 1) } - it { is_expected.to be_allowed_for master } - it { is_expected.to be_allowed_for reporter } it { is_expected.to be_allowed_for :admin } + it { is_expected.to be_allowed_for owner } + it { is_expected.to be_allowed_for master } + it { is_expected.to be_allowed_for developer } + it { is_expected.to be_allowed_for reporter } it { is_expected.to be_denied_for guest } it { is_expected.to be_denied_for :user } it { is_expected.to be_denied_for :external } - it { is_expected.to be_allowed_for external_team_member } it { is_expected.to be_denied_for :visitor } end describe "GET /:project_path/commit/:sha" do subject { namespace_project_commit_path(project.namespace, project, project.repository.commit) } - it { is_expected.to be_allowed_for master } - it { is_expected.to be_allowed_for reporter } it { is_expected.to be_allowed_for :admin } + it { is_expected.to be_allowed_for owner } + it { is_expected.to be_allowed_for master } + it { is_expected.to be_allowed_for developer } + it { is_expected.to be_allowed_for reporter } it { is_expected.to be_denied_for guest } it { is_expected.to be_denied_for :user } - it { is_expected.to be_allowed_for external_team_member } + it { is_expected.to be_denied_for :external } it { is_expected.to be_denied_for :visitor } end describe "GET /:project_path/compare" do subject { namespace_project_compare_index_path(project.namespace, project) } - it { is_expected.to be_allowed_for master } - it { is_expected.to be_allowed_for reporter } it { is_expected.to be_allowed_for :admin } + it { is_expected.to be_allowed_for owner } + it { is_expected.to be_allowed_for master } + it { is_expected.to be_allowed_for developer } + it { is_expected.to be_allowed_for reporter } it { is_expected.to be_denied_for guest } it { is_expected.to be_denied_for :user } it { is_expected.to be_denied_for :external } - it { is_expected.to be_allowed_for external_team_member } it { is_expected.to be_denied_for :visitor } end describe "GET /:project_path/project_members" do subject { namespace_project_project_members_path(project.namespace, project) } - it { is_expected.to be_allowed_for master } - it { is_expected.to be_denied_for reporter } it { is_expected.to be_allowed_for :admin } + it { is_expected.to be_allowed_for owner } + it { is_expected.to be_allowed_for master } + it { is_expected.to be_denied_for developer } + it { is_expected.to be_denied_for reporter } it { is_expected.to be_denied_for guest } it { is_expected.to be_denied_for :user } it { is_expected.to be_denied_for :external } - it { is_expected.to be_allowed_for external_team_member } it { is_expected.to be_denied_for :visitor } end @@ -109,52 +113,56 @@ describe "Private Project Access", feature: true do let(:commit) { project.repository.commit } subject { namespace_project_blob_path(project.namespace, project, File.join(commit.id, '.gitignore'))} - it { is_expected.to be_allowed_for master } - it { is_expected.to be_allowed_for reporter } it { is_expected.to be_allowed_for :admin } + it { is_expected.to be_allowed_for owner } + it { is_expected.to be_allowed_for master } + it { is_expected.to be_allowed_for developer } + it { is_expected.to be_allowed_for reporter } it { is_expected.to be_denied_for guest } it { is_expected.to be_denied_for :user } it { is_expected.to be_denied_for :external } - it { is_expected.to be_allowed_for external_team_member } it { is_expected.to be_denied_for :visitor } end describe "GET /:project_path/edit" do subject { edit_namespace_project_path(project.namespace, project) } - it { is_expected.to be_allowed_for master } - it { is_expected.to be_denied_for reporter } it { is_expected.to be_allowed_for :admin } + it { is_expected.to be_allowed_for owner } + it { is_expected.to be_allowed_for master } + it { is_expected.to be_denied_for developer } + it { is_expected.to be_denied_for reporter } it { is_expected.to be_denied_for guest } it { is_expected.to be_denied_for :user } it { is_expected.to be_denied_for :external } - it { is_expected.to be_allowed_for external_team_member } it { is_expected.to be_denied_for :visitor } end describe "GET /:project_path/deploy_keys" do subject { namespace_project_deploy_keys_path(project.namespace, project) } - it { is_expected.to be_allowed_for master } - it { is_expected.to be_denied_for reporter } it { is_expected.to be_allowed_for :admin } + it { is_expected.to be_allowed_for owner } + it { is_expected.to be_allowed_for master } + it { is_expected.to be_denied_for developer } + it { is_expected.to be_denied_for reporter } it { is_expected.to be_denied_for guest } it { is_expected.to be_denied_for :user } it { is_expected.to be_denied_for :external } - it { is_expected.to be_allowed_for external_team_member } it { is_expected.to be_denied_for :visitor } end describe "GET /:project_path/issues" do subject { namespace_project_issues_path(project.namespace, project) } - it { is_expected.to be_allowed_for master } - it { is_expected.to be_allowed_for reporter } it { is_expected.to be_allowed_for :admin } - it { is_expected.to be_denied_for guest } + it { is_expected.to be_allowed_for owner } + it { is_expected.to be_allowed_for master } + it { is_expected.to be_allowed_for developer } + it { is_expected.to be_allowed_for reporter } + it { is_expected.to be_allowed_for guest } it { is_expected.to be_denied_for :user } it { is_expected.to be_denied_for :external } - it { is_expected.to be_allowed_for external_team_member } it { is_expected.to be_denied_for :visitor } end @@ -162,39 +170,42 @@ describe "Private Project Access", feature: true do let(:issue) { create(:issue, project: project) } subject { edit_namespace_project_issue_path(project.namespace, project, issue) } - it { is_expected.to be_allowed_for master } - it { is_expected.to be_allowed_for reporter } it { is_expected.to be_allowed_for :admin } + it { is_expected.to be_allowed_for owner } + it { is_expected.to be_allowed_for master } + it { is_expected.to be_allowed_for developer } + it { is_expected.to be_allowed_for reporter } it { is_expected.to be_denied_for guest } it { is_expected.to be_denied_for :user } it { is_expected.to be_denied_for :external } - it { is_expected.to be_allowed_for external_team_member } it { is_expected.to be_denied_for :visitor } end describe "GET /:project_path/snippets" do subject { namespace_project_snippets_path(project.namespace, project) } - it { is_expected.to be_allowed_for master } - it { is_expected.to be_allowed_for reporter } it { is_expected.to be_allowed_for :admin } - it { is_expected.to be_denied_for guest } + it { is_expected.to be_allowed_for owner } + it { is_expected.to be_allowed_for master } + it { is_expected.to be_allowed_for developer } + it { is_expected.to be_allowed_for reporter } + it { is_expected.to be_allowed_for guest } it { is_expected.to be_denied_for :user } it { is_expected.to be_denied_for :external } - it { is_expected.to be_allowed_for external_team_member } it { is_expected.to be_denied_for :visitor } end describe "GET /:project_path/merge_requests" do subject { namespace_project_merge_requests_path(project.namespace, project) } - it { is_expected.to be_allowed_for master } - it { is_expected.to be_allowed_for reporter } it { is_expected.to be_allowed_for :admin } - it { is_expected.to be_denied_for guest } + it { is_expected.to be_allowed_for owner } + it { is_expected.to be_allowed_for master } + it { is_expected.to be_allowed_for developer } + it { is_expected.to be_allowed_for reporter } + it { is_expected.to be_allowed_for guest } it { is_expected.to be_denied_for :user } it { is_expected.to be_denied_for :external } - it { is_expected.to be_allowed_for external_team_member } it { is_expected.to be_denied_for :visitor } end @@ -206,13 +217,14 @@ describe "Private Project Access", feature: true do allow_any_instance_of(Project).to receive(:branches).and_return([]) end - it { is_expected.to be_allowed_for master } - it { is_expected.to be_allowed_for reporter } it { is_expected.to be_allowed_for :admin } + it { is_expected.to be_allowed_for owner } + it { is_expected.to be_allowed_for master } + it { is_expected.to be_allowed_for developer } + it { is_expected.to be_allowed_for reporter } it { is_expected.to be_denied_for guest } it { is_expected.to be_denied_for :user } it { is_expected.to be_denied_for :external } - it { is_expected.to be_allowed_for external_team_member } it { is_expected.to be_denied_for :visitor } end @@ -224,26 +236,28 @@ describe "Private Project Access", feature: true do allow_any_instance_of(Project).to receive(:tags).and_return([]) end - it { is_expected.to be_allowed_for master } - it { is_expected.to be_allowed_for reporter } it { is_expected.to be_allowed_for :admin } + it { is_expected.to be_allowed_for owner } + it { is_expected.to be_allowed_for master } + it { is_expected.to be_allowed_for developer } + it { is_expected.to be_allowed_for reporter } it { is_expected.to be_denied_for guest } it { is_expected.to be_denied_for :user } it { is_expected.to be_denied_for :external } - it { is_expected.to be_allowed_for external_team_member } it { is_expected.to be_denied_for :visitor } end describe "GET /:project_path/hooks" do subject { namespace_project_hooks_path(project.namespace, project) } - it { is_expected.to be_allowed_for master } - it { is_expected.to be_denied_for reporter } it { is_expected.to be_allowed_for :admin } + it { is_expected.to be_allowed_for owner } + it { is_expected.to be_allowed_for master } + it { is_expected.to be_denied_for developer } + it { is_expected.to be_denied_for reporter } it { is_expected.to be_denied_for guest } it { is_expected.to be_denied_for :user } it { is_expected.to be_denied_for :external } - it { is_expected.to be_allowed_for external_team_member } it { is_expected.to be_denied_for :visitor } end end diff --git a/spec/features/security/project/public_access_spec.rb b/spec/features/security/project/public_access_spec.rb index 4e13507636..40daac89d4 100644 --- a/spec/features/security/project/public_access_spec.rb +++ b/spec/features/security/project/public_access_spec.rb @@ -3,29 +3,24 @@ require 'spec_helper' describe "Public Project Access", feature: true do include AccessMatchers - let(:project) { create(:project) } + let(:project) { create(:project, :public) } - let(:master) { create(:user) } - let(:guest) { create(:user) } - let(:reporter) { create(:user) } + let(:owner) { project.owner } + let(:master) { create(:user) } + let(:developer) { create(:user) } + let(:reporter) { create(:user) } + let(:guest) { create(:user) } before do - # public project - project.visibility_level = Gitlab::VisibilityLevel::PUBLIC - project.save! - - # full access project.team << [master, :master] - - # readonly + project.team << [developer, :developer] project.team << [reporter, :reporter] + project.team << [guest, :guest] end describe "Project should be public" do - subject { project } - describe '#public?' do - subject { super().public? } + subject { project.public? } it { is_expected.to be_truthy } end end @@ -33,9 +28,11 @@ describe "Public Project Access", feature: true do describe "GET /:project_path" do subject { namespace_project_path(project.namespace, project) } - it { is_expected.to be_allowed_for master } - it { is_expected.to be_allowed_for reporter } it { is_expected.to be_allowed_for :admin } + it { is_expected.to be_allowed_for owner } + it { is_expected.to be_allowed_for master } + it { is_expected.to be_allowed_for developer } + it { is_expected.to be_allowed_for reporter } it { is_expected.to be_allowed_for guest } it { is_expected.to be_allowed_for :user } it { is_expected.to be_allowed_for :external } @@ -45,9 +42,11 @@ describe "Public Project Access", feature: true do describe "GET /:project_path/tree/master" do subject { namespace_project_tree_path(project.namespace, project, project.repository.root_ref) } - it { is_expected.to be_allowed_for master } - it { is_expected.to be_allowed_for reporter } it { is_expected.to be_allowed_for :admin } + it { is_expected.to be_allowed_for owner } + it { is_expected.to be_allowed_for master } + it { is_expected.to be_allowed_for developer } + it { is_expected.to be_allowed_for reporter } it { is_expected.to be_allowed_for guest } it { is_expected.to be_allowed_for :user } it { is_expected.to be_allowed_for :external } @@ -57,9 +56,11 @@ describe "Public Project Access", feature: true do describe "GET /:project_path/commits/master" do subject { namespace_project_commits_path(project.namespace, project, project.repository.root_ref, limit: 1) } - it { is_expected.to be_allowed_for master } - it { is_expected.to be_allowed_for reporter } it { is_expected.to be_allowed_for :admin } + it { is_expected.to be_allowed_for owner } + it { is_expected.to be_allowed_for master } + it { is_expected.to be_allowed_for developer } + it { is_expected.to be_allowed_for reporter } it { is_expected.to be_allowed_for guest } it { is_expected.to be_allowed_for :user } it { is_expected.to be_allowed_for :external } @@ -69,9 +70,11 @@ describe "Public Project Access", feature: true do describe "GET /:project_path/commit/:sha" do subject { namespace_project_commit_path(project.namespace, project, project.repository.commit) } - it { is_expected.to be_allowed_for master } - it { is_expected.to be_allowed_for reporter } it { is_expected.to be_allowed_for :admin } + it { is_expected.to be_allowed_for owner } + it { is_expected.to be_allowed_for master } + it { is_expected.to be_allowed_for developer } + it { is_expected.to be_allowed_for reporter } it { is_expected.to be_allowed_for guest } it { is_expected.to be_allowed_for :user } it { is_expected.to be_allowed_for :external } @@ -81,9 +84,11 @@ describe "Public Project Access", feature: true do describe "GET /:project_path/compare" do subject { namespace_project_compare_index_path(project.namespace, project) } - it { is_expected.to be_allowed_for master } - it { is_expected.to be_allowed_for reporter } it { is_expected.to be_allowed_for :admin } + it { is_expected.to be_allowed_for owner } + it { is_expected.to be_allowed_for master } + it { is_expected.to be_allowed_for developer } + it { is_expected.to be_allowed_for reporter } it { is_expected.to be_allowed_for guest } it { is_expected.to be_allowed_for :user } it { is_expected.to be_allowed_for :external } @@ -93,9 +98,11 @@ describe "Public Project Access", feature: true do describe "GET /:project_path/project_members" do subject { namespace_project_project_members_path(project.namespace, project) } - it { is_expected.to be_allowed_for master } - it { is_expected.to be_denied_for reporter } it { is_expected.to be_allowed_for :admin } + it { is_expected.to be_allowed_for owner } + it { is_expected.to be_allowed_for master } + it { is_expected.to be_denied_for developer } + it { is_expected.to be_denied_for reporter } it { is_expected.to be_denied_for guest } it { is_expected.to be_denied_for :user } it { is_expected.to be_denied_for :external } @@ -108,9 +115,11 @@ describe "Public Project Access", feature: true do context "when allowed for public" do before { project.update(public_builds: true) } - it { is_expected.to be_allowed_for master } - it { is_expected.to be_allowed_for reporter } it { is_expected.to be_allowed_for :admin } + it { is_expected.to be_allowed_for owner } + it { is_expected.to be_allowed_for master } + it { is_expected.to be_allowed_for developer } + it { is_expected.to be_allowed_for reporter } it { is_expected.to be_allowed_for guest } it { is_expected.to be_allowed_for :user } it { is_expected.to be_allowed_for :external } @@ -120,9 +129,11 @@ describe "Public Project Access", feature: true do context "when disallowed for public" do before { project.update(public_builds: false) } - it { is_expected.to be_allowed_for master } - it { is_expected.to be_allowed_for reporter } it { is_expected.to be_allowed_for :admin } + it { is_expected.to be_allowed_for owner } + it { is_expected.to be_allowed_for master } + it { is_expected.to be_allowed_for developer } + it { is_expected.to be_allowed_for reporter } it { is_expected.to be_denied_for guest } it { is_expected.to be_denied_for :user } it { is_expected.to be_denied_for :external } @@ -138,9 +149,11 @@ describe "Public Project Access", feature: true do context "when allowed for public" do before { project.update(public_builds: true) } - it { is_expected.to be_allowed_for master } - it { is_expected.to be_allowed_for reporter } it { is_expected.to be_allowed_for :admin } + it { is_expected.to be_allowed_for owner } + it { is_expected.to be_allowed_for master } + it { is_expected.to be_allowed_for developer } + it { is_expected.to be_allowed_for reporter } it { is_expected.to be_allowed_for guest } it { is_expected.to be_allowed_for :user } it { is_expected.to be_allowed_for :external } @@ -150,9 +163,11 @@ describe "Public Project Access", feature: true do context "when disallowed for public" do before { project.update(public_builds: false) } - it { is_expected.to be_allowed_for master } - it { is_expected.to be_allowed_for reporter } it { is_expected.to be_allowed_for :admin } + it { is_expected.to be_allowed_for owner } + it { is_expected.to be_allowed_for master } + it { is_expected.to be_allowed_for developer } + it { is_expected.to be_allowed_for reporter } it { is_expected.to be_denied_for guest } it { is_expected.to be_denied_for :user } it { is_expected.to be_denied_for :external } @@ -165,9 +180,11 @@ describe "Public Project Access", feature: true do subject { namespace_project_blob_path(project.namespace, project, File.join(commit.id, '.gitignore')) } - it { is_expected.to be_allowed_for master } - it { is_expected.to be_allowed_for reporter } it { is_expected.to be_allowed_for :admin } + it { is_expected.to be_allowed_for owner } + it { is_expected.to be_allowed_for master } + it { is_expected.to be_allowed_for developer } + it { is_expected.to be_allowed_for reporter } it { is_expected.to be_allowed_for guest } it { is_expected.to be_allowed_for :user } it { is_expected.to be_allowed_for :visitor } @@ -176,9 +193,11 @@ describe "Public Project Access", feature: true do describe "GET /:project_path/edit" do subject { edit_namespace_project_path(project.namespace, project) } - it { is_expected.to be_allowed_for master } - it { is_expected.to be_denied_for reporter } it { is_expected.to be_allowed_for :admin } + it { is_expected.to be_allowed_for owner } + it { is_expected.to be_allowed_for master } + it { is_expected.to be_denied_for developer } + it { is_expected.to be_denied_for reporter } it { is_expected.to be_denied_for guest } it { is_expected.to be_denied_for :user } it { is_expected.to be_denied_for :external } @@ -188,9 +207,11 @@ describe "Public Project Access", feature: true do describe "GET /:project_path/deploy_keys" do subject { namespace_project_deploy_keys_path(project.namespace, project) } - it { is_expected.to be_allowed_for master } - it { is_expected.to be_denied_for reporter } it { is_expected.to be_allowed_for :admin } + it { is_expected.to be_allowed_for owner } + it { is_expected.to be_allowed_for master } + it { is_expected.to be_denied_for developer } + it { is_expected.to be_denied_for reporter } it { is_expected.to be_denied_for guest } it { is_expected.to be_denied_for :user } it { is_expected.to be_denied_for :external } @@ -200,9 +221,11 @@ describe "Public Project Access", feature: true do describe "GET /:project_path/issues" do subject { namespace_project_issues_path(project.namespace, project) } - it { is_expected.to be_allowed_for master } - it { is_expected.to be_allowed_for reporter } it { is_expected.to be_allowed_for :admin } + it { is_expected.to be_allowed_for owner } + it { is_expected.to be_allowed_for master } + it { is_expected.to be_allowed_for developer } + it { is_expected.to be_allowed_for reporter } it { is_expected.to be_allowed_for guest } it { is_expected.to be_allowed_for :user } it { is_expected.to be_allowed_for :external } @@ -213,9 +236,11 @@ describe "Public Project Access", feature: true do let(:issue) { create(:issue, project: project) } subject { edit_namespace_project_issue_path(project.namespace, project, issue) } - it { is_expected.to be_allowed_for master } - it { is_expected.to be_allowed_for reporter } it { is_expected.to be_allowed_for :admin } + it { is_expected.to be_allowed_for owner } + it { is_expected.to be_allowed_for master } + it { is_expected.to be_allowed_for developer } + it { is_expected.to be_allowed_for reporter } it { is_expected.to be_denied_for guest } it { is_expected.to be_denied_for :user } it { is_expected.to be_denied_for :external } @@ -225,9 +250,11 @@ describe "Public Project Access", feature: true do describe "GET /:project_path/snippets" do subject { namespace_project_snippets_path(project.namespace, project) } - it { is_expected.to be_allowed_for master } - it { is_expected.to be_allowed_for reporter } it { is_expected.to be_allowed_for :admin } + it { is_expected.to be_allowed_for owner } + it { is_expected.to be_allowed_for master } + it { is_expected.to be_allowed_for developer } + it { is_expected.to be_allowed_for reporter } it { is_expected.to be_allowed_for guest } it { is_expected.to be_allowed_for :user } it { is_expected.to be_allowed_for :external } @@ -237,9 +264,11 @@ describe "Public Project Access", feature: true do describe "GET /:project_path/snippets/new" do subject { new_namespace_project_snippet_path(project.namespace, project) } - it { is_expected.to be_allowed_for master } - it { is_expected.to be_allowed_for reporter } it { is_expected.to be_allowed_for :admin } + it { is_expected.to be_allowed_for owner } + it { is_expected.to be_allowed_for master } + it { is_expected.to be_allowed_for developer } + it { is_expected.to be_allowed_for reporter } it { is_expected.to be_denied_for guest } it { is_expected.to be_denied_for :user } it { is_expected.to be_denied_for :external } @@ -249,9 +278,11 @@ describe "Public Project Access", feature: true do describe "GET /:project_path/merge_requests" do subject { namespace_project_merge_requests_path(project.namespace, project) } - it { is_expected.to be_allowed_for master } - it { is_expected.to be_allowed_for reporter } it { is_expected.to be_allowed_for :admin } + it { is_expected.to be_allowed_for owner } + it { is_expected.to be_allowed_for master } + it { is_expected.to be_allowed_for developer } + it { is_expected.to be_allowed_for reporter } it { is_expected.to be_allowed_for guest } it { is_expected.to be_allowed_for :user } it { is_expected.to be_allowed_for :external } @@ -261,9 +292,11 @@ describe "Public Project Access", feature: true do describe "GET /:project_path/merge_requests/new" do subject { new_namespace_project_merge_request_path(project.namespace, project) } - it { is_expected.to be_allowed_for master } - it { is_expected.to be_denied_for reporter } it { is_expected.to be_allowed_for :admin } + it { is_expected.to be_allowed_for owner } + it { is_expected.to be_allowed_for master } + it { is_expected.to be_allowed_for developer } + it { is_expected.to be_denied_for reporter } it { is_expected.to be_denied_for guest } it { is_expected.to be_denied_for :user } it { is_expected.to be_denied_for :external } @@ -278,9 +311,11 @@ describe "Public Project Access", feature: true do allow_any_instance_of(Project).to receive(:branches).and_return([]) end - it { is_expected.to be_allowed_for master } - it { is_expected.to be_allowed_for reporter } it { is_expected.to be_allowed_for :admin } + it { is_expected.to be_allowed_for owner } + it { is_expected.to be_allowed_for master } + it { is_expected.to be_allowed_for developer } + it { is_expected.to be_allowed_for reporter } it { is_expected.to be_allowed_for guest } it { is_expected.to be_allowed_for :user } it { is_expected.to be_allowed_for :external } @@ -295,9 +330,11 @@ describe "Public Project Access", feature: true do allow_any_instance_of(Project).to receive(:tags).and_return([]) end - it { is_expected.to be_allowed_for master } - it { is_expected.to be_allowed_for reporter } it { is_expected.to be_allowed_for :admin } + it { is_expected.to be_allowed_for owner } + it { is_expected.to be_allowed_for master } + it { is_expected.to be_allowed_for developer } + it { is_expected.to be_allowed_for reporter } it { is_expected.to be_allowed_for guest } it { is_expected.to be_allowed_for :user } it { is_expected.to be_allowed_for :external } @@ -307,9 +344,11 @@ describe "Public Project Access", feature: true do describe "GET /:project_path/hooks" do subject { namespace_project_hooks_path(project.namespace, project) } - it { is_expected.to be_allowed_for master } - it { is_expected.to be_denied_for reporter } it { is_expected.to be_allowed_for :admin } + it { is_expected.to be_allowed_for owner } + it { is_expected.to be_allowed_for master } + it { is_expected.to be_denied_for developer } + it { is_expected.to be_denied_for reporter } it { is_expected.to be_denied_for guest } it { is_expected.to be_denied_for :user } it { is_expected.to be_denied_for :external } diff --git a/spec/finders/group_projects_finder_spec.rb b/spec/finders/group_projects_finder_spec.rb new file mode 100644 index 0000000000..fdd3849816 --- /dev/null +++ b/spec/finders/group_projects_finder_spec.rb @@ -0,0 +1,89 @@ +require 'spec_helper' + +describe GroupProjectsFinder do + let(:group) { create(:group) } + let(:current_user) { create(:user) } + + let(:finder) { described_class.new(source_user) } + + let!(:public_project) { create(:project, :public, group: group, path: '1') } + let!(:private_project) { create(:project, :private, group: group, path: '2') } + let!(:shared_project_1) { create(:project, :public, path: '3') } + let!(:shared_project_2) { create(:project, :private, path: '4') } + let!(:shared_project_3) { create(:project, :internal, path: '5') } + + + before do + shared_project_1.project_group_links.create(group_access: Gitlab::Access::MASTER, group: group) + shared_project_2.project_group_links.create(group_access: Gitlab::Access::MASTER, group: group) + shared_project_3.project_group_links.create(group_access: Gitlab::Access::MASTER, group: group) + end + + + describe 'with a group member current user' do + before { group.add_user(current_user, Gitlab::Access::MASTER) } + + context "only shared" do + subject { described_class.new(group, only_shared: true).execute(current_user) } + it { is_expected.to eq([shared_project_3, shared_project_2, shared_project_1]) } + end + + context "only owned" do + subject { described_class.new(group, only_owned: true).execute(current_user) } + it { is_expected.to eq([private_project, public_project]) } + end + + context "all" do + subject { described_class.new(group).execute(current_user) } + it { is_expected.to eq([shared_project_3, shared_project_2, shared_project_1, private_project, public_project]) } + end + end + + describe 'without group member current_user' do + before { shared_project_2.team << [current_user, Gitlab::Access::MASTER] } + + context "only shared" do + context "without external user" do + subject { described_class.new(group, only_shared: true).execute(current_user) } + it { is_expected.to eq([shared_project_3, shared_project_2, shared_project_1]) } + end + + context "with external user" do + before { current_user.update_attributes(external: true) } + subject { described_class.new(group, only_shared: true).execute(current_user) } + it { is_expected.to eq([shared_project_2, shared_project_1]) } + end + end + + context "only owned" do + context "without external user" do + before { private_project.team << [current_user, Gitlab::Access::MASTER] } + subject { described_class.new(group, only_owned: true).execute(current_user) } + it { is_expected.to eq([private_project, public_project]) } + end + + context "with external user" do + before { current_user.update_attributes(external: true) } + subject { described_class.new(group, only_owned: true).execute(current_user) } + it { is_expected.to eq([public_project]) } + end + + context "all" do + subject { described_class.new(group).execute(current_user) } + it { is_expected.to eq([shared_project_3, shared_project_2, shared_project_1, public_project]) } + end + end + end + + describe "no user" do + context "only shared" do + subject { described_class.new(group, only_shared: true).execute(current_user) } + it { is_expected.to eq([shared_project_3, shared_project_1]) } + end + + context "only owned" do + subject { described_class.new(group, only_owned: true).execute(current_user) } + it { is_expected.to eq([public_project]) } + end + end +end diff --git a/spec/finders/groups_finder_spec.rb b/spec/finders/groups_finder_spec.rb new file mode 100644 index 0000000000..d5d111e8d1 --- /dev/null +++ b/spec/finders/groups_finder_spec.rb @@ -0,0 +1,33 @@ +require 'spec_helper' + +describe GroupsFinder do + describe '#execute' do + let(:user) { create(:user) } + let!(:private_group) { create(:group, :private) } + let!(:internal_group) { create(:group, :internal) } + let!(:public_group) { create(:group, :public) } + let(:finder) { described_class.new } + + describe 'execute' do + describe 'without a user' do + subject { finder.execute } + + it { is_expected.to eq([public_group]) } + end + + describe 'with a user' do + subject { finder.execute(user) } + + context 'normal user' do + it { is_expected.to eq([public_group, internal_group]) } + end + + context 'external user' do + let(:user) { create(:user, external: true) } + + it { is_expected.to eq([public_group]) } + end + end + end + end +end diff --git a/spec/finders/joined_groups_finder_spec.rb b/spec/finders/joined_groups_finder_spec.rb new file mode 100644 index 0000000000..f90a8e007c --- /dev/null +++ b/spec/finders/joined_groups_finder_spec.rb @@ -0,0 +1,77 @@ +require 'spec_helper' + +describe JoinedGroupsFinder do + describe '#execute' do + let!(:profile_owner) { create(:user) } + let!(:profile_visitor) { create(:user) } + + let!(:private_group) { create(:group, :private) } + let!(:private_group_2) { create(:group, :private) } + let!(:internal_group) { create(:group, :internal) } + let!(:internal_group_2) { create(:group, :internal) } + let!(:public_group) { create(:group, :public) } + let!(:public_group_2) { create(:group, :public) } + let!(:finder) { described_class.new(profile_owner) } + + context 'without a user' do + before do + public_group.add_master(profile_owner) + end + + it 'only shows public groups from profile owner' do + expect(finder.execute).to eq([public_group]) + end + end + + context "with a user" do + before do + private_group.add_master(profile_owner) + internal_group.add_master(profile_owner) + public_group.add_master(profile_owner) + end + + context "when the profile visitor is in the private group" do + before do + private_group.add_developer(profile_visitor) + end + + it 'only shows groups where both users are authorized to see' do + expect(finder.execute(profile_visitor)).to eq([public_group, internal_group, private_group]) + end + end + + context 'if profile visitor is in one of the private group projects' do + before do + project = create(:project, :private, group: private_group, name: 'B', path: 'B') + project.team.add_user(profile_visitor, Gitlab::Access::DEVELOPER) + end + + it 'shows group' do + expect(finder.execute(profile_visitor)).to eq([public_group, internal_group, private_group]) + end + end + + context 'external users' do + before do + profile_visitor.update_attributes(external: true) + end + + context 'if not a member' do + it "does not show internal groups" do + expect(finder.execute(profile_visitor)).to eq([public_group]) + end + end + + context "if authorized" do + before do + internal_group.add_master(profile_visitor) + end + + it "shows internal groups if authorized" do + expect(finder.execute(profile_visitor)).to eq([public_group, internal_group]) + end + end + end + end + end +end diff --git a/spec/finders/personal_projects_finder_spec.rb b/spec/finders/personal_projects_finder_spec.rb index 38817add45..a4681fe59d 100644 --- a/spec/finders/personal_projects_finder_spec.rb +++ b/spec/finders/personal_projects_finder_spec.rb @@ -1,19 +1,17 @@ require 'spec_helper' describe PersonalProjectsFinder do - let(:source_user) { create(:user) } - let(:current_user) { create(:user) } - - let(:finder) { described_class.new(source_user) } - - let!(:public_project) do - create(:project, :public, namespace: source_user.namespace, name: 'A', - path: 'A') - end + let(:source_user) { create(:user) } + let(:current_user) { create(:user) } + let(:finder) { described_class.new(source_user) } + let!(:public_project) { create(:project, :public, namespace: source_user.namespace) } let!(:private_project) do - create(:project, :private, namespace: source_user.namespace, name: 'B', - path: 'B') + create(:project, :private, namespace: source_user.namespace, path: 'mepmep') + end + + let!(:internal_project) do + create(:project, :internal, namespace: source_user.namespace, path: 'C') end before do @@ -29,6 +27,14 @@ describe PersonalProjectsFinder do describe 'with a current user' do subject { finder.execute(current_user) } - it { is_expected.to eq([private_project, public_project]) } + context 'normal user' do + it { is_expected.to eq([internal_project, private_project, public_project]) } + end + + context 'external' do + before { current_user.update_attributes(external: true) } + + it { is_expected.to eq([private_project, public_project]) } + end end end diff --git a/spec/finders/projects_finder_spec.rb b/spec/finders/projects_finder_spec.rb index fae0da9d89..0a1cc3b3df 100644 --- a/spec/finders/projects_finder_spec.rb +++ b/spec/finders/projects_finder_spec.rb @@ -3,7 +3,7 @@ require 'spec_helper' describe ProjectsFinder do describe '#execute' do let(:user) { create(:user) } - let(:group) { create(:group) } + let(:group) { create(:group, :public) } let!(:private_project) do create(:project, :private, name: 'A', path: 'A') diff --git a/spec/finders/snippets_finder_spec.rb b/spec/finders/snippets_finder_spec.rb index 7fdc5e5d7a..810016c965 100644 --- a/spec/finders/snippets_finder_spec.rb +++ b/spec/finders/snippets_finder_spec.rb @@ -3,7 +3,7 @@ require 'spec_helper' describe SnippetsFinder do let(:user) { create :user } let(:user1) { create :user } - let(:group) { create :group } + let(:group) { create :group, :public } let(:project1) { create(:empty_project, :public, group: group) } let(:project2) { create(:empty_project, :private, group: group) } diff --git a/spec/helpers/groups_helper.rb b/spec/helpers/groups_helper_spec.rb similarity index 100% rename from spec/helpers/groups_helper.rb rename to spec/helpers/groups_helper_spec.rb diff --git a/spec/helpers/labels_helper_spec.rb b/spec/helpers/labels_helper_spec.rb index eca8bc8ab2..39042ff7e9 100644 --- a/spec/helpers/labels_helper_spec.rb +++ b/spec/helpers/labels_helper_spec.rb @@ -11,7 +11,7 @@ describe LabelsHelper do end it 'uses the instance variable' do - expect(link_to_label(label)).to match %r{} + expect(link_to_label(label)).to match %r{} end end @@ -41,8 +41,8 @@ describe LabelsHelper do context 'with a tooltip argument' do context 'set to false' do - it 'does not include the has_tooltip class' do - expect(link_to_label(label, tooltip: false)).not_to match %r{has_tooltip} + it 'does not include the has-tooltip class' do + expect(link_to_label(label, tooltip: false)).not_to match %r{has-tooltip} end end end diff --git a/spec/helpers/projects_helper_spec.rb b/spec/helpers/projects_helper_spec.rb index 86cbd29830..c258cfebd7 100644 --- a/spec/helpers/projects_helper_spec.rb +++ b/spec/helpers/projects_helper_spec.rb @@ -11,16 +11,8 @@ describe ProjectsHelper do describe "can_change_visibility_level?" do let(:project) { create(:project) } - - let(:fork_project) do - fork_project = create(:forked_project_with_submodules) - fork_project.build_forked_project_link(forked_to_project_id: fork_project.id, forked_from_project_id: project.id) - fork_project.save - - fork_project - end - let(:user) { create(:user) } + let(:fork_project) { Projects::ForkService.new(project, user).execute } it "returns false if there are no appropriate permissions" do allow(helper).to receive(:can?) { false } diff --git a/spec/helpers/visibility_level_helper_spec.rb b/spec/helpers/visibility_level_helper_spec.rb index cd7596a763..ff98249570 100644 --- a/spec/helpers/visibility_level_helper_spec.rb +++ b/spec/helpers/visibility_level_helper_spec.rb @@ -8,6 +8,7 @@ describe VisibilityLevelHelper do end let(:project) { build(:project) } + let(:group) { build(:group) } let(:personal_snippet) { build(:personal_snippet) } let(:project_snippet) { build(:project_snippet) } @@ -19,6 +20,13 @@ describe VisibilityLevelHelper do end end + context 'used with a Group' do + it 'delegates groups to #group_visibility_level_description' do + expect(visibility_level_description(Gitlab::VisibilityLevel::PRIVATE, group)) + .to match /group/i + end + end + context 'called with a Snippet' do it 'delegates snippets to #snippet_visibility_level_description' do expect(visibility_level_description(Gitlab::VisibilityLevel::INTERNAL, project_snippet)) @@ -58,13 +66,8 @@ describe VisibilityLevelHelper do describe "skip_level?" do describe "forks" do - let(:project) { create(:project, :internal) } - let(:fork_project) { create(:forked_project_with_submodules) } - - before do - fork_project.build_forked_project_link(forked_to_project_id: fork_project.id, forked_from_project_id: project.id) - fork_project.save - end + let(:project) { create(:project, :internal) } + let(:fork_project) { create(:project, forked_from_project: project) } it "skips levels" do expect(skip_level?(fork_project, Gitlab::VisibilityLevel::PUBLIC)).to be_truthy diff --git a/spec/lib/banzai/filter/label_reference_filter_spec.rb b/spec/lib/banzai/filter/label_reference_filter_spec.rb index 4c1d4a2d24..94468abcbb 100644 --- a/spec/lib/banzai/filter/label_reference_filter_spec.rb +++ b/spec/lib/banzai/filter/label_reference_filter_spec.rb @@ -56,7 +56,7 @@ describe Banzai::Filter::LabelReferenceFilter, lib: true do describe 'label span element' do it 'includes default classes' do doc = reference_filter("Label #{reference}") - expect(doc.css('a span').first.attr('class')).to eq 'label color-label has_tooltip' + expect(doc.css('a span').first.attr('class')).to eq 'label color-label has-tooltip' end it 'includes a style attribute' do diff --git a/spec/lib/banzai/filter/redactor_filter_spec.rb b/spec/lib/banzai/filter/redactor_filter_spec.rb index 9acf6304bc..c2c2fd0eb6 100644 --- a/spec/lib/banzai/filter/redactor_filter_spec.rb +++ b/spec/lib/banzai/filter/redactor_filter_spec.rb @@ -119,7 +119,7 @@ describe Banzai::Filter::RedactorFilter, lib: true do context 'with data-group' do it 'removes unpermitted Group references' do user = create(:user) - group = create(:group) + group = create(:group, :private) link = reference_link(group: group.id, reference_filter: 'UserReferenceFilter') doc = filter(link, current_user: user) @@ -129,7 +129,7 @@ describe Banzai::Filter::RedactorFilter, lib: true do it 'allows permitted Group references' do user = create(:user) - group = create(:group) + group = create(:group, :private) group.add_developer(user) link = reference_link(group: group.id, reference_filter: 'UserReferenceFilter') diff --git a/spec/lib/ci/gitlab_ci_yaml_processor_spec.rb b/spec/lib/ci/gitlab_ci_yaml_processor_spec.rb index fab6412d29..dcb8a3451b 100644 --- a/spec/lib/ci/gitlab_ci_yaml_processor_spec.rb +++ b/spec/lib/ci/gitlab_ci_yaml_processor_spec.rb @@ -97,6 +97,28 @@ module Ci expect(config_processor.builds_for_stage_and_ref(type, "deploy").size).to eq(0) end + it "returns builds if only has a triggers keyword specified and a trigger is provided" do + config = YAML.dump({ + before_script: ["pwd"], + rspec: { script: "rspec", type: type, only: ["triggers"] } + }) + + config_processor = GitlabCiYamlProcessor.new(config, path) + + expect(config_processor.builds_for_stage_and_ref(type, "deploy", false, true).size).to eq(1) + end + + it "does not return builds if only has a triggers keyword specified and no trigger is provided" do + config = YAML.dump({ + before_script: ["pwd"], + rspec: { script: "rspec", type: type, only: ["triggers"] } + }) + + config_processor = GitlabCiYamlProcessor.new(config, path) + + expect(config_processor.builds_for_stage_and_ref(type, "deploy").size).to eq(0) + end + it "returns builds if only has current repository path" do config = YAML.dump({ before_script: ["pwd"], @@ -203,6 +225,28 @@ module Ci expect(config_processor.builds_for_stage_and_ref(type, "deploy").size).to eq(1) end + it "does not return builds if except has a triggers keyword specified and a trigger is provided" do + config = YAML.dump({ + before_script: ["pwd"], + rspec: { script: "rspec", type: type, except: ["triggers"] } + }) + + config_processor = GitlabCiYamlProcessor.new(config, path) + + expect(config_processor.builds_for_stage_and_ref(type, "deploy", false, true).size).to eq(0) + end + + it "returns builds if except has a triggers keyword specified and no trigger is provided" do + config = YAML.dump({ + before_script: ["pwd"], + rspec: { script: "rspec", type: type, except: ["triggers"] } + }) + + config_processor = GitlabCiYamlProcessor.new(config, path) + + expect(config_processor.builds_for_stage_and_ref(type, "deploy").size).to eq(1) + end + it "does not return builds if except has current repository path" do config = YAML.dump({ before_script: ["pwd"], @@ -448,19 +492,25 @@ module Ci end context 'dependencies to builds' do + let(:dependencies) { ['build1', 'build2'] } + + it { expect { subject }.to_not raise_error } + end + + context 'dependencies to builds defined as symbols' do let(:dependencies) { [:build1, :build2] } it { expect { subject }.to_not raise_error } end context 'undefined dependency' do - let(:dependencies) { [:undefined] } + let(:dependencies) { ['undefined'] } it { expect { subject }.to raise_error(GitlabCiYamlProcessor::ValidationError, 'test1 job: undefined dependency: undefined') } end context 'dependencies to deploy' do - let(:dependencies) { [:deploy] } + let(:dependencies) { ['deploy'] } it { expect { subject }.to raise_error(GitlabCiYamlProcessor::ValidationError, 'test1 job: dependency deploy is not defined in prior stages') } end diff --git a/spec/models/group_spec.rb b/spec/models/group_spec.rb index c9245fc953..7bfca1e72c 100644 --- a/spec/models/group_spec.rb +++ b/spec/models/group_spec.rb @@ -56,6 +56,23 @@ describe Group, models: true do end end + describe 'scopes' do + let!(:private_group) { create(:group, :private) } + let!(:internal_group) { create(:group, :internal) } + + describe 'public_only' do + subject { described_class.public_only.to_a } + + it{ is_expected.to eq([group]) } + end + + describe 'public_and_internal_only' do + subject { described_class.public_and_internal_only.to_a } + + it{ is_expected.to match_array([group, internal_group]) } + end + end + describe '#to_reference' do it 'returns a String reference to the object' do expect(group.to_reference).to eq "@#{group.name}" diff --git a/spec/models/issue_spec.rb b/spec/models/issue_spec.rb index 8334545b75..15052aaca2 100644 --- a/spec/models/issue_spec.rb +++ b/spec/models/issue_spec.rb @@ -37,6 +37,11 @@ describe Issue, models: true do subject { create(:issue) } + describe "act_as_paranoid" do + it { is_expected.to have_db_column(:deleted_at) } + it { is_expected.to have_db_index(:deleted_at) } + end + describe '#to_reference' do it 'returns a String reference to the object' do expect(subject.to_reference).to eq "##{subject.iid}" @@ -147,6 +152,11 @@ describe Issue, models: true do it { is_expected.to eq true } + context 'issue not persisted' do + let(:issue) { build(:issue, project: project) } + it { is_expected.to eq false } + end + context 'checking destination project also' do subject { issue.can_move?(user, to_project) } let(:to_project) { create(:project) } diff --git a/spec/models/merge_request_spec.rb b/spec/models/merge_request_spec.rb index f2f07e4ee1..bd0a4ebe33 100644 --- a/spec/models/merge_request_spec.rb +++ b/spec/models/merge_request_spec.rb @@ -49,6 +49,11 @@ describe MergeRequest, models: true do it { is_expected.to include_module(Taskable) } end + describe "act_as_paranoid" do + it { is_expected.to have_db_column(:deleted_at) } + it { is_expected.to have_db_index(:deleted_at) } + end + describe 'validation' do it { is_expected.to validate_presence_of(:target_branch) } it { is_expected.to validate_presence_of(:source_branch) } diff --git a/spec/models/project_security_spec.rb b/spec/models/project_security_spec.rb index 3643ad1b05..e12258c087 100644 --- a/spec/models/project_security_spec.rb +++ b/spec/models/project_security_spec.rb @@ -18,11 +18,11 @@ describe Project, models: true do let(:report_actions) { Ability.project_report_rules } let(:dev_actions) { Ability.project_dev_rules } let(:master_actions) { Ability.project_master_rules } - let(:admin_actions) { Ability.project_admin_rules } + let(:owner_actions) { Ability.project_owner_rules } describe "Non member rules" do it "should deny for non-project users any actions" do - admin_actions.each do |action| + owner_actions.each do |action| expect(@abilities.allowed?(@u1, action, @p1)).to be_falsey end end @@ -90,20 +90,20 @@ describe Project, models: true do end end - describe "Admin Rules" do + describe "Owner Rules" do before do @p1.project_members.create(project: @p1, user: @u2, access_level: ProjectMember::DEVELOPER) @p1.project_members.create(project: @p1, user: @u3, access_level: ProjectMember::MASTER) end it "should deny for masters admin-specific actions" do - [admin_actions - master_actions].each do |action| + [owner_actions - master_actions].each do |action| expect(@abilities.allowed?(@u2, action, @p1)).to be_falsey end end it "should allow for project owner any admin actions" do - admin_actions.each do |action| + owner_actions.each do |action| expect(@abilities.allowed?(@u4, action, @p1)).to be_truthy end end diff --git a/spec/models/project_spec.rb b/spec/models/project_spec.rb index 624022c1dd..20f06f4b7e 100644 --- a/spec/models/project_spec.rb +++ b/spec/models/project_spec.rb @@ -442,7 +442,7 @@ describe Project, models: true do end describe '.trending' do - let(:group) { create(:group) } + let(:group) { create(:group, :public) } let(:project1) { create(:empty_project, :public, group: group) } let(:project2) { create(:empty_project, :public, group: group) } @@ -571,12 +571,8 @@ describe Project, models: true do end context 'when checking on forked project' do - let(:forked_project) { create :forked_project_with_submodules } - - before do - forked_project.build_forked_project_link(forked_to_project_id: forked_project.id, forked_from_project_id: project.id) - forked_project.save - end + let(:project) { create(:project, :internal) } + let(:forked_project) { create(:project, forked_from_project: project) } it { expect(forked_project.visibility_level_allowed?(Gitlab::VisibilityLevel::PRIVATE)).to be_truthy } it { expect(forked_project.visibility_level_allowed?(Gitlab::VisibilityLevel::INTERNAL)).to be_truthy } @@ -721,6 +717,22 @@ describe Project, models: true do end end + context 'when checking projects from groups' do + let(:private_group) { create(:group, visibility_level: 0) } + let(:internal_group) { create(:group, visibility_level: 10) } + + let(:private_project) { create :project, :private, group: private_group } + let(:internal_project) { create :project, :internal, group: internal_group } + + context 'when group is private project can not be internal' do + it { expect(private_project.visibility_level_allowed?(Gitlab::VisibilityLevel::INTERNAL)).to be_falsey } + end + + context 'when group is internal project can not be public' do + it { expect(internal_project.visibility_level_allowed?(Gitlab::VisibilityLevel::PUBLIC)).to be_falsey } + end + end + describe '#create_repository' do let(:project) { create(:project) } let(:shell) { Gitlab::Shell.new } diff --git a/spec/requests/api/group_members_spec.rb b/spec/requests/api/group_members_spec.rb index dd5baa44cb..3e8b4aa1f8 100644 --- a/spec/requests/api/group_members_spec.rb +++ b/spec/requests/api/group_members_spec.rb @@ -11,7 +11,7 @@ describe API::API, api: true do let(:stranger) { create(:user) } let!(:group_with_members) do - group = create(:group) + group = create(:group, :private) group.add_users([reporter.id], GroupMember::REPORTER) group.add_users([developer.id], GroupMember::DEVELOPER) group.add_users([master.id], GroupMember::MASTER) diff --git a/spec/requests/api/groups_spec.rb b/spec/requests/api/groups_spec.rb index 4cfa49d156..41c9cacd45 100644 --- a/spec/requests/api/groups_spec.rb +++ b/spec/requests/api/groups_spec.rb @@ -9,7 +9,7 @@ describe API::API, api: true do let(:admin) { create(:admin) } let(:avatar_file_path) { File.join(Rails.root, 'spec', 'fixtures', 'banana_sample.gif') } let!(:group1) { create(:group, avatar: File.open(avatar_file_path)) } - let!(:group2) { create(:group) } + let!(:group2) { create(:group, :private) } let!(:project1) { create(:project, namespace: group1) } let!(:project2) { create(:project, namespace: group2) } diff --git a/spec/requests/api/issues_spec.rb b/spec/requests/api/issues_spec.rb index bb2ab05800..ce55cb7b0a 100644 --- a/spec/requests/api/issues_spec.rb +++ b/spec/requests/api/issues_spec.rb @@ -2,12 +2,12 @@ require 'spec_helper' describe API::API, api: true do include ApiHelpers - let(:user) { create(:user) } - let(:non_member) { create(:user) } - let(:author) { create(:author) } - let(:assignee) { create(:assignee) } - let(:admin) { create(:admin) } - let!(:project) { create(:project, :public, namespace: user.namespace ) } + let(:user) { create(:user) } + let(:non_member) { create(:user) } + let(:author) { create(:author) } + let(:assignee) { create(:assignee) } + let(:admin) { create(:user, :admin) } + let!(:project) { create(:project, :public, namespace: user.namespace ) } let!(:closed_issue) do create :closed_issue, author: user, @@ -469,9 +469,25 @@ describe API::API, api: true do end describe "DELETE /projects/:id/issues/:issue_id" do - it "should delete a project issue" do - delete api("/projects/#{project.id}/issues/#{issue.id}", user) - expect(response.status).to eq(405) + it "rejects a non member from deleting an issue" do + delete api("/projects/#{project.id}/issues/#{issue.id}", non_member) + expect(response.status).to be(403) + end + + it "rejects a developer from deleting an issue" do + delete api("/projects/#{project.id}/issues/#{issue.id}", author) + expect(response.status).to be(403) + end + + context "when the user is project owner" do + let(:owner) { create(:user) } + let(:project) { create(:project, namespace: owner.namespace) } + + it "deletes the issue if an admin requests it" do + delete api("/projects/#{project.id}/issues/#{issue.id}", owner) + expect(response.status).to eq(200) + expect(json_response['state']).to eq 'opened' + end end end end diff --git a/spec/requests/api/merge_requests_spec.rb b/spec/requests/api/merge_requests_spec.rb index 4fd1df2556..c9175a4d6e 100644 --- a/spec/requests/api/merge_requests_spec.rb +++ b/spec/requests/api/merge_requests_spec.rb @@ -2,15 +2,17 @@ require "spec_helper" describe API::API, api: true do include ApiHelpers - let(:base_time) { Time.now } - let(:user) { create(:user) } - let!(:project) {create(:project, creator_id: user.id, namespace: user.namespace) } + let(:base_time) { Time.now } + let(:user) { create(:user) } + let(:admin) { create(:user, :admin) } + let(:non_member) { create(:user) } + let!(:project) { create(:project, creator_id: user.id, namespace: user.namespace) } let!(:merge_request) { create(:merge_request, :simple, author: user, assignee: user, source_project: project, target_project: project, title: "Test", created_at: base_time) } let!(:merge_request_closed) { create(:merge_request, state: "closed", author: user, assignee: user, source_project: project, target_project: project, title: "Closed test", created_at: base_time + 1.second) } let!(:merge_request_merged) { create(:merge_request, state: "merged", author: user, assignee: user, source_project: project, target_project: project, title: "Merged test", created_at: base_time + 2.seconds) } - let!(:note) { create(:note_on_merge_request, author: user, project: project, noteable: merge_request, note: "a comment on a MR") } - let!(:note2) { create(:note_on_merge_request, author: user, project: project, noteable: merge_request, note: "another comment on a MR") } - let(:milestone) { create(:milestone, title: '1.0.0', project: project) } + let!(:note) { create(:note_on_merge_request, author: user, project: project, noteable: merge_request, note: "a comment on a MR") } + let!(:note2) { create(:note_on_merge_request, author: user, project: project, noteable: merge_request, note: "another comment on a MR") } + let(:milestone) { create(:milestone, title: '1.0.0', project: project) } before do project.team << [user, :reporters] @@ -315,6 +317,29 @@ describe API::API, api: true do end end + describe "DELETE /projects/:id/merge_requests/:merge_request_id" do + context "when the user is developer" do + let(:developer) { create(:user) } + + before do + project.team << [developer, :developer] + end + + it "denies the deletion of the merge request" do + delete api("/projects/#{project.id}/merge_requests/#{merge_request.id}", developer) + expect(response.status).to be(403) + end + end + + context "when the user is project owner" do + it "destroys the merge request owners can destroy" do + delete api("/projects/#{project.id}/merge_requests/#{merge_request.id}", user) + + expect(response.status).to eq(200) + end + end + end + describe "PUT /projects/:id/merge_requests/:merge_request_id to close MR" do it "should return merge_request" do put api("/projects/#{project.id}/merge_requests/#{merge_request.id}", user), state_event: "close" diff --git a/spec/requests/api/projects_spec.rb b/spec/requests/api/projects_spec.rb index a6699cdc81..a5d4985dc7 100644 --- a/spec/requests/api/projects_spec.rb +++ b/spec/requests/api/projects_spec.rb @@ -275,6 +275,7 @@ describe API::API, api: true do it 'should not allow a non-admin to use a restricted visibility level' do post api('/projects', user), @project + expect(response.status).to eq(400) expect(json_response['message']['visibility_level'].first).to( match('restricted by your GitLab administrator') diff --git a/spec/services/create_snippet_service_spec.rb b/spec/services/create_snippet_service_spec.rb index c800dea04f..7a850066bf 100644 --- a/spec/services/create_snippet_service_spec.rb +++ b/spec/services/create_snippet_service_spec.rb @@ -23,7 +23,7 @@ describe CreateSnippetService, services: true do snippet = create_snippet(nil, @user, @opts) expect(snippet.errors.messages).to have_key(:visibility_level) expect(snippet.errors.messages[:visibility_level].first).to( - match('Public visibility has been restricted') + match('has been restricted') ) end diff --git a/spec/services/groups/create_service_spec.rb b/spec/services/groups/create_service_spec.rb new file mode 100644 index 0000000000..6aefb48a4e --- /dev/null +++ b/spec/services/groups/create_service_spec.rb @@ -0,0 +1,20 @@ +require 'spec_helper' + +describe Groups::CreateService, services: true do + let!(:user) { create(:user) } + let!(:group_params) { { path: "group_path", visibility_level: Gitlab::VisibilityLevel::PUBLIC } } + + describe "execute" do + let!(:service) { described_class.new(user, group_params ) } + subject { service.execute } + + context "create groups without restricted visibility level" do + it { is_expected.to be_persisted } + end + + context "cannot create group with restricted visibility level" do + before { allow(current_application_settings).to receive(:restricted_visibility_levels).and_return([Gitlab::VisibilityLevel::PUBLIC]) } + it { is_expected.to_not be_persisted } + end + end +end diff --git a/spec/services/groups/update_service_spec.rb b/spec/services/groups/update_service_spec.rb new file mode 100644 index 0000000000..9c2331144a --- /dev/null +++ b/spec/services/groups/update_service_spec.rb @@ -0,0 +1,52 @@ +require 'spec_helper' + +describe Groups::UpdateService, services: true do + let!(:user) { create(:user) } + let!(:private_group) { create(:group, :private) } + let!(:internal_group) { create(:group, :internal) } + let!(:public_group) { create(:group, :public) } + + describe "#execute" do + context "project visibility_level validation" do + context "public group with public projects" do + let!(:service) { described_class.new(public_group, user, visibility_level: Gitlab::VisibilityLevel::INTERNAL ) } + + before do + public_group.add_user(user, Gitlab::Access::MASTER) + create(:project, :public, group: public_group) + end + + it "does not change permission level" do + service.execute + expect(public_group.errors.count).to eq(1) + end + end + + context "internal group with internal project" do + let!(:service) { described_class.new(internal_group, user, visibility_level: Gitlab::VisibilityLevel::PRIVATE ) } + + before do + internal_group.add_user(user, Gitlab::Access::MASTER) + create(:project, :internal, group: internal_group) + end + + it "does not change permission level" do + service.execute + expect(internal_group.errors.count).to eq(1) + end + end + end + end + + context "unauthorized visibility_level validation" do + let!(:service) { described_class.new(internal_group, user, visibility_level: 99 ) } + before do + internal_group.add_user(user, Gitlab::Access::MASTER) + end + + it "does not change permission level" do + service.execute + expect(internal_group.errors.count).to eq(1) + end + end +end diff --git a/spec/services/issues/move_service_spec.rb b/spec/services/issues/move_service_spec.rb index 14cc20e529..9b0c73aaf3 100644 --- a/spec/services/issues/move_service_spec.rb +++ b/spec/services/issues/move_service_spec.rb @@ -85,6 +85,10 @@ describe Issues::MoveService, services: true do expect(old_issue.moved?).to eq true expect(old_issue.moved_to).to eq new_issue end + + it 'preserves create time' do + expect(old_issue.created_at).to eq new_issue.created_at + end end context 'issue with notes' do @@ -121,10 +125,23 @@ describe Issues::MoveService, services: true do it 'preserves orignal author of comment' do expect(user_notes.pluck(:author_id)).to all(eq(author.id)) end + end + + context 'note that has been updated' do + let!(:note) do + create(:note, noteable: old_issue, project: old_project, + author: author, updated_at: Date.yesterday, + created_at: Date.yesterday) + end + + include_context 'issue move executed' it 'preserves time when note has been created at' do - expect(old_issue.notes.first.created_at) - .to eq new_issue.notes.first.created_at + expect(new_issue.notes.first.created_at).to eq note.created_at + end + + it 'preserves time when note has been updated at' do + expect(new_issue.notes.first.updated_at).to eq note.updated_at end end @@ -208,6 +225,12 @@ describe Issues::MoveService, services: true do it { expect { move }.to raise_error(StandardError, /permissions/) } end + + context 'issue is not persisted' do + include_context 'user can move issue' + let(:old_issue) { build(:issue, project: old_project, author: author) } + it { expect { move }.to raise_error(StandardError, /permissions/) } + end end end end diff --git a/spec/services/issues/update_service_spec.rb b/spec/services/issues/update_service_spec.rb index 4ffe753fef..6b214a0d96 100644 --- a/spec/services/issues/update_service_spec.rb +++ b/spec/services/issues/update_service_spec.rb @@ -151,7 +151,12 @@ describe Issues::UpdateService, services: true do context 'when the issue is relabeled' do let!(:non_subscriber) { create(:user) } - let!(:subscriber) { create(:user).tap { |u| label.toggle_subscription(u) } } + let!(:subscriber) do + create(:user).tap do |u| + label.toggle_subscription(u) + project.team << [u, :developer] + end + end it 'sends notifications for subscribers of newly added labels' do opts = { label_ids: [label.id] } diff --git a/spec/services/notification_service_spec.rb b/spec/services/notification_service_spec.rb index b5407397c1..0f2aa3ae73 100644 --- a/spec/services/notification_service_spec.rb +++ b/spec/services/notification_service_spec.rb @@ -111,6 +111,33 @@ describe NotificationService, services: true do end end + context 'confidential issue note' do + let(:project) { create(:empty_project, :public) } + let(:author) { create(:user) } + let(:assignee) { create(:user) } + let(:non_member) { create(:user) } + let(:member) { create(:user) } + let(:admin) { create(:admin) } + let(:confidential_issue) { create(:issue, :confidential, project: project, author: author, assignee: assignee) } + let(:note) { create(:note_on_issue, noteable: confidential_issue, project: project, note: "#{author.to_reference} #{assignee.to_reference} #{non_member.to_reference} #{member.to_reference} #{admin.to_reference}") } + + it 'filters out users that can not read the issue' do + project.team << [member, :developer] + + expect(SentNotification).to receive(:record).with(confidential_issue, any_args).exactly(4).times + + ActionMailer::Base.deliveries.clear + + notification.new_note(note) + + should_not_email(non_member) + should_email(author) + should_email(assignee) + should_email(member) + should_email(admin) + end + end + context 'issue note mention' do let(:project) { create(:empty_project, :public) } let(:issue) { create(:issue, project: project, assignee: create(:user)) } @@ -233,6 +260,36 @@ describe NotificationService, services: true do should_email(subscriber) end + + context 'confidential issues' do + let(:author) { create(:user) } + let(:assignee) { create(:user) } + let(:non_member) { create(:user) } + let(:member) { create(:user) } + let(:admin) { create(:admin) } + let(:confidential_issue) { create(:issue, :confidential, project: project, title: 'Confidential issue', author: author, assignee: assignee) } + + it "emails subscribers of the issue's labels that can read the issue" do + project.team << [member, :developer] + + label = create(:label, issues: [confidential_issue]) + label.toggle_subscription(non_member) + label.toggle_subscription(author) + label.toggle_subscription(assignee) + label.toggle_subscription(member) + label.toggle_subscription(admin) + + ActionMailer::Base.deliveries.clear + + notification.new_issue(confidential_issue, @u_disabled) + + should_not_email(non_member) + should_not_email(author) + should_email(assignee) + should_email(member) + should_email(admin) + end + end end describe :reassigned_issue do @@ -332,6 +389,37 @@ describe NotificationService, services: true do should_not_email(subscriber_to_label) should_email(subscriber_to_label2) end + + context 'confidential issues' do + let(:author) { create(:user) } + let(:assignee) { create(:user) } + let(:non_member) { create(:user) } + let(:member) { create(:user) } + let(:admin) { create(:admin) } + let(:confidential_issue) { create(:issue, :confidential, project: project, title: 'Confidential issue', author: author, assignee: assignee) } + let!(:label_1) { create(:label, issues: [confidential_issue]) } + let!(:label_2) { create(:label) } + + it "emails subscribers of the issue's labels that can read the issue" do + project.team << [member, :developer] + + label_2.toggle_subscription(non_member) + label_2.toggle_subscription(author) + label_2.toggle_subscription(assignee) + label_2.toggle_subscription(member) + label_2.toggle_subscription(admin) + + ActionMailer::Base.deliveries.clear + + notification.relabeled_issue(confidential_issue, [label_2], @u_disabled) + + should_not_email(non_member) + should_email(author) + should_email(assignee) + should_email(member) + should_email(admin) + end + end end describe :close_issue do diff --git a/spec/services/update_snippet_service_spec.rb b/spec/services/update_snippet_service_spec.rb index 48d114896d..37c2e86136 100644 --- a/spec/services/update_snippet_service_spec.rb +++ b/spec/services/update_snippet_service_spec.rb @@ -25,7 +25,7 @@ describe UpdateSnippetService, services: true do update_snippet(@project, @user, @snippet, @opts) expect(@snippet.errors.messages).to have_key(:visibility_level) expect(@snippet.errors.messages[:visibility_level].first).to( - match('Public visibility has been restricted') + match('has been restricted') ) expect(@snippet.visibility_level).to eq(old_visibility) end diff --git a/spec/support/matchers/access_matchers.rb b/spec/support/matchers/access_matchers.rb index 4e007c777e..0497e39186 100644 --- a/spec/support/matchers/access_matchers.rb +++ b/spec/support/matchers/access_matchers.rb @@ -28,7 +28,7 @@ module AccessMatchers if user.kind_of?(User) # User#inspect displays too much information for RSpec's description # messages - "be #{type} for supplied User" + "be #{type} for the specified user" else "be #{type} for #{user}" end diff --git a/spec/tasks/gitlab/backup_rake_spec.rb b/spec/tasks/gitlab/backup_rake_spec.rb index 63bed2414d..320be9a0b6 100644 --- a/spec/tasks/gitlab/backup_rake_spec.rb +++ b/spec/tasks/gitlab/backup_rake_spec.rb @@ -3,9 +3,10 @@ require 'rake' describe 'gitlab:app namespace rake task' do before :all do - Rake.application.rake_require "tasks/gitlab/task_helpers" - Rake.application.rake_require "tasks/gitlab/backup" - Rake.application.rake_require "tasks/gitlab/shell" + Rake.application.rake_require 'tasks/gitlab/task_helpers' + Rake.application.rake_require 'tasks/gitlab/backup' + Rake.application.rake_require 'tasks/gitlab/shell' + Rake.application.rake_require 'tasks/gitlab/db' # empty task as env is already loaded Rake::Task.define_task :environment end @@ -37,6 +38,7 @@ describe 'gitlab:app namespace rake task' do allow(FileUtils).to receive(:mv).and_return(true) allow(Rake::Task["gitlab:shell:setup"]). to receive(:invoke).and_return(true) + ENV['force'] = 'yes' end let(:gitlab_version) { Gitlab::VERSION } @@ -52,13 +54,14 @@ describe 'gitlab:app namespace rake task' do it 'should invoke restoration on match' do allow(YAML).to receive(:load_file). and_return({ gitlab_version: gitlab_version }) - expect(Rake::Task["gitlab:backup:db:restore"]).to receive(:invoke) - expect(Rake::Task["gitlab:backup:repo:restore"]).to receive(:invoke) - expect(Rake::Task["gitlab:backup:builds:restore"]).to receive(:invoke) - expect(Rake::Task["gitlab:backup:uploads:restore"]).to receive(:invoke) - expect(Rake::Task["gitlab:backup:artifacts:restore"]).to receive(:invoke) - expect(Rake::Task["gitlab:backup:lfs:restore"]).to receive(:invoke) - expect(Rake::Task["gitlab:shell:setup"]).to receive(:invoke) + expect(Rake::Task['gitlab:db:drop_tables']).to receive(:invoke) + expect(Rake::Task['gitlab:backup:db:restore']).to receive(:invoke) + expect(Rake::Task['gitlab:backup:repo:restore']).to receive(:invoke) + expect(Rake::Task['gitlab:backup:builds:restore']).to receive(:invoke) + expect(Rake::Task['gitlab:backup:uploads:restore']).to receive(:invoke) + expect(Rake::Task['gitlab:backup:artifacts:restore']).to receive(:invoke) + expect(Rake::Task['gitlab:backup:lfs:restore']).to receive(:invoke) + expect(Rake::Task['gitlab:shell:setup']).to receive(:invoke) expect { run_rake_task('gitlab:backup:restore') }.not_to raise_error end end @@ -177,17 +180,18 @@ describe 'gitlab:app namespace rake task' do end it 'does not invoke repositories restore' do - allow(Rake::Task["gitlab:shell:setup"]). + allow(Rake::Task['gitlab:shell:setup']). to receive(:invoke).and_return(true) allow($stdout).to receive :write - expect(Rake::Task["gitlab:backup:db:restore"]).to receive :invoke - expect(Rake::Task["gitlab:backup:repo:restore"]).not_to receive :invoke - expect(Rake::Task["gitlab:backup:uploads:restore"]).not_to receive :invoke - expect(Rake::Task["gitlab:backup:builds:restore"]).to receive :invoke - expect(Rake::Task["gitlab:backup:artifacts:restore"]).to receive :invoke - expect(Rake::Task["gitlab:backup:lfs:restore"]).to receive :invoke - expect(Rake::Task["gitlab:shell:setup"]).to receive :invoke + expect(Rake::Task['gitlab:db:drop_tables']).to receive :invoke + expect(Rake::Task['gitlab:backup:db:restore']).to receive :invoke + expect(Rake::Task['gitlab:backup:repo:restore']).not_to receive :invoke + expect(Rake::Task['gitlab:backup:uploads:restore']).not_to receive :invoke + expect(Rake::Task['gitlab:backup:builds:restore']).to receive :invoke + expect(Rake::Task['gitlab:backup:artifacts:restore']).to receive :invoke + expect(Rake::Task['gitlab:backup:lfs:restore']).to receive :invoke + expect(Rake::Task['gitlab:shell:setup']).to receive :invoke expect { run_rake_task('gitlab:backup:restore') }.not_to raise_error end end diff --git a/vendor/assets/javascripts/cropper.js b/vendor/assets/javascripts/cropper.js new file mode 100644 index 0000000000..805485904a --- /dev/null +++ b/vendor/assets/javascripts/cropper.js @@ -0,0 +1,2993 @@ +/*! + * Cropper v2.3.0 + * https://github.com/fengyuanchen/cropper + * + * Copyright (c) 2014-2016 Fengyuan Chen and contributors + * Released under the MIT license + * + * Date: 2016-02-22T02:13:13.332Z + */ + +(function (factory) { + if (typeof define === 'function' && define.amd) { + // AMD. Register as anonymous module. + define(['jquery'], factory); + } else if (typeof exports === 'object') { + // Node / CommonJS + factory(require('jquery')); + } else { + // Browser globals. + factory(jQuery); + } +})(function ($) { + + 'use strict'; + + // Globals + var $window = $(window); + var $document = $(document); + var location = window.location; + var navigator = window.navigator; + var ArrayBuffer = window.ArrayBuffer; + var Uint8Array = window.Uint8Array; + var DataView = window.DataView; + var btoa = window.btoa; + + // Constants + var NAMESPACE = 'cropper'; + + // Classes + var CLASS_MODAL = 'cropper-modal'; + var CLASS_HIDE = 'cropper-hide'; + var CLASS_HIDDEN = 'cropper-hidden'; + var CLASS_INVISIBLE = 'cropper-invisible'; + var CLASS_MOVE = 'cropper-move'; + var CLASS_CROP = 'cropper-crop'; + var CLASS_DISABLED = 'cropper-disabled'; + var CLASS_BG = 'cropper-bg'; + + // Events + var EVENT_MOUSE_DOWN = 'mousedown touchstart pointerdown MSPointerDown'; + var EVENT_MOUSE_MOVE = 'mousemove touchmove pointermove MSPointerMove'; + var EVENT_MOUSE_UP = 'mouseup touchend touchcancel pointerup pointercancel MSPointerUp MSPointerCancel'; + var EVENT_WHEEL = 'wheel mousewheel DOMMouseScroll'; + var EVENT_DBLCLICK = 'dblclick'; + var EVENT_LOAD = 'load.' + NAMESPACE; + var EVENT_ERROR = 'error.' + NAMESPACE; + var EVENT_RESIZE = 'resize.' + NAMESPACE; // Bind to window with namespace + var EVENT_BUILD = 'build.' + NAMESPACE; + var EVENT_BUILT = 'built.' + NAMESPACE; + var EVENT_CROP_START = 'cropstart.' + NAMESPACE; + var EVENT_CROP_MOVE = 'cropmove.' + NAMESPACE; + var EVENT_CROP_END = 'cropend.' + NAMESPACE; + var EVENT_CROP = 'crop.' + NAMESPACE; + var EVENT_ZOOM = 'zoom.' + NAMESPACE; + + // RegExps + var REGEXP_ACTIONS = /e|w|s|n|se|sw|ne|nw|all|crop|move|zoom/; + var REGEXP_DATA_URL = /^data\:/; + var REGEXP_DATA_URL_HEAD = /^data\:([^\;]+)\;base64,/; + var REGEXP_DATA_URL_JPEG = /^data\:image\/jpeg.*;base64,/; + + // Data keys + var DATA_PREVIEW = 'preview'; + var DATA_ACTION = 'action'; + + // Actions + var ACTION_EAST = 'e'; + var ACTION_WEST = 'w'; + var ACTION_SOUTH = 's'; + var ACTION_NORTH = 'n'; + var ACTION_SOUTH_EAST = 'se'; + var ACTION_SOUTH_WEST = 'sw'; + var ACTION_NORTH_EAST = 'ne'; + var ACTION_NORTH_WEST = 'nw'; + var ACTION_ALL = 'all'; + var ACTION_CROP = 'crop'; + var ACTION_MOVE = 'move'; + var ACTION_ZOOM = 'zoom'; + var ACTION_NONE = 'none'; + + // Supports + var SUPPORT_CANVAS = $.isFunction($('')[0].getContext); + var IS_SAFARI = navigator && /safari/i.test(navigator.userAgent) && /apple computer/i.test(navigator.vendor); + + // Maths + var num = Number; + var min = Math.min; + var max = Math.max; + var abs = Math.abs; + var sin = Math.sin; + var cos = Math.cos; + var sqrt = Math.sqrt; + var round = Math.round; + var floor = Math.floor; + + // Utilities + var fromCharCode = String.fromCharCode; + + function isNumber(n) { + return typeof n === 'number' && !isNaN(n); + } + + function isUndefined(n) { + return typeof n === 'undefined'; + } + + function toArray(obj, offset) { + var args = []; + + // This is necessary for IE8 + if (isNumber(offset)) { + args.push(offset); + } + + return args.slice.apply(obj, args); + } + + // Custom proxy to avoid jQuery's guid + function proxy(fn, context) { + var args = toArray(arguments, 2); + + return function () { + return fn.apply(context, args.concat(toArray(arguments))); + }; + } + + function isCrossOriginURL(url) { + var parts = url.match(/^(https?:)\/\/([^\:\/\?#]+):?(\d*)/i); + + return parts && ( + parts[1] !== location.protocol || + parts[2] !== location.hostname || + parts[3] !== location.port + ); + } + + function addTimestamp(url) { + var timestamp = 'timestamp=' + (new Date()).getTime(); + + return (url + (url.indexOf('?') === -1 ? '?' : '&') + timestamp); + } + + function getCrossOrigin(crossOrigin) { + return crossOrigin ? ' crossOrigin="' + crossOrigin + '"' : ''; + } + + function getImageSize(image, callback) { + var newImage; + + // Modern browsers (ignore Safari, #120 & #509) + if (image.naturalWidth && !IS_SAFARI) { + return callback(image.naturalWidth, image.naturalHeight); + } + + // IE8: Don't use `new Image()` here (#319) + newImage = document.createElement('img'); + + newImage.onload = function () { + callback(this.width, this.height); + }; + + newImage.src = image.src; + } + + function getTransform(options) { + var transforms = []; + var rotate = options.rotate; + var scaleX = options.scaleX; + var scaleY = options.scaleY; + + if (isNumber(rotate)) { + transforms.push('rotate(' + rotate + 'deg)'); + } + + if (isNumber(scaleX) && isNumber(scaleY)) { + transforms.push('scale(' + scaleX + ',' + scaleY + ')'); + } + + return transforms.length ? transforms.join(' ') : 'none'; + } + + function getRotatedSizes(data, isReversed) { + var deg = abs(data.degree) % 180; + var arc = (deg > 90 ? (180 - deg) : deg) * Math.PI / 180; + var sinArc = sin(arc); + var cosArc = cos(arc); + var width = data.width; + var height = data.height; + var aspectRatio = data.aspectRatio; + var newWidth; + var newHeight; + + if (!isReversed) { + newWidth = width * cosArc + height * sinArc; + newHeight = width * sinArc + height * cosArc; + } else { + newWidth = width / (cosArc + sinArc / aspectRatio); + newHeight = newWidth / aspectRatio; + } + + return { + width: newWidth, + height: newHeight + }; + } + + function getSourceCanvas(image, data) { + var canvas = $('')[0]; + var context = canvas.getContext('2d'); + var dstX = 0; + var dstY = 0; + var dstWidth = data.naturalWidth; + var dstHeight = data.naturalHeight; + var rotate = data.rotate; + var scaleX = data.scaleX; + var scaleY = data.scaleY; + var scalable = isNumber(scaleX) && isNumber(scaleY) && (scaleX !== 1 || scaleY !== 1); + var rotatable = isNumber(rotate) && rotate !== 0; + var advanced = rotatable || scalable; + var canvasWidth = dstWidth * abs(scaleX || 1); + var canvasHeight = dstHeight * abs(scaleY || 1); + var translateX; + var translateY; + var rotated; + + if (scalable) { + translateX = canvasWidth / 2; + translateY = canvasHeight / 2; + } + + if (rotatable) { + rotated = getRotatedSizes({ + width: canvasWidth, + height: canvasHeight, + degree: rotate + }); + + canvasWidth = rotated.width; + canvasHeight = rotated.height; + translateX = canvasWidth / 2; + translateY = canvasHeight / 2; + } + + canvas.width = canvasWidth; + canvas.height = canvasHeight; + + if (advanced) { + dstX = -dstWidth / 2; + dstY = -dstHeight / 2; + + context.save(); + context.translate(translateX, translateY); + } + + if (rotatable) { + context.rotate(rotate * Math.PI / 180); + } + + // Should call `scale` after rotated + if (scalable) { + context.scale(scaleX, scaleY); + } + + context.drawImage(image, floor(dstX), floor(dstY), floor(dstWidth), floor(dstHeight)); + + if (advanced) { + context.restore(); + } + + return canvas; + } + + function getTouchesCenter(touches) { + var length = touches.length; + var pageX = 0; + var pageY = 0; + + if (length) { + $.each(touches, function (i, touch) { + pageX += touch.pageX; + pageY += touch.pageY; + }); + + pageX /= length; + pageY /= length; + } + + return { + pageX: pageX, + pageY: pageY + }; + } + + function getStringFromCharCode(dataView, start, length) { + var str = ''; + var i; + + for (i = start, length += start; i < length; i++) { + str += fromCharCode(dataView.getUint8(i)); + } + + return str; + } + + function getOrientation(arrayBuffer) { + var dataView = new DataView(arrayBuffer); + var length = dataView.byteLength; + var orientation; + var exifIDCode; + var tiffOffset; + var firstIFDOffset; + var littleEndian; + var endianness; + var app1Start; + var ifdStart; + var offset; + var i; + + // Only handle JPEG image (start by 0xFFD8) + if (dataView.getUint8(0) === 0xFF && dataView.getUint8(1) === 0xD8) { + offset = 2; + + while (offset < length) { + if (dataView.getUint8(offset) === 0xFF && dataView.getUint8(offset + 1) === 0xE1) { + app1Start = offset; + break; + } + + offset++; + } + } + + if (app1Start) { + exifIDCode = app1Start + 4; + tiffOffset = app1Start + 10; + + if (getStringFromCharCode(dataView, exifIDCode, 4) === 'Exif') { + endianness = dataView.getUint16(tiffOffset); + littleEndian = endianness === 0x4949; + + if (littleEndian || endianness === 0x4D4D /* bigEndian */) { + if (dataView.getUint16(tiffOffset + 2, littleEndian) === 0x002A) { + firstIFDOffset = dataView.getUint32(tiffOffset + 4, littleEndian); + + if (firstIFDOffset >= 0x00000008) { + ifdStart = tiffOffset + firstIFDOffset; + } + } + } + } + } + + if (ifdStart) { + length = dataView.getUint16(ifdStart, littleEndian); + + for (i = 0; i < length; i++) { + offset = ifdStart + i * 12 + 2; + + if (dataView.getUint16(offset, littleEndian) === 0x0112 /* Orientation */) { + + // 8 is the offset of the current tag's value + offset += 8; + + // Get the original orientation value + orientation = dataView.getUint16(offset, littleEndian); + + // Override the orientation with its default value for Safari (#120) + if (IS_SAFARI) { + dataView.setUint16(offset, 1, littleEndian); + } + + break; + } + } + } + + return orientation; + } + + function dataURLToArrayBuffer(dataURL) { + var base64 = dataURL.replace(REGEXP_DATA_URL_HEAD, ''); + var binary = atob(base64); + var length = binary.length; + var arrayBuffer = new ArrayBuffer(length); + var dataView = new Uint8Array(arrayBuffer); + var i; + + for (i = 0; i < length; i++) { + dataView[i] = binary.charCodeAt(i); + } + + return arrayBuffer; + } + + // Only available for JPEG image + function arrayBufferToDataURL(arrayBuffer) { + var dataView = new Uint8Array(arrayBuffer); + var length = dataView.length; + var base64 = ''; + var i; + + for (i = 0; i < length; i++) { + base64 += fromCharCode(dataView[i]); + } + + return 'data:image/jpeg;base64,' + btoa(base64); + } + + function Cropper(element, options) { + this.$element = $(element); + this.options = $.extend({}, Cropper.DEFAULTS, $.isPlainObject(options) && options); + this.isLoaded = false; + this.isBuilt = false; + this.isCompleted = false; + this.isRotated = false; + this.isCropped = false; + this.isDisabled = false; + this.isReplaced = false; + this.isLimited = false; + this.wheeling = false; + this.isImg = false; + this.originalUrl = ''; + this.canvas = null; + this.cropBox = null; + this.init(); + } + + Cropper.prototype = { + constructor: Cropper, + + init: function () { + var $this = this.$element; + var url; + + if ($this.is('img')) { + this.isImg = true; + + // Should use `$.fn.attr` here. e.g.: "img/picture.jpg" + this.originalUrl = url = $this.attr('src'); + + // Stop when it's a blank image + if (!url) { + return; + } + + // Should use `$.fn.prop` here. e.g.: "http://example.com/img/picture.jpg" + url = $this.prop('src'); + } else if ($this.is('canvas') && SUPPORT_CANVAS) { + url = $this[0].toDataURL(); + } + + this.load(url); + }, + + // A shortcut for triggering custom events + trigger: function (type, data) { + var e = $.Event(type, data); + + this.$element.trigger(e); + + return e; + }, + + load: function (url) { + var options = this.options; + var $this = this.$element; + var read; + var xhr; + + if (!url) { + return; + } + + // Trigger build event first + $this.one(EVENT_BUILD, options.build); + + if (this.trigger(EVENT_BUILD).isDefaultPrevented()) { + return; + } + + this.url = url; + this.image = {}; + + if (!options.checkOrientation || !ArrayBuffer) { + return this.clone(); + } + + read = $.proxy(this.read, this); + + // XMLHttpRequest disallows to open a Data URL in some browsers like IE11 and Safari + if (REGEXP_DATA_URL.test(url)) { + return REGEXP_DATA_URL_JPEG.test(url) ? + read(dataURLToArrayBuffer(url)) : + this.clone(); + } + + xhr = new XMLHttpRequest(); + + xhr.onerror = xhr.onabort = $.proxy(function () { + this.clone(); + }, this); + + xhr.onload = function () { + read(this.response); + }; + + xhr.open('get', url); + xhr.responseType = 'arraybuffer'; + xhr.send(); + }, + + read: function (arrayBuffer) { + var options = this.options; + var orientation = getOrientation(arrayBuffer); + var image = this.image; + var rotate; + var scaleX; + var scaleY; + + if (orientation > 1) { + this.url = arrayBufferToDataURL(arrayBuffer); + + switch (orientation) { + + // flip horizontal + case 2: + scaleX = -1; + break; + + // rotate left 180° + case 3: + rotate = -180; + break; + + // flip vertical + case 4: + scaleY = -1; + break; + + // flip vertical + rotate right 90° + case 5: + rotate = 90; + scaleY = -1; + break; + + // rotate right 90° + case 6: + rotate = 90; + break; + + // flip horizontal + rotate right 90° + case 7: + rotate = 90; + scaleX = -1; + break; + + // rotate left 90° + case 8: + rotate = -90; + break; + } + } + + if (options.rotatable) { + image.rotate = rotate; + } + + if (options.scalable) { + image.scaleX = scaleX; + image.scaleY = scaleY; + } + + this.clone(); + }, + + clone: function () { + var options = this.options; + var $this = this.$element; + var url = this.url; + var crossOrigin = ''; + var crossOriginUrl; + var $clone; + + if (options.checkCrossOrigin && isCrossOriginURL(url)) { + crossOrigin = $this.prop('crossOrigin'); + + if (crossOrigin) { + crossOriginUrl = url; + } else { + crossOrigin = 'anonymous'; + + // Bust cache (#148) when there is not a "crossOrigin" property + crossOriginUrl = addTimestamp(url); + } + } + + this.crossOrigin = crossOrigin; + this.crossOriginUrl = crossOriginUrl; + this.$clone = $clone = $(''); + + if (this.isImg) { + if ($this[0].complete) { + this.start(); + } else { + $this.one(EVENT_LOAD, $.proxy(this.start, this)); + } + } else { + $clone. + one(EVENT_LOAD, $.proxy(this.start, this)). + one(EVENT_ERROR, $.proxy(this.stop, this)). + addClass(CLASS_HIDE). + insertAfter($this); + } + }, + + start: function () { + var $image = this.$element; + var $clone = this.$clone; + + if (!this.isImg) { + $clone.off(EVENT_ERROR, this.stop); + $image = $clone; + } + + getImageSize($image[0], $.proxy(function (naturalWidth, naturalHeight) { + $.extend(this.image, { + naturalWidth: naturalWidth, + naturalHeight: naturalHeight, + aspectRatio: naturalWidth / naturalHeight + }); + + this.isLoaded = true; + this.build(); + }, this)); + }, + + stop: function () { + this.$clone.remove(); + this.$clone = null; + }, + + build: function () { + var options = this.options; + var $this = this.$element; + var $clone = this.$clone; + var $cropper; + var $cropBox; + var $face; + + if (!this.isLoaded) { + return; + } + + // Unbuild first when replace + if (this.isBuilt) { + this.unbuild(); + } + + // Create cropper elements + this.$container = $this.parent(); + this.$cropper = $cropper = $(Cropper.TEMPLATE); + this.$canvas = $cropper.find('.cropper-canvas').append($clone); + this.$dragBox = $cropper.find('.cropper-drag-box'); + this.$cropBox = $cropBox = $cropper.find('.cropper-crop-box'); + this.$viewBox = $cropper.find('.cropper-view-box'); + this.$face = $face = $cropBox.find('.cropper-face'); + + // Hide the original image + $this.addClass(CLASS_HIDDEN).after($cropper); + + // Show the clone image if is hidden + if (!this.isImg) { + $clone.removeClass(CLASS_HIDE); + } + + this.initPreview(); + this.bind(); + + options.aspectRatio = max(0, options.aspectRatio) || NaN; + options.viewMode = max(0, min(3, round(options.viewMode))) || 0; + + if (options.autoCrop) { + this.isCropped = true; + + if (options.modal) { + this.$dragBox.addClass(CLASS_MODAL); + } + } else { + $cropBox.addClass(CLASS_HIDDEN); + } + + if (!options.guides) { + $cropBox.find('.cropper-dashed').addClass(CLASS_HIDDEN); + } + + if (!options.center) { + $cropBox.find('.cropper-center').addClass(CLASS_HIDDEN); + } + + if (options.cropBoxMovable) { + $face.addClass(CLASS_MOVE).data(DATA_ACTION, ACTION_ALL); + } + + if (!options.highlight) { + $face.addClass(CLASS_INVISIBLE); + } + + if (options.background) { + $cropper.addClass(CLASS_BG); + } + + if (!options.cropBoxResizable) { + $cropBox.find('.cropper-line, .cropper-point').addClass(CLASS_HIDDEN); + } + + this.setDragMode(options.dragMode); + this.render(); + this.isBuilt = true; + this.setData(options.data); + $this.one(EVENT_BUILT, options.built); + + // Trigger the built event asynchronously to keep `data('cropper')` is defined + setTimeout($.proxy(function () { + this.trigger(EVENT_BUILT); + this.isCompleted = true; + }, this), 0); + }, + + unbuild: function () { + if (!this.isBuilt) { + return; + } + + this.isBuilt = false; + this.isCompleted = false; + this.initialImage = null; + + // Clear `initialCanvas` is necessary when replace + this.initialCanvas = null; + this.initialCropBox = null; + this.container = null; + this.canvas = null; + + // Clear `cropBox` is necessary when replace + this.cropBox = null; + this.unbind(); + + this.resetPreview(); + this.$preview = null; + + this.$viewBox = null; + this.$cropBox = null; + this.$dragBox = null; + this.$canvas = null; + this.$container = null; + + this.$cropper.remove(); + this.$cropper = null; + }, + + render: function () { + this.initContainer(); + this.initCanvas(); + this.initCropBox(); + + this.renderCanvas(); + + if (this.isCropped) { + this.renderCropBox(); + } + }, + + initContainer: function () { + var options = this.options; + var $this = this.$element; + var $container = this.$container; + var $cropper = this.$cropper; + + $cropper.addClass(CLASS_HIDDEN); + $this.removeClass(CLASS_HIDDEN); + + $cropper.css((this.container = { + width: max($container.width(), num(options.minContainerWidth) || 200), + height: max($container.height(), num(options.minContainerHeight) || 100) + })); + + $this.addClass(CLASS_HIDDEN); + $cropper.removeClass(CLASS_HIDDEN); + }, + + // Canvas (image wrapper) + initCanvas: function () { + var viewMode = this.options.viewMode; + var container = this.container; + var containerWidth = container.width; + var containerHeight = container.height; + var image = this.image; + var imageNaturalWidth = image.naturalWidth; + var imageNaturalHeight = image.naturalHeight; + var is90Degree = abs(image.rotate) === 90; + var naturalWidth = is90Degree ? imageNaturalHeight : imageNaturalWidth; + var naturalHeight = is90Degree ? imageNaturalWidth : imageNaturalHeight; + var aspectRatio = naturalWidth / naturalHeight; + var canvasWidth = containerWidth; + var canvasHeight = containerHeight; + var canvas; + + if (containerHeight * aspectRatio > containerWidth) { + if (viewMode === 3) { + canvasWidth = containerHeight * aspectRatio; + } else { + canvasHeight = containerWidth / aspectRatio; + } + } else { + if (viewMode === 3) { + canvasHeight = containerWidth / aspectRatio; + } else { + canvasWidth = containerHeight * aspectRatio; + } + } + + canvas = { + naturalWidth: naturalWidth, + naturalHeight: naturalHeight, + aspectRatio: aspectRatio, + width: canvasWidth, + height: canvasHeight + }; + + canvas.oldLeft = canvas.left = (containerWidth - canvasWidth) / 2; + canvas.oldTop = canvas.top = (containerHeight - canvasHeight) / 2; + + this.canvas = canvas; + this.isLimited = (viewMode === 1 || viewMode === 2); + this.limitCanvas(true, true); + this.initialImage = $.extend({}, image); + this.initialCanvas = $.extend({}, canvas); + }, + + limitCanvas: function (isSizeLimited, isPositionLimited) { + var options = this.options; + var viewMode = options.viewMode; + var container = this.container; + var containerWidth = container.width; + var containerHeight = container.height; + var canvas = this.canvas; + var aspectRatio = canvas.aspectRatio; + var cropBox = this.cropBox; + var isCropped = this.isCropped && cropBox; + var minCanvasWidth; + var minCanvasHeight; + var newCanvasLeft; + var newCanvasTop; + + if (isSizeLimited) { + minCanvasWidth = num(options.minCanvasWidth) || 0; + minCanvasHeight = num(options.minCanvasHeight) || 0; + + if (viewMode) { + if (viewMode > 1) { + minCanvasWidth = max(minCanvasWidth, containerWidth); + minCanvasHeight = max(minCanvasHeight, containerHeight); + + if (viewMode === 3) { + if (minCanvasHeight * aspectRatio > minCanvasWidth) { + minCanvasWidth = minCanvasHeight * aspectRatio; + } else { + minCanvasHeight = minCanvasWidth / aspectRatio; + } + } + } else { + if (minCanvasWidth) { + minCanvasWidth = max(minCanvasWidth, isCropped ? cropBox.width : 0); + } else if (minCanvasHeight) { + minCanvasHeight = max(minCanvasHeight, isCropped ? cropBox.height : 0); + } else if (isCropped) { + minCanvasWidth = cropBox.width; + minCanvasHeight = cropBox.height; + + if (minCanvasHeight * aspectRatio > minCanvasWidth) { + minCanvasWidth = minCanvasHeight * aspectRatio; + } else { + minCanvasHeight = minCanvasWidth / aspectRatio; + } + } + } + } + + if (minCanvasWidth && minCanvasHeight) { + if (minCanvasHeight * aspectRatio > minCanvasWidth) { + minCanvasHeight = minCanvasWidth / aspectRatio; + } else { + minCanvasWidth = minCanvasHeight * aspectRatio; + } + } else if (minCanvasWidth) { + minCanvasHeight = minCanvasWidth / aspectRatio; + } else if (minCanvasHeight) { + minCanvasWidth = minCanvasHeight * aspectRatio; + } + + canvas.minWidth = minCanvasWidth; + canvas.minHeight = minCanvasHeight; + canvas.maxWidth = Infinity; + canvas.maxHeight = Infinity; + } + + if (isPositionLimited) { + if (viewMode) { + newCanvasLeft = containerWidth - canvas.width; + newCanvasTop = containerHeight - canvas.height; + + canvas.minLeft = min(0, newCanvasLeft); + canvas.minTop = min(0, newCanvasTop); + canvas.maxLeft = max(0, newCanvasLeft); + canvas.maxTop = max(0, newCanvasTop); + + if (isCropped && this.isLimited) { + canvas.minLeft = min( + cropBox.left, + cropBox.left + cropBox.width - canvas.width + ); + canvas.minTop = min( + cropBox.top, + cropBox.top + cropBox.height - canvas.height + ); + canvas.maxLeft = cropBox.left; + canvas.maxTop = cropBox.top; + + if (viewMode === 2) { + if (canvas.width >= containerWidth) { + canvas.minLeft = min(0, newCanvasLeft); + canvas.maxLeft = max(0, newCanvasLeft); + } + + if (canvas.height >= containerHeight) { + canvas.minTop = min(0, newCanvasTop); + canvas.maxTop = max(0, newCanvasTop); + } + } + } + } else { + canvas.minLeft = -canvas.width; + canvas.minTop = -canvas.height; + canvas.maxLeft = containerWidth; + canvas.maxTop = containerHeight; + } + } + }, + + renderCanvas: function (isChanged) { + var canvas = this.canvas; + var image = this.image; + var rotate = image.rotate; + var naturalWidth = image.naturalWidth; + var naturalHeight = image.naturalHeight; + var aspectRatio; + var rotated; + + if (this.isRotated) { + this.isRotated = false; + + // Computes rotated sizes with image sizes + rotated = getRotatedSizes({ + width: image.width, + height: image.height, + degree: rotate + }); + + aspectRatio = rotated.width / rotated.height; + + if (aspectRatio !== canvas.aspectRatio) { + canvas.left -= (rotated.width - canvas.width) / 2; + canvas.top -= (rotated.height - canvas.height) / 2; + canvas.width = rotated.width; + canvas.height = rotated.height; + canvas.aspectRatio = aspectRatio; + canvas.naturalWidth = naturalWidth; + canvas.naturalHeight = naturalHeight; + + // Computes rotated sizes with natural image sizes + if (rotate % 180) { + rotated = getRotatedSizes({ + width: naturalWidth, + height: naturalHeight, + degree: rotate + }); + + canvas.naturalWidth = rotated.width; + canvas.naturalHeight = rotated.height; + } + + this.limitCanvas(true, false); + } + } + + if (canvas.width > canvas.maxWidth || canvas.width < canvas.minWidth) { + canvas.left = canvas.oldLeft; + } + + if (canvas.height > canvas.maxHeight || canvas.height < canvas.minHeight) { + canvas.top = canvas.oldTop; + } + + canvas.width = min(max(canvas.width, canvas.minWidth), canvas.maxWidth); + canvas.height = min(max(canvas.height, canvas.minHeight), canvas.maxHeight); + + this.limitCanvas(false, true); + + canvas.oldLeft = canvas.left = min(max(canvas.left, canvas.minLeft), canvas.maxLeft); + canvas.oldTop = canvas.top = min(max(canvas.top, canvas.minTop), canvas.maxTop); + + this.$canvas.css({ + width: canvas.width, + height: canvas.height, + left: canvas.left, + top: canvas.top + }); + + this.renderImage(); + + if (this.isCropped && this.isLimited) { + this.limitCropBox(true, true); + } + + if (isChanged) { + this.output(); + } + }, + + renderImage: function (isChanged) { + var canvas = this.canvas; + var image = this.image; + var reversed; + + if (image.rotate) { + reversed = getRotatedSizes({ + width: canvas.width, + height: canvas.height, + degree: image.rotate, + aspectRatio: image.aspectRatio + }, true); + } + + $.extend(image, reversed ? { + width: reversed.width, + height: reversed.height, + left: (canvas.width - reversed.width) / 2, + top: (canvas.height - reversed.height) / 2 + } : { + width: canvas.width, + height: canvas.height, + left: 0, + top: 0 + }); + + this.$clone.css({ + width: image.width, + height: image.height, + marginLeft: image.left, + marginTop: image.top, + transform: getTransform(image) + }); + + if (isChanged) { + this.output(); + } + }, + + initCropBox: function () { + var options = this.options; + var canvas = this.canvas; + var aspectRatio = options.aspectRatio; + var autoCropArea = num(options.autoCropArea) || 0.8; + var cropBox = { + width: canvas.width, + height: canvas.height + }; + + if (aspectRatio) { + if (canvas.height * aspectRatio > canvas.width) { + cropBox.height = cropBox.width / aspectRatio; + } else { + cropBox.width = cropBox.height * aspectRatio; + } + } + + this.cropBox = cropBox; + this.limitCropBox(true, true); + + // Initialize auto crop area + cropBox.width = min(max(cropBox.width, cropBox.minWidth), cropBox.maxWidth); + cropBox.height = min(max(cropBox.height, cropBox.minHeight), cropBox.maxHeight); + + // The width of auto crop area must large than "minWidth", and the height too. (#164) + cropBox.width = max(cropBox.minWidth, cropBox.width * autoCropArea); + cropBox.height = max(cropBox.minHeight, cropBox.height * autoCropArea); + cropBox.oldLeft = cropBox.left = canvas.left + (canvas.width - cropBox.width) / 2; + cropBox.oldTop = cropBox.top = canvas.top + (canvas.height - cropBox.height) / 2; + + this.initialCropBox = $.extend({}, cropBox); + }, + + limitCropBox: function (isSizeLimited, isPositionLimited) { + var options = this.options; + var aspectRatio = options.aspectRatio; + var container = this.container; + var containerWidth = container.width; + var containerHeight = container.height; + var canvas = this.canvas; + var cropBox = this.cropBox; + var isLimited = this.isLimited; + var minCropBoxWidth; + var minCropBoxHeight; + var maxCropBoxWidth; + var maxCropBoxHeight; + + if (isSizeLimited) { + minCropBoxWidth = num(options.minCropBoxWidth) || 0; + minCropBoxHeight = num(options.minCropBoxHeight) || 0; + + // The min/maxCropBoxWidth/Height must be less than containerWidth/Height + minCropBoxWidth = min(minCropBoxWidth, containerWidth); + minCropBoxHeight = min(minCropBoxHeight, containerHeight); + maxCropBoxWidth = min(containerWidth, isLimited ? canvas.width : containerWidth); + maxCropBoxHeight = min(containerHeight, isLimited ? canvas.height : containerHeight); + + if (aspectRatio) { + if (minCropBoxWidth && minCropBoxHeight) { + if (minCropBoxHeight * aspectRatio > minCropBoxWidth) { + minCropBoxHeight = minCropBoxWidth / aspectRatio; + } else { + minCropBoxWidth = minCropBoxHeight * aspectRatio; + } + } else if (minCropBoxWidth) { + minCropBoxHeight = minCropBoxWidth / aspectRatio; + } else if (minCropBoxHeight) { + minCropBoxWidth = minCropBoxHeight * aspectRatio; + } + + if (maxCropBoxHeight * aspectRatio > maxCropBoxWidth) { + maxCropBoxHeight = maxCropBoxWidth / aspectRatio; + } else { + maxCropBoxWidth = maxCropBoxHeight * aspectRatio; + } + } + + // The minWidth/Height must be less than maxWidth/Height + cropBox.minWidth = min(minCropBoxWidth, maxCropBoxWidth); + cropBox.minHeight = min(minCropBoxHeight, maxCropBoxHeight); + cropBox.maxWidth = maxCropBoxWidth; + cropBox.maxHeight = maxCropBoxHeight; + } + + if (isPositionLimited) { + if (isLimited) { + cropBox.minLeft = max(0, canvas.left); + cropBox.minTop = max(0, canvas.top); + cropBox.maxLeft = min(containerWidth, canvas.left + canvas.width) - cropBox.width; + cropBox.maxTop = min(containerHeight, canvas.top + canvas.height) - cropBox.height; + } else { + cropBox.minLeft = 0; + cropBox.minTop = 0; + cropBox.maxLeft = containerWidth - cropBox.width; + cropBox.maxTop = containerHeight - cropBox.height; + } + } + }, + + renderCropBox: function () { + var options = this.options; + var container = this.container; + var containerWidth = container.width; + var containerHeight = container.height; + var cropBox = this.cropBox; + + if (cropBox.width > cropBox.maxWidth || cropBox.width < cropBox.minWidth) { + cropBox.left = cropBox.oldLeft; + } + + if (cropBox.height > cropBox.maxHeight || cropBox.height < cropBox.minHeight) { + cropBox.top = cropBox.oldTop; + } + + cropBox.width = min(max(cropBox.width, cropBox.minWidth), cropBox.maxWidth); + cropBox.height = min(max(cropBox.height, cropBox.minHeight), cropBox.maxHeight); + + this.limitCropBox(false, true); + + cropBox.oldLeft = cropBox.left = min(max(cropBox.left, cropBox.minLeft), cropBox.maxLeft); + cropBox.oldTop = cropBox.top = min(max(cropBox.top, cropBox.minTop), cropBox.maxTop); + + if (options.movable && options.cropBoxMovable) { + + // Turn to move the canvas when the crop box is equal to the container + this.$face.data(DATA_ACTION, (cropBox.width === containerWidth && cropBox.height === containerHeight) ? ACTION_MOVE : ACTION_ALL); + } + + this.$cropBox.css({ + width: cropBox.width, + height: cropBox.height, + left: cropBox.left, + top: cropBox.top + }); + + if (this.isCropped && this.isLimited) { + this.limitCanvas(true, true); + } + + if (!this.isDisabled) { + this.output(); + } + }, + + output: function () { + this.preview(); + + if (this.isCompleted) { + this.trigger(EVENT_CROP, this.getData()); + } else if (!this.isBuilt) { + + // Only trigger one crop event before complete + this.$element.one(EVENT_BUILT, $.proxy(function () { + this.trigger(EVENT_CROP, this.getData()); + }, this)); + } + }, + + initPreview: function () { + var crossOrigin = getCrossOrigin(this.crossOrigin); + var url = crossOrigin ? this.crossOriginUrl : this.url; + var $clone2; + + this.$preview = $(this.options.preview); + this.$clone2 = $clone2 = $(''); + this.$viewBox.html($clone2); + this.$preview.each(function () { + var $this = $(this); + + // Save the original size for recover + $this.data(DATA_PREVIEW, { + width: $this.width(), + height: $this.height(), + html: $this.html() + }); + + /** + * Override img element styles + * Add `display:block` to avoid margin top issue + * (Occur only when margin-top <= -height) + */ + $this.html( + '' + ); + }); + }, + + resetPreview: function () { + this.$preview.each(function () { + var $this = $(this); + var data = $this.data(DATA_PREVIEW); + + $this.css({ + width: data.width, + height: data.height + }).html(data.html).removeData(DATA_PREVIEW); + }); + }, + + preview: function () { + var image = this.image; + var canvas = this.canvas; + var cropBox = this.cropBox; + var cropBoxWidth = cropBox.width; + var cropBoxHeight = cropBox.height; + var width = image.width; + var height = image.height; + var left = cropBox.left - canvas.left - image.left; + var top = cropBox.top - canvas.top - image.top; + + if (!this.isCropped || this.isDisabled) { + return; + } + + this.$clone2.css({ + width: width, + height: height, + marginLeft: -left, + marginTop: -top, + transform: getTransform(image) + }); + + this.$preview.each(function () { + var $this = $(this); + var data = $this.data(DATA_PREVIEW); + var originalWidth = data.width; + var originalHeight = data.height; + var newWidth = originalWidth; + var newHeight = originalHeight; + var ratio = 1; + + if (cropBoxWidth) { + ratio = originalWidth / cropBoxWidth; + newHeight = cropBoxHeight * ratio; + } + + if (cropBoxHeight && newHeight > originalHeight) { + ratio = originalHeight / cropBoxHeight; + newWidth = cropBoxWidth * ratio; + newHeight = originalHeight; + } + + $this.css({ + width: newWidth, + height: newHeight + }).find('img').css({ + width: width * ratio, + height: height * ratio, + marginLeft: -left * ratio, + marginTop: -top * ratio, + transform: getTransform(image) + }); + }); + }, + + bind: function () { + var options = this.options; + var $this = this.$element; + var $cropper = this.$cropper; + + if ($.isFunction(options.cropstart)) { + $this.on(EVENT_CROP_START, options.cropstart); + } + + if ($.isFunction(options.cropmove)) { + $this.on(EVENT_CROP_MOVE, options.cropmove); + } + + if ($.isFunction(options.cropend)) { + $this.on(EVENT_CROP_END, options.cropend); + } + + if ($.isFunction(options.crop)) { + $this.on(EVENT_CROP, options.crop); + } + + if ($.isFunction(options.zoom)) { + $this.on(EVENT_ZOOM, options.zoom); + } + + $cropper.on(EVENT_MOUSE_DOWN, $.proxy(this.cropStart, this)); + + if (options.zoomable && options.zoomOnWheel) { + $cropper.on(EVENT_WHEEL, $.proxy(this.wheel, this)); + } + + if (options.toggleDragModeOnDblclick) { + $cropper.on(EVENT_DBLCLICK, $.proxy(this.dblclick, this)); + } + + $document. + on(EVENT_MOUSE_MOVE, (this._cropMove = proxy(this.cropMove, this))). + on(EVENT_MOUSE_UP, (this._cropEnd = proxy(this.cropEnd, this))); + + if (options.responsive) { + $window.on(EVENT_RESIZE, (this._resize = proxy(this.resize, this))); + } + }, + + unbind: function () { + var options = this.options; + var $this = this.$element; + var $cropper = this.$cropper; + + if ($.isFunction(options.cropstart)) { + $this.off(EVENT_CROP_START, options.cropstart); + } + + if ($.isFunction(options.cropmove)) { + $this.off(EVENT_CROP_MOVE, options.cropmove); + } + + if ($.isFunction(options.cropend)) { + $this.off(EVENT_CROP_END, options.cropend); + } + + if ($.isFunction(options.crop)) { + $this.off(EVENT_CROP, options.crop); + } + + if ($.isFunction(options.zoom)) { + $this.off(EVENT_ZOOM, options.zoom); + } + + $cropper.off(EVENT_MOUSE_DOWN, this.cropStart); + + if (options.zoomable && options.zoomOnWheel) { + $cropper.off(EVENT_WHEEL, this.wheel); + } + + if (options.toggleDragModeOnDblclick) { + $cropper.off(EVENT_DBLCLICK, this.dblclick); + } + + $document. + off(EVENT_MOUSE_MOVE, this._cropMove). + off(EVENT_MOUSE_UP, this._cropEnd); + + if (options.responsive) { + $window.off(EVENT_RESIZE, this._resize); + } + }, + + resize: function () { + var restore = this.options.restore; + var $container = this.$container; + var container = this.container; + var canvasData; + var cropBoxData; + var ratio; + + // Check `container` is necessary for IE8 + if (this.isDisabled || !container) { + return; + } + + ratio = $container.width() / container.width; + + // Resize when width changed or height changed + if (ratio !== 1 || $container.height() !== container.height) { + if (restore) { + canvasData = this.getCanvasData(); + cropBoxData = this.getCropBoxData(); + } + + this.render(); + + if (restore) { + this.setCanvasData($.each(canvasData, function (i, n) { + canvasData[i] = n * ratio; + })); + this.setCropBoxData($.each(cropBoxData, function (i, n) { + cropBoxData[i] = n * ratio; + })); + } + } + }, + + dblclick: function () { + if (this.isDisabled) { + return; + } + + if (this.$dragBox.hasClass(CLASS_CROP)) { + this.setDragMode(ACTION_MOVE); + } else { + this.setDragMode(ACTION_CROP); + } + }, + + wheel: function (event) { + var e = event.originalEvent || event; + var ratio = num(this.options.wheelZoomRatio) || 0.1; + var delta = 1; + + if (this.isDisabled) { + return; + } + + event.preventDefault(); + + // Limit wheel speed to prevent zoom too fast + if (this.wheeling) { + return; + } + + this.wheeling = true; + + setTimeout($.proxy(function () { + this.wheeling = false; + }, this), 50); + + if (e.deltaY) { + delta = e.deltaY > 0 ? 1 : -1; + } else if (e.wheelDelta) { + delta = -e.wheelDelta / 120; + } else if (e.detail) { + delta = e.detail > 0 ? 1 : -1; + } + + this.zoom(-delta * ratio, event); + }, + + cropStart: function (event) { + var options = this.options; + var originalEvent = event.originalEvent; + var touches = originalEvent && originalEvent.touches; + var e = event; + var touchesLength; + var action; + + if (this.isDisabled) { + return; + } + + if (touches) { + touchesLength = touches.length; + + if (touchesLength > 1) { + if (options.zoomable && options.zoomOnTouch && touchesLength === 2) { + e = touches[1]; + this.startX2 = e.pageX; + this.startY2 = e.pageY; + action = ACTION_ZOOM; + } else { + return; + } + } + + e = touches[0]; + } + + action = action || $(e.target).data(DATA_ACTION); + + if (REGEXP_ACTIONS.test(action)) { + if (this.trigger(EVENT_CROP_START, { + originalEvent: originalEvent, + action: action + }).isDefaultPrevented()) { + return; + } + + event.preventDefault(); + + this.action = action; + this.cropping = false; + + // IE8 has `event.pageX/Y`, but not `event.originalEvent.pageX/Y` + // IE10 has `event.originalEvent.pageX/Y`, but not `event.pageX/Y` + this.startX = e.pageX || originalEvent && originalEvent.pageX; + this.startY = e.pageY || originalEvent && originalEvent.pageY; + + if (action === ACTION_CROP) { + this.cropping = true; + this.$dragBox.addClass(CLASS_MODAL); + } + } + }, + + cropMove: function (event) { + var options = this.options; + var originalEvent = event.originalEvent; + var touches = originalEvent && originalEvent.touches; + var e = event; + var action = this.action; + var touchesLength; + + if (this.isDisabled) { + return; + } + + if (touches) { + touchesLength = touches.length; + + if (touchesLength > 1) { + if (options.zoomable && options.zoomOnTouch && touchesLength === 2) { + e = touches[1]; + this.endX2 = e.pageX; + this.endY2 = e.pageY; + } else { + return; + } + } + + e = touches[0]; + } + + if (action) { + if (this.trigger(EVENT_CROP_MOVE, { + originalEvent: originalEvent, + action: action + }).isDefaultPrevented()) { + return; + } + + event.preventDefault(); + + this.endX = e.pageX || originalEvent && originalEvent.pageX; + this.endY = e.pageY || originalEvent && originalEvent.pageY; + + this.change(e.shiftKey, action === ACTION_ZOOM ? event : null); + } + }, + + cropEnd: function (event) { + var originalEvent = event.originalEvent; + var action = this.action; + + if (this.isDisabled) { + return; + } + + if (action) { + event.preventDefault(); + + if (this.cropping) { + this.cropping = false; + this.$dragBox.toggleClass(CLASS_MODAL, this.isCropped && this.options.modal); + } + + this.action = ''; + + this.trigger(EVENT_CROP_END, { + originalEvent: originalEvent, + action: action + }); + } + }, + + change: function (shiftKey, event) { + var options = this.options; + var aspectRatio = options.aspectRatio; + var action = this.action; + var container = this.container; + var canvas = this.canvas; + var cropBox = this.cropBox; + var width = cropBox.width; + var height = cropBox.height; + var left = cropBox.left; + var top = cropBox.top; + var right = left + width; + var bottom = top + height; + var minLeft = 0; + var minTop = 0; + var maxWidth = container.width; + var maxHeight = container.height; + var renderable = true; + var offset; + var range; + + // Locking aspect ratio in "free mode" by holding shift key (#259) + if (!aspectRatio && shiftKey) { + aspectRatio = width && height ? width / height : 1; + } + + if (this.limited) { + minLeft = cropBox.minLeft; + minTop = cropBox.minTop; + maxWidth = minLeft + min(container.width, canvas.left + canvas.width); + maxHeight = minTop + min(container.height, canvas.top + canvas.height); + } + + range = { + x: this.endX - this.startX, + y: this.endY - this.startY + }; + + if (aspectRatio) { + range.X = range.y * aspectRatio; + range.Y = range.x / aspectRatio; + } + + switch (action) { + // Move crop box + case ACTION_ALL: + left += range.x; + top += range.y; + break; + + // Resize crop box + case ACTION_EAST: + if (range.x >= 0 && (right >= maxWidth || aspectRatio && + (top <= minTop || bottom >= maxHeight))) { + + renderable = false; + break; + } + + width += range.x; + + if (aspectRatio) { + height = width / aspectRatio; + top -= range.Y / 2; + } + + if (width < 0) { + action = ACTION_WEST; + width = 0; + } + + break; + + case ACTION_NORTH: + if (range.y <= 0 && (top <= minTop || aspectRatio && + (left <= minLeft || right >= maxWidth))) { + + renderable = false; + break; + } + + height -= range.y; + top += range.y; + + if (aspectRatio) { + width = height * aspectRatio; + left += range.X / 2; + } + + if (height < 0) { + action = ACTION_SOUTH; + height = 0; + } + + break; + + case ACTION_WEST: + if (range.x <= 0 && (left <= minLeft || aspectRatio && + (top <= minTop || bottom >= maxHeight))) { + + renderable = false; + break; + } + + width -= range.x; + left += range.x; + + if (aspectRatio) { + height = width / aspectRatio; + top += range.Y / 2; + } + + if (width < 0) { + action = ACTION_EAST; + width = 0; + } + + break; + + case ACTION_SOUTH: + if (range.y >= 0 && (bottom >= maxHeight || aspectRatio && + (left <= minLeft || right >= maxWidth))) { + + renderable = false; + break; + } + + height += range.y; + + if (aspectRatio) { + width = height * aspectRatio; + left -= range.X / 2; + } + + if (height < 0) { + action = ACTION_NORTH; + height = 0; + } + + break; + + case ACTION_NORTH_EAST: + if (aspectRatio) { + if (range.y <= 0 && (top <= minTop || right >= maxWidth)) { + renderable = false; + break; + } + + height -= range.y; + top += range.y; + width = height * aspectRatio; + } else { + if (range.x >= 0) { + if (right < maxWidth) { + width += range.x; + } else if (range.y <= 0 && top <= minTop) { + renderable = false; + } + } else { + width += range.x; + } + + if (range.y <= 0) { + if (top > minTop) { + height -= range.y; + top += range.y; + } + } else { + height -= range.y; + top += range.y; + } + } + + if (width < 0 && height < 0) { + action = ACTION_SOUTH_WEST; + height = 0; + width = 0; + } else if (width < 0) { + action = ACTION_NORTH_WEST; + width = 0; + } else if (height < 0) { + action = ACTION_SOUTH_EAST; + height = 0; + } + + break; + + case ACTION_NORTH_WEST: + if (aspectRatio) { + if (range.y <= 0 && (top <= minTop || left <= minLeft)) { + renderable = false; + break; + } + + height -= range.y; + top += range.y; + width = height * aspectRatio; + left += range.X; + } else { + if (range.x <= 0) { + if (left > minLeft) { + width -= range.x; + left += range.x; + } else if (range.y <= 0 && top <= minTop) { + renderable = false; + } + } else { + width -= range.x; + left += range.x; + } + + if (range.y <= 0) { + if (top > minTop) { + height -= range.y; + top += range.y; + } + } else { + height -= range.y; + top += range.y; + } + } + + if (width < 0 && height < 0) { + action = ACTION_SOUTH_EAST; + height = 0; + width = 0; + } else if (width < 0) { + action = ACTION_NORTH_EAST; + width = 0; + } else if (height < 0) { + action = ACTION_SOUTH_WEST; + height = 0; + } + + break; + + case ACTION_SOUTH_WEST: + if (aspectRatio) { + if (range.x <= 0 && (left <= minLeft || bottom >= maxHeight)) { + renderable = false; + break; + } + + width -= range.x; + left += range.x; + height = width / aspectRatio; + } else { + if (range.x <= 0) { + if (left > minLeft) { + width -= range.x; + left += range.x; + } else if (range.y >= 0 && bottom >= maxHeight) { + renderable = false; + } + } else { + width -= range.x; + left += range.x; + } + + if (range.y >= 0) { + if (bottom < maxHeight) { + height += range.y; + } + } else { + height += range.y; + } + } + + if (width < 0 && height < 0) { + action = ACTION_NORTH_EAST; + height = 0; + width = 0; + } else if (width < 0) { + action = ACTION_SOUTH_EAST; + width = 0; + } else if (height < 0) { + action = ACTION_NORTH_WEST; + height = 0; + } + + break; + + case ACTION_SOUTH_EAST: + if (aspectRatio) { + if (range.x >= 0 && (right >= maxWidth || bottom >= maxHeight)) { + renderable = false; + break; + } + + width += range.x; + height = width / aspectRatio; + } else { + if (range.x >= 0) { + if (right < maxWidth) { + width += range.x; + } else if (range.y >= 0 && bottom >= maxHeight) { + renderable = false; + } + } else { + width += range.x; + } + + if (range.y >= 0) { + if (bottom < maxHeight) { + height += range.y; + } + } else { + height += range.y; + } + } + + if (width < 0 && height < 0) { + action = ACTION_NORTH_WEST; + height = 0; + width = 0; + } else if (width < 0) { + action = ACTION_SOUTH_WEST; + width = 0; + } else if (height < 0) { + action = ACTION_NORTH_EAST; + height = 0; + } + + break; + + // Move canvas + case ACTION_MOVE: + this.move(range.x, range.y); + renderable = false; + break; + + // Zoom canvas + case ACTION_ZOOM: + this.zoom((function (x1, y1, x2, y2) { + var z1 = sqrt(x1 * x1 + y1 * y1); + var z2 = sqrt(x2 * x2 + y2 * y2); + + return (z2 - z1) / z1; + })( + abs(this.startX - this.startX2), + abs(this.startY - this.startY2), + abs(this.endX - this.endX2), + abs(this.endY - this.endY2) + ), event); + this.startX2 = this.endX2; + this.startY2 = this.endY2; + renderable = false; + break; + + // Create crop box + case ACTION_CROP: + if (!range.x || !range.y) { + renderable = false; + break; + } + + offset = this.$cropper.offset(); + left = this.startX - offset.left; + top = this.startY - offset.top; + width = cropBox.minWidth; + height = cropBox.minHeight; + + if (range.x > 0) { + action = range.y > 0 ? ACTION_SOUTH_EAST : ACTION_NORTH_EAST; + } else if (range.x < 0) { + left -= width; + action = range.y > 0 ? ACTION_SOUTH_WEST : ACTION_NORTH_WEST; + } + + if (range.y < 0) { + top -= height; + } + + // Show the crop box if is hidden + if (!this.isCropped) { + this.$cropBox.removeClass(CLASS_HIDDEN); + this.isCropped = true; + + if (this.limited) { + this.limitCropBox(true, true); + } + } + + break; + + // No default + } + + if (renderable) { + cropBox.width = width; + cropBox.height = height; + cropBox.left = left; + cropBox.top = top; + this.action = action; + + this.renderCropBox(); + } + + // Override + this.startX = this.endX; + this.startY = this.endY; + }, + + // Show the crop box manually + crop: function () { + if (!this.isBuilt || this.isDisabled) { + return; + } + + if (!this.isCropped) { + this.isCropped = true; + this.limitCropBox(true, true); + + if (this.options.modal) { + this.$dragBox.addClass(CLASS_MODAL); + } + + this.$cropBox.removeClass(CLASS_HIDDEN); + } + + this.setCropBoxData(this.initialCropBox); + }, + + // Reset the image and crop box to their initial states + reset: function () { + if (!this.isBuilt || this.isDisabled) { + return; + } + + this.image = $.extend({}, this.initialImage); + this.canvas = $.extend({}, this.initialCanvas); + this.cropBox = $.extend({}, this.initialCropBox); + + this.renderCanvas(); + + if (this.isCropped) { + this.renderCropBox(); + } + }, + + // Clear the crop box + clear: function () { + if (!this.isCropped || this.isDisabled) { + return; + } + + $.extend(this.cropBox, { + left: 0, + top: 0, + width: 0, + height: 0 + }); + + this.isCropped = false; + this.renderCropBox(); + + this.limitCanvas(true, true); + + // Render canvas after crop box rendered + this.renderCanvas(); + + this.$dragBox.removeClass(CLASS_MODAL); + this.$cropBox.addClass(CLASS_HIDDEN); + }, + + /** + * Replace the image's src and rebuild the cropper + * + * @param {String} url + * @param {Boolean} onlyColorChanged (optional) + */ + replace: function (url, onlyColorChanged) { + if (!this.isDisabled && url) { + if (this.isImg) { + this.$element.attr('src', url); + } + + if (onlyColorChanged) { + this.url = url; + this.$clone.attr('src', url); + + if (this.isBuilt) { + this.$preview.find('img').add(this.$clone2).attr('src', url); + } + } else { + if (this.isImg) { + this.isReplaced = true; + } + + // Clear previous data + this.options.data = null; + this.load(url); + } + } + }, + + // Enable (unfreeze) the cropper + enable: function () { + if (this.isBuilt) { + this.isDisabled = false; + this.$cropper.removeClass(CLASS_DISABLED); + } + }, + + // Disable (freeze) the cropper + disable: function () { + if (this.isBuilt) { + this.isDisabled = true; + this.$cropper.addClass(CLASS_DISABLED); + } + }, + + // Destroy the cropper and remove the instance from the image + destroy: function () { + var $this = this.$element; + + if (this.isLoaded) { + if (this.isImg && this.isReplaced) { + $this.attr('src', this.originalUrl); + } + + this.unbuild(); + $this.removeClass(CLASS_HIDDEN); + } else { + if (this.isImg) { + $this.off(EVENT_LOAD, this.start); + } else if (this.$clone) { + this.$clone.remove(); + } + } + + $this.removeData(NAMESPACE); + }, + + /** + * Move the canvas with relative offsets + * + * @param {Number} offsetX + * @param {Number} offsetY (optional) + */ + move: function (offsetX, offsetY) { + var canvas = this.canvas; + + this.moveTo( + isUndefined(offsetX) ? offsetX : canvas.left + num(offsetX), + isUndefined(offsetY) ? offsetY : canvas.top + num(offsetY) + ); + }, + + /** + * Move the canvas to an absolute point + * + * @param {Number} x + * @param {Number} y (optional) + */ + moveTo: function (x, y) { + var canvas = this.canvas; + var isChanged = false; + + // If "y" is not present, its default value is "x" + if (isUndefined(y)) { + y = x; + } + + x = num(x); + y = num(y); + + if (this.isBuilt && !this.isDisabled && this.options.movable) { + if (isNumber(x)) { + canvas.left = x; + isChanged = true; + } + + if (isNumber(y)) { + canvas.top = y; + isChanged = true; + } + + if (isChanged) { + this.renderCanvas(true); + } + } + }, + + /** + * Zoom the canvas with a relative ratio + * + * @param {Number} ratio + * @param {jQuery Event} _event (private) + */ + zoom: function (ratio, _event) { + var canvas = this.canvas; + + ratio = num(ratio); + + if (ratio < 0) { + ratio = 1 / (1 - ratio); + } else { + ratio = 1 + ratio; + } + + this.zoomTo(canvas.width * ratio / canvas.naturalWidth, _event); + }, + + /** + * Zoom the canvas to an absolute ratio + * + * @param {Number} ratio + * @param {jQuery Event} _event (private) + */ + zoomTo: function (ratio, _event) { + var options = this.options; + var canvas = this.canvas; + var width = canvas.width; + var height = canvas.height; + var naturalWidth = canvas.naturalWidth; + var naturalHeight = canvas.naturalHeight; + var originalEvent; + var newWidth; + var newHeight; + var offset; + var center; + + ratio = num(ratio); + + if (ratio >= 0 && this.isBuilt && !this.isDisabled && options.zoomable) { + newWidth = naturalWidth * ratio; + newHeight = naturalHeight * ratio; + + if (_event) { + originalEvent = _event.originalEvent; + } + + if (this.trigger(EVENT_ZOOM, { + originalEvent: originalEvent, + oldRatio: width / naturalWidth, + ratio: newWidth / naturalWidth + }).isDefaultPrevented()) { + return; + } + + if (originalEvent) { + offset = this.$cropper.offset(); + center = originalEvent.touches ? getTouchesCenter(originalEvent.touches) : { + pageX: _event.pageX || originalEvent.pageX || 0, + pageY: _event.pageY || originalEvent.pageY || 0 + }; + + // Zoom from the triggering point of the event + canvas.left -= (newWidth - width) * ( + ((center.pageX - offset.left) - canvas.left) / width + ); + canvas.top -= (newHeight - height) * ( + ((center.pageY - offset.top) - canvas.top) / height + ); + } else { + + // Zoom from the center of the canvas + canvas.left -= (newWidth - width) / 2; + canvas.top -= (newHeight - height) / 2; + } + + canvas.width = newWidth; + canvas.height = newHeight; + this.renderCanvas(true); + } + }, + + /** + * Rotate the canvas with a relative degree + * + * @param {Number} degree + */ + rotate: function (degree) { + this.rotateTo((this.image.rotate || 0) + num(degree)); + }, + + /** + * Rotate the canvas to an absolute degree + * https://developer.mozilla.org/en-US/docs/Web/CSS/transform-function#rotate() + * + * @param {Number} degree + */ + rotateTo: function (degree) { + degree = num(degree); + + if (isNumber(degree) && this.isBuilt && !this.isDisabled && this.options.rotatable) { + this.image.rotate = degree % 360; + this.isRotated = true; + this.renderCanvas(true); + } + }, + + /** + * Scale the image + * https://developer.mozilla.org/en-US/docs/Web/CSS/transform-function#scale() + * + * @param {Number} scaleX + * @param {Number} scaleY (optional) + */ + scale: function (scaleX, scaleY) { + var image = this.image; + var isChanged = false; + + // If "scaleY" is not present, its default value is "scaleX" + if (isUndefined(scaleY)) { + scaleY = scaleX; + } + + scaleX = num(scaleX); + scaleY = num(scaleY); + + if (this.isBuilt && !this.isDisabled && this.options.scalable) { + if (isNumber(scaleX)) { + image.scaleX = scaleX; + isChanged = true; + } + + if (isNumber(scaleY)) { + image.scaleY = scaleY; + isChanged = true; + } + + if (isChanged) { + this.renderImage(true); + } + } + }, + + /** + * Scale the abscissa of the image + * + * @param {Number} scaleX + */ + scaleX: function (scaleX) { + var scaleY = this.image.scaleY; + + this.scale(scaleX, isNumber(scaleY) ? scaleY : 1); + }, + + /** + * Scale the ordinate of the image + * + * @param {Number} scaleY + */ + scaleY: function (scaleY) { + var scaleX = this.image.scaleX; + + this.scale(isNumber(scaleX) ? scaleX : 1, scaleY); + }, + + /** + * Get the cropped area position and size data (base on the original image) + * + * @param {Boolean} isRounded (optional) + * @return {Object} data + */ + getData: function (isRounded) { + var options = this.options; + var image = this.image; + var canvas = this.canvas; + var cropBox = this.cropBox; + var ratio; + var data; + + if (this.isBuilt && this.isCropped) { + data = { + x: cropBox.left - canvas.left, + y: cropBox.top - canvas.top, + width: cropBox.width, + height: cropBox.height + }; + + ratio = image.width / image.naturalWidth; + + $.each(data, function (i, n) { + n = n / ratio; + data[i] = isRounded ? round(n) : n; + }); + + } else { + data = { + x: 0, + y: 0, + width: 0, + height: 0 + }; + } + + if (options.rotatable) { + data.rotate = image.rotate || 0; + } + + if (options.scalable) { + data.scaleX = image.scaleX || 1; + data.scaleY = image.scaleY || 1; + } + + return data; + }, + + /** + * Set the cropped area position and size with new data + * + * @param {Object} data + */ + setData: function (data) { + var options = this.options; + var image = this.image; + var canvas = this.canvas; + var cropBoxData = {}; + var isRotated; + var isScaled; + var ratio; + + if ($.isFunction(data)) { + data = data.call(this.element); + } + + if (this.isBuilt && !this.isDisabled && $.isPlainObject(data)) { + if (options.rotatable) { + if (isNumber(data.rotate) && data.rotate !== image.rotate) { + image.rotate = data.rotate; + this.isRotated = isRotated = true; + } + } + + if (options.scalable) { + if (isNumber(data.scaleX) && data.scaleX !== image.scaleX) { + image.scaleX = data.scaleX; + isScaled = true; + } + + if (isNumber(data.scaleY) && data.scaleY !== image.scaleY) { + image.scaleY = data.scaleY; + isScaled = true; + } + } + + if (isRotated) { + this.renderCanvas(); + } else if (isScaled) { + this.renderImage(); + } + + ratio = image.width / image.naturalWidth; + + if (isNumber(data.x)) { + cropBoxData.left = data.x * ratio + canvas.left; + } + + if (isNumber(data.y)) { + cropBoxData.top = data.y * ratio + canvas.top; + } + + if (isNumber(data.width)) { + cropBoxData.width = data.width * ratio; + } + + if (isNumber(data.height)) { + cropBoxData.height = data.height * ratio; + } + + this.setCropBoxData(cropBoxData); + } + }, + + /** + * Get the container size data + * + * @return {Object} data + */ + getContainerData: function () { + return this.isBuilt ? this.container : {}; + }, + + /** + * Get the image position and size data + * + * @return {Object} data + */ + getImageData: function () { + return this.isLoaded ? this.image : {}; + }, + + /** + * Get the canvas position and size data + * + * @return {Object} data + */ + getCanvasData: function () { + var canvas = this.canvas; + var data = {}; + + if (this.isBuilt) { + $.each([ + 'left', + 'top', + 'width', + 'height', + 'naturalWidth', + 'naturalHeight' + ], function (i, n) { + data[n] = canvas[n]; + }); + } + + return data; + }, + + /** + * Set the canvas position and size with new data + * + * @param {Object} data + */ + setCanvasData: function (data) { + var canvas = this.canvas; + var aspectRatio = canvas.aspectRatio; + + if ($.isFunction(data)) { + data = data.call(this.$element); + } + + if (this.isBuilt && !this.isDisabled && $.isPlainObject(data)) { + if (isNumber(data.left)) { + canvas.left = data.left; + } + + if (isNumber(data.top)) { + canvas.top = data.top; + } + + if (isNumber(data.width)) { + canvas.width = data.width; + canvas.height = data.width / aspectRatio; + } else if (isNumber(data.height)) { + canvas.height = data.height; + canvas.width = data.height * aspectRatio; + } + + this.renderCanvas(true); + } + }, + + /** + * Get the crop box position and size data + * + * @return {Object} data + */ + getCropBoxData: function () { + var cropBox = this.cropBox; + var data; + + if (this.isBuilt && this.isCropped) { + data = { + left: cropBox.left, + top: cropBox.top, + width: cropBox.width, + height: cropBox.height + }; + } + + return data || {}; + }, + + /** + * Set the crop box position and size with new data + * + * @param {Object} data + */ + setCropBoxData: function (data) { + var cropBox = this.cropBox; + var aspectRatio = this.options.aspectRatio; + var isWidthChanged; + var isHeightChanged; + + if ($.isFunction(data)) { + data = data.call(this.$element); + } + + if (this.isBuilt && this.isCropped && !this.isDisabled && $.isPlainObject(data)) { + + if (isNumber(data.left)) { + cropBox.left = data.left; + } + + if (isNumber(data.top)) { + cropBox.top = data.top; + } + + if (isNumber(data.width)) { + isWidthChanged = true; + cropBox.width = data.width; + } + + if (isNumber(data.height)) { + isHeightChanged = true; + cropBox.height = data.height; + } + + if (aspectRatio) { + if (isWidthChanged) { + cropBox.height = cropBox.width / aspectRatio; + } else if (isHeightChanged) { + cropBox.width = cropBox.height * aspectRatio; + } + } + + this.renderCropBox(); + } + }, + + /** + * Get a canvas drawn the cropped image + * + * @param {Object} options (optional) + * @return {HTMLCanvasElement} canvas + */ + getCroppedCanvas: function (options) { + var originalWidth; + var originalHeight; + var canvasWidth; + var canvasHeight; + var scaledWidth; + var scaledHeight; + var scaledRatio; + var aspectRatio; + var canvas; + var context; + var data; + + if (!this.isBuilt || !this.isCropped || !SUPPORT_CANVAS) { + return; + } + + if (!$.isPlainObject(options)) { + options = {}; + } + + data = this.getData(); + originalWidth = data.width; + originalHeight = data.height; + aspectRatio = originalWidth / originalHeight; + + if ($.isPlainObject(options)) { + scaledWidth = options.width; + scaledHeight = options.height; + + if (scaledWidth) { + scaledHeight = scaledWidth / aspectRatio; + scaledRatio = scaledWidth / originalWidth; + } else if (scaledHeight) { + scaledWidth = scaledHeight * aspectRatio; + scaledRatio = scaledHeight / originalHeight; + } + } + + // The canvas element will use `Math.floor` on a float number, so floor first + canvasWidth = floor(scaledWidth || originalWidth); + canvasHeight = floor(scaledHeight || originalHeight); + + canvas = $('')[0]; + canvas.width = canvasWidth; + canvas.height = canvasHeight; + context = canvas.getContext('2d'); + + if (options.fillColor) { + context.fillStyle = options.fillColor; + context.fillRect(0, 0, canvasWidth, canvasHeight); + } + + // https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D.drawImage + context.drawImage.apply(context, (function () { + var source = getSourceCanvas(this.$clone[0], this.image); + var sourceWidth = source.width; + var sourceHeight = source.height; + var canvas = this.canvas; + var params = [source]; + + // Source canvas + var srcX = data.x + canvas.naturalWidth * (abs(data.scaleX || 1) - 1) / 2; + var srcY = data.y + canvas.naturalHeight * (abs(data.scaleY || 1) - 1) / 2; + var srcWidth; + var srcHeight; + + // Destination canvas + var dstX; + var dstY; + var dstWidth; + var dstHeight; + + if (srcX <= -originalWidth || srcX > sourceWidth) { + srcX = srcWidth = dstX = dstWidth = 0; + } else if (srcX <= 0) { + dstX = -srcX; + srcX = 0; + srcWidth = dstWidth = min(sourceWidth, originalWidth + srcX); + } else if (srcX <= sourceWidth) { + dstX = 0; + srcWidth = dstWidth = min(originalWidth, sourceWidth - srcX); + } + + if (srcWidth <= 0 || srcY <= -originalHeight || srcY > sourceHeight) { + srcY = srcHeight = dstY = dstHeight = 0; + } else if (srcY <= 0) { + dstY = -srcY; + srcY = 0; + srcHeight = dstHeight = min(sourceHeight, originalHeight + srcY); + } else if (srcY <= sourceHeight) { + dstY = 0; + srcHeight = dstHeight = min(originalHeight, sourceHeight - srcY); + } + + // All the numerical parameters should be integer for `drawImage` (#476) + params.push(floor(srcX), floor(srcY), floor(srcWidth), floor(srcHeight)); + + // Scale destination sizes + if (scaledRatio) { + dstX *= scaledRatio; + dstY *= scaledRatio; + dstWidth *= scaledRatio; + dstHeight *= scaledRatio; + } + + // Avoid "IndexSizeError" in IE and Firefox + if (dstWidth > 0 && dstHeight > 0) { + params.push(floor(dstX), floor(dstY), floor(dstWidth), floor(dstHeight)); + } + + return params; + }).call(this)); + + return canvas; + }, + + /** + * Change the aspect ratio of the crop box + * + * @param {Number} aspectRatio + */ + setAspectRatio: function (aspectRatio) { + var options = this.options; + + if (!this.isDisabled && !isUndefined(aspectRatio)) { + + // 0 -> NaN + options.aspectRatio = max(0, aspectRatio) || NaN; + + if (this.isBuilt) { + this.initCropBox(); + + if (this.isCropped) { + this.renderCropBox(); + } + } + } + }, + + /** + * Change the drag mode + * + * @param {String} mode (optional) + */ + setDragMode: function (mode) { + var options = this.options; + var croppable; + var movable; + + if (this.isLoaded && !this.isDisabled) { + croppable = mode === ACTION_CROP; + movable = options.movable && mode === ACTION_MOVE; + mode = (croppable || movable) ? mode : ACTION_NONE; + + this.$dragBox. + data(DATA_ACTION, mode). + toggleClass(CLASS_CROP, croppable). + toggleClass(CLASS_MOVE, movable); + + if (!options.cropBoxMovable) { + + // Sync drag mode to crop box when it is not movable(#300) + this.$face. + data(DATA_ACTION, mode). + toggleClass(CLASS_CROP, croppable). + toggleClass(CLASS_MOVE, movable); + } + } + } + }; + + Cropper.DEFAULTS = { + + // Define the view mode of the cropper + viewMode: 0, // 0, 1, 2, 3 + + // Define the dragging mode of the cropper + dragMode: 'crop', // 'crop', 'move' or 'none' + + // Define the aspect ratio of the crop box + aspectRatio: NaN, + + // An object with the previous cropping result data + data: null, + + // A jQuery selector for adding extra containers to preview + preview: '', + + // Re-render the cropper when resize the window + responsive: true, + + // Restore the cropped area after resize the window + restore: true, + + // Check if the current image is a cross-origin image + checkCrossOrigin: true, + + // Check the current image's Exif Orientation information + checkOrientation: true, + + // Show the black modal + modal: true, + + // Show the dashed lines for guiding + guides: true, + + // Show the center indicator for guiding + center: true, + + // Show the white modal to highlight the crop box + highlight: true, + + // Show the grid background + background: true, + + // Enable to crop the image automatically when initialize + autoCrop: true, + + // Define the percentage of automatic cropping area when initializes + autoCropArea: 0.8, + + // Enable to move the image + movable: true, + + // Enable to rotate the image + rotatable: true, + + // Enable to scale the image + scalable: true, + + // Enable to zoom the image + zoomable: true, + + // Enable to zoom the image by dragging touch + zoomOnTouch: true, + + // Enable to zoom the image by wheeling mouse + zoomOnWheel: true, + + // Define zoom ratio when zoom the image by wheeling mouse + wheelZoomRatio: 0.1, + + // Enable to move the crop box + cropBoxMovable: true, + + // Enable to resize the crop box + cropBoxResizable: true, + + // Toggle drag mode between "crop" and "move" when click twice on the cropper + toggleDragModeOnDblclick: true, + + // Size limitation + minCanvasWidth: 0, + minCanvasHeight: 0, + minCropBoxWidth: 0, + minCropBoxHeight: 0, + minContainerWidth: 200, + minContainerHeight: 100, + + // Shortcuts of events + build: null, + built: null, + cropstart: null, + cropmove: null, + cropend: null, + crop: null, + zoom: null + }; + + Cropper.setDefaults = function (options) { + $.extend(Cropper.DEFAULTS, options); + }; + + Cropper.TEMPLATE = ( + '
    ' + + '
    ' + + '
    ' + + '
    ' + + '
    ' + + '
    ' + + '' + + '' + + '' + + '' + + '' + + '' + + '' + + '' + + '' + + '' + + '' + + '' + + '' + + '' + + '' + + '' + + '' + + '
    ' + + '
    ' + ); + + // Save the other cropper + Cropper.other = $.fn.cropper; + + // Register as jQuery plugin + $.fn.cropper = function (option) { + var args = toArray(arguments, 1); + var result; + + this.each(function () { + var $this = $(this); + var data = $this.data(NAMESPACE); + var options; + var fn; + + if (!data) { + if (/destroy/.test(option)) { + return; + } + + options = $.extend({}, $this.data(), $.isPlainObject(option) && option); + $this.data(NAMESPACE, (data = new Cropper(this, options))); + } + + if (typeof option === 'string' && $.isFunction(fn = data[option])) { + result = fn.apply(data, args); + } + }); + + return isUndefined(result) ? this : result; + }; + + $.fn.cropper.Constructor = Cropper; + $.fn.cropper.setDefaults = Cropper.setDefaults; + + // No conflict + $.fn.cropper.noConflict = function () { + $.fn.cropper = Cropper.other; + return this; + }; + +}); diff --git a/vendor/assets/stylesheets/cropper.css b/vendor/assets/stylesheets/cropper.css new file mode 100644 index 0000000000..8668c7c049 --- /dev/null +++ b/vendor/assets/stylesheets/cropper.css @@ -0,0 +1,379 @@ +/*! + * Cropper v2.3.0 + * https://github.com/fengyuanchen/cropper + * + * Copyright (c) 2014-2016 Fengyuan Chen and contributors + * Released under the MIT license + * + * Date: 2016-02-22T02:13:13.332Z + */ +.cropper-container { + font-size: 0; + line-height: 0; + + position: relative; + + -webkit-user-select: none; + -moz-user-select: none; + -ms-user-select: none; + user-select: none; + + direction: ltr !important; + -ms-touch-action: none; + touch-action: none; + -webkit-tap-highlight-color: transparent; + -webkit-touch-callout: none; +} + +.cropper-container img { + display: block; + + width: 100%; + min-width: 0 !important; + max-width: none !important; + height: 100%; + min-height: 0 !important; + max-height: none !important; + + image-orientation: 0deg !important; +} + +.cropper-wrap-box, +.cropper-canvas, +.cropper-drag-box, +.cropper-crop-box, +.cropper-modal { + position: absolute; + top: 0; + right: 0; + bottom: 0; + left: 0; +} + +.cropper-wrap-box { + overflow: hidden; +} + +.cropper-drag-box { + opacity: 0; + background-color: #fff; + + filter: alpha(opacity=0); +} + +.cropper-modal { + opacity: .5; + background-color: #000; + + filter: alpha(opacity=50); +} + +.cropper-view-box { + display: block; + overflow: hidden; + + width: 100%; + height: 100%; + + outline: 1px solid #39f; + outline-color: rgba(51, 153, 255, .75); +} + +.cropper-dashed { + position: absolute; + + display: block; + + opacity: .5; + border: 0 dashed #eee; + + filter: alpha(opacity=50); +} + +.cropper-dashed.dashed-h { + top: 33.33333%; + left: 0; + + width: 100%; + height: 33.33333%; + + border-top-width: 1px; + border-bottom-width: 1px; +} + +.cropper-dashed.dashed-v { + top: 0; + left: 33.33333%; + + width: 33.33333%; + height: 100%; + + border-right-width: 1px; + border-left-width: 1px; +} + +.cropper-center { + position: absolute; + top: 50%; + left: 50%; + + display: block; + + width: 0; + height: 0; + + opacity: .75; + + filter: alpha(opacity=75); +} + +.cropper-center:before, +.cropper-center:after { + position: absolute; + + display: block; + + content: ' '; + + background-color: #eee; +} + +.cropper-center:before { + top: 0; + left: -3px; + + width: 7px; + height: 1px; +} + +.cropper-center:after { + top: -3px; + left: 0; + + width: 1px; + height: 7px; +} + +.cropper-face, +.cropper-line, +.cropper-point { + position: absolute; + + display: block; + + width: 100%; + height: 100%; + + opacity: .1; + + filter: alpha(opacity=10); +} + +.cropper-face { + top: 0; + left: 0; + + background-color: #fff; +} + +.cropper-line { + background-color: #39f; +} + +.cropper-line.line-e { + top: 0; + right: -3px; + + width: 5px; + + cursor: e-resize; +} + +.cropper-line.line-n { + top: -3px; + left: 0; + + height: 5px; + + cursor: n-resize; +} + +.cropper-line.line-w { + top: 0; + left: -3px; + + width: 5px; + + cursor: w-resize; +} + +.cropper-line.line-s { + bottom: -3px; + left: 0; + + height: 5px; + + cursor: s-resize; +} + +.cropper-point { + width: 5px; + height: 5px; + + opacity: .75; + background-color: #39f; + + filter: alpha(opacity=75); +} + +.cropper-point.point-e { + top: 50%; + right: -3px; + + margin-top: -3px; + + cursor: e-resize; +} + +.cropper-point.point-n { + top: -3px; + left: 50%; + + margin-left: -3px; + + cursor: n-resize; +} + +.cropper-point.point-w { + top: 50%; + left: -3px; + + margin-top: -3px; + + cursor: w-resize; +} + +.cropper-point.point-s { + bottom: -3px; + left: 50%; + + margin-left: -3px; + + cursor: s-resize; +} + +.cropper-point.point-ne { + top: -3px; + right: -3px; + + cursor: ne-resize; +} + +.cropper-point.point-nw { + top: -3px; + left: -3px; + + cursor: nw-resize; +} + +.cropper-point.point-sw { + bottom: -3px; + left: -3px; + + cursor: sw-resize; +} + +.cropper-point.point-se { + right: -3px; + bottom: -3px; + + width: 20px; + height: 20px; + + cursor: se-resize; + + opacity: 1; + + filter: alpha(opacity=100); +} + +.cropper-point.point-se:before { + position: absolute; + right: -50%; + bottom: -50%; + + display: block; + + width: 200%; + height: 200%; + + content: ' '; + + opacity: 0; + background-color: #39f; + + filter: alpha(opacity=0); +} + +@media (min-width: 768px) { + .cropper-point.point-se { + width: 15px; + height: 15px; + } +} + +@media (min-width: 992px) { + .cropper-point.point-se { + width: 10px; + height: 10px; + } +} + +@media (min-width: 1200px) { + .cropper-point.point-se { + width: 5px; + height: 5px; + + opacity: .75; + + filter: alpha(opacity=75); + } +} + +.cropper-invisible { + opacity: 0; + + filter: alpha(opacity=0); +} + +.cropper-bg { + background-image: url('data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQAQMAAAAlPW0iAAAAA3NCSVQICAjb4U/gAAAABlBMVEXMzMz////TjRV2AAAACXBIWXMAAArrAAAK6wGCiw1aAAAAHHRFWHRTb2Z0d2FyZQBBZG9iZSBGaXJld29ya3MgQ1M26LyyjAAAABFJREFUCJlj+M/AgBVhF/0PAH6/D/HkDxOGAAAAAElFTkSuQmCC'); +} + +.cropper-hide { + position: absolute; + + display: block; + + width: 0; + height: 0; +} + +.cropper-hidden { + display: none !important; +} + +.cropper-move { + cursor: move; +} + +.cropper-crop { + cursor: crosshair; +} + +.cropper-disabled .cropper-drag-box, +.cropper-disabled .cropper-face, +.cropper-disabled .cropper-line, +.cropper-disabled .cropper-point { + cursor: not-allowed; +}