add itsdangerous' URLSafeTimedSerializer parser

Parse and return serialized datastructure, if not expired yet. Does not
validate the signature.

    lib.itsdangerous("WzIsIjg1MTM2Yzc5Y2JmOWZlMzZiYjlkMDVkMDYzOWM3MGMyNjVjMThkMzciXQ.BrF35w.IoiMIKcqb2Dgy4Gq7uYXSojcVSM"));
This commit is contained in:
Martin Zimmermann 2014-07-23 18:58:46 +02:00
parent 2001ed423b
commit 701ea7058c
2 changed files with 53 additions and 1 deletions

View File

@ -1,6 +1,7 @@
define(function (require) { define(function (require) {
return { return {
editorify: require("app/lib/editor"), editorify: require("app/lib/editor"),
identicons: require("app/lib/identicons") identicons: require("app/lib/identicons"),
itsdangerous: require("app/lib/itsdangerous")
}; };
}); });

View File

@ -0,0 +1,51 @@
define(function() {
"use strict";
// 2011/01/01 in UTC
var epoch = 1293840000;
var decode = function(str) {
return atob(str + new Array(str.length % 4 + 1).join("="));
};
var timestamp = function(str) {
var bytes = [];
for (var i = 0; i < str.length; i++) {
bytes.push(str.charCodeAt(i));
}
var a = 0;
for (var j = 0; j < bytes.length; j++) {
a = a << 8 | +bytes[j];
}
return a + epoch;
};
/*
* Load data signed with itsdangerous' URLSafeTimedSerializer.
*
* If no signature was found or the payload has been expired, return
* `null`. Otherwise, return unserialized datastructure.
*/
return function(val, max_age) {
if (typeof max_age === "undefined") {
max_age = 900;
}
var _ = val.split(".", 3),
payload = _[0], ts = _[1], signature = _[2];
if (typeof signature === "undefined") {
return null;
}
var age = (new Date()).getTime() / 1000 - timestamp(decode(ts));
if (age > max_age) {
return null;
}
return JSON.parse(decode(payload));
};
});