Created
October 10, 2013 20:00
-
-
Save joshtwist/6924589 to your computer and use it in GitHub Desktop.
Custom API to let me upload avatars to my blob storage account.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var azure = require('azure'); | |
var qs = require('querystring'); | |
function getSAS(accountName, accountKey, path, resourceType, sharedAccessPolicy) { | |
return qs.encode(new azure.SharedAccessSignature(accountName, accountKey) | |
.generateSignedQueryString(path, {}, resourceType, sharedAccessPolicy)); | |
} | |
function formatDate(date){ | |
var raw = date.toJSON(); | |
//blob service does not like milliseconds on the end of the time so strip | |
return raw.substr(0, raw.lastIndexOf('.')) + 'Z'; | |
} | |
function createAvatarSas(name) { | |
var accountName = '<your blob account name>'; | |
var accountKey = '<your key>'; | |
var host = accountName + '.blob.core.windows.net'; | |
var canonicalizedResource = '/avatars/' + name; | |
// Container exists now define a policy that provides write access | |
// that starts immediately and expires in 5 mins | |
var sharedAccessPolicy = { | |
AccessPolicy:{ | |
Permissions: azure.Constants.BlobConstants.SharedAccessPermissions.WRITE, | |
//Start: //use for start time in future, beware of server time skew | |
Expiry: formatDate(new Date(new Date().getTime() + 1 * 60 * 1000)) //1 minutes from now | |
} | |
}; | |
//Generate the SAS for your BLOB | |
var sasQueryString = getSAS(accountName, | |
accountKey, | |
canonicalizedResource, | |
azure.Constants.BlobConstants.ResourceTypes.BLOB, | |
sharedAccessPolicy); | |
//full path for resource with sas | |
return 'https://' + host + canonicalizedResource + '?' + sasQueryString; | |
} | |
exports.post = function(request, response) { | |
// storage key | |
var sas = createAvatarSas(request.user.userId.replace(':','') + '.png'); | |
response.send( { url: sas}); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment