# HG changeset patch
# User leetickett <lee@tickett.net>
# Date 1614895424 0
#      Thu Mar 04 22:03:44 2021 +0000
# Node ID 6d271b444801555b37d5b408a1347bcbefadaf04
# Parent  d557403225824baeabfa7b0e53f3b33a07e916f2
Fix alternate port support in gitlab pages

Resolves bug where user custom port settings were not honored for
gitlab pages.

Changelog: fixed

diff --git a/changelogs/unreleased/fix-gitlab-pages-on-alternate-port.yml b/changelogs/unreleased/fix-gitlab-pages-on-alternate-port.yml
new file mode 100644
--- /dev/null
+++ b/changelogs/unreleased/fix-gitlab-pages-on-alternate-port.yml
@@ -0,0 +1,5 @@
+---
+title: Fix gitlab pages on alternate port
+merge_request: 5070
+author: Lee Tickett @leetickett
+type: fixed
diff --git a/files/gitlab-cookbooks/gitlab-pages/libraries/gitlab_pages.rb b/files/gitlab-cookbooks/gitlab-pages/libraries/gitlab_pages.rb
--- a/files/gitlab-cookbooks/gitlab-pages/libraries/gitlab_pages.rb
+++ b/files/gitlab-cookbooks/gitlab-pages/libraries/gitlab_pages.rb
@@ -76,10 +76,16 @@
       Gitlab['gitlab_pages']['gitlab_server'] ||= Gitlab['external_url']
       Gitlab['gitlab_pages']['artifacts_server_url'] ||= Gitlab['gitlab_pages']['gitlab_server'].chomp('/') + '/api/v4'
 
+      parse_auth_redirect_uri
+    end
+
+    def parse_auth_redirect_uri
       return unless Gitlab['gitlab_pages']['access_control']
+      return if Gitlab['gitlab_pages']['auth_redirect_uri']
 
       pages_uri = URI(Gitlab['pages_external_url'].to_s)
-      Gitlab['gitlab_pages']['auth_redirect_uri'] ||= pages_uri.scheme + '://projects.' + pages_uri.host + '/auth'
+      parsed_port = [80, 443].include?(pages_uri.port) ? "" : ":#{pages_uri.port}"
+      Gitlab['gitlab_pages']['auth_redirect_uri'] = pages_uri.scheme + '://projects.' + pages_uri.host + parsed_port + '/auth'
     end
 
     def authorize_with_gitlab
diff --git a/spec/chef/gitlab-pages/recipes/gitlab-pages_spec.rb b/spec/chef/gitlab-pages/recipes/gitlab-pages_spec.rb
--- a/spec/chef/gitlab-pages/recipes/gitlab-pages_spec.rb
+++ b/spec/chef/gitlab-pages/recipes/gitlab-pages_spec.rb
@@ -155,6 +155,23 @@
       end
     end
 
+    context 'with custom port' do
+      before do
+        stub_gitlab_rb(
+          pages_external_url: 'https://pages.example.com:8443',
+          gitlab_pages: {
+            access_control: true
+          }
+        )
+      end
+
+      it 'sets the correct port number' do
+        expect(chef_run).to render_file("/var/opt/gitlab/gitlab-pages/gitlab-pages-config").with_content { |content|
+          expect(content).to match(%r{auth-redirect-uri=https://projects.pages.example.com:8443/auth})
+        }
+      end
+    end
+
     context 'with custom values' do
       before do
         stub_gitlab_rb(