Skip to content

Commit

Permalink
Made some restructuring of the code for better readability.
Browse files Browse the repository at this point in the history
Also fixed bug with the MD5_REGEX where the regexp was accually looking if there was a MD5 hash in the string and not that the string itself was a MD5 hash.
  • Loading branch information
Johan Lindell committed Feb 11, 2016
1 parent c2a9ccd commit 7ae817b
Showing 1 changed file with 20 additions and 13 deletions.
33 changes: 20 additions & 13 deletions lib/gravatar.js
@@ -1,36 +1,43 @@
var crypto = require('crypto')
, querystring = require('querystring');

var MD5_REGEX = /[0-9a-f]{32}/;
var MD5_REGEX = /^[0-9a-f]{32}$/;

var gravatar = module.exports = {
url: function (email, options, protocol) {
email = email || 'unspecified';
email = email.trim().toLowerCase();
var hash = email.match(MD5_REGEX) ? email : crypto.createHash('md5').update(email).digest('hex');
var baseURL;

if(typeof protocol === 'undefined'){
baseURL = "//www.gravatar.com/avatar/";
} else {
baseURL = protocol ? "https://s.gravatar.com/avatar/" : 'http://www.gravatar.com/avatar/';
}

var queryData = querystring.stringify(options);
var query = (queryData && "?" + queryData) || "";
var query = queryData ? ("?" + queryData) : "";

return baseURL + hash + query;
return baseURL + getHash(email) + query;
},
profile_url: function (email, options, https) {
email = email.trim().toLowerCase();
var hash = email.match(MD5_REGEX) ? email : crypto.createHash('md5').update(email).digest('hex');
var format = options != undefined && options.format != undefined ? String(options.format) : 'json'
//delete options.format
if (options != undefined && options.format != undefined) delete options.format
var baseUrl = (typeof secure === 'undefined') ? "//www.gravatar.com/" : (secure ? "https://s.gravatar.com/" : "http://www.gravatar.com/");

//Default format is json, replace
var format = "json";
if(options != undefined && options.format != undefined){
format = options.format;
delete options.format; //Delete so that it is not included in the querystring
}

var baseURL = (https && "https://secure.gravatar.com/") || 'http://www.gravatar.com/';

var queryData = querystring.stringify(options);
var query = (queryData && "?" + queryData) || "";

return baseURL + hash + '.' + format + query;
return baseURL + getHash(email) + '.' + format + query;
}
};

function getHash(email){
email = email || 'unspecified';
email = email.trim().toLowerCase();
return email.match(MD5_REGEX) ? email : crypto.createHash('md5').update(email).digest('hex');
}

0 comments on commit 7ae817b

Please sign in to comment.