Fixed img_url to work with protocol relative urls

closes #10391

- We use "relative protocol" urls for gravatar images, which were
  incorrectly getting treated as relative path urls.

- Refactored getBlogUrl calls into const
This commit is contained in:
Fabien O'Carroll 2019-01-21 11:41:23 +01:00
parent 26d0f48561
commit 6f87f2af93
2 changed files with 31 additions and 2 deletions

View File

@ -7,6 +7,7 @@
// Returns the URL for the current object scope i.e. If inside a post scope will return image permalink
// `absolute` flag outputs absolute URL, else URL is relative.
const url = require('url');
const proxy = require('./proxy');
const urlService = proxy.urlService;
const STATIC_IMAGE_URL_PREFIX = `/${urlService.utils.STATIC_IMAGE_URL_PREFIX}`;
@ -48,8 +49,18 @@ function getImageWithSize(imagePath, requestedSize, imageSizes) {
return imagePath;
}
if (/https?:\/\//.test(imagePath) && !imagePath.startsWith(urlService.utils.getBlogUrl())) {
const blogUrl = urlService.utils.getBlogUrl();
if (/https?:\/\//.test(imagePath) && !imagePath.startsWith(blogUrl)) {
return imagePath;
} else {
// CASE: imagePath is a "protocol relative" url e.g. "//www.gravatar.com/ava..."
// by resolving the the imagePath relative to the blog url, we can then
// detect if the imagePath is external, or internal.
const resolvedUrl = url.resolve(blogUrl, imagePath);
if (!resolvedUrl.startsWith(blogUrl)) {
return imagePath;
}
}
if (!imageSizes || !imageSizes[requestedSize]) {

View File

@ -117,7 +117,25 @@ describe('{{image}} helper', function () {
});
should.exist(rendered);
rendered.should.equal('http://localhost:82832/content/images/size/w400/my-coole-img.jpg');
});
});
it('should output the correct url for protocol relative urls', function () {
var rendered = helpers.img_url('//website.com/whatever/my-coole-img.jpg', {
hash: {
size: 'medium',
},
data: {
config: {
image_sizes: {
medium: {
width: 400
}
}
}
}
});
should.exist(rendered);
rendered.should.equal('//website.com/whatever/my-coole-img.jpg');
});
it('should output the correct url for relative paths', function () {
var rendered = helpers.img_url('/content/images/my-coole-img.jpg', {
hash: {