mirror of
https://github.com/scratchfoundation/scratch-auth.git
synced 2025-06-27 10:30:20 -04:00
72 lines
2.1 KiB
JavaScript
72 lines
2.1 KiB
JavaScript
const pako = require('pako');
|
|
|
|
const signer = require('./lib/signer');
|
|
const util = require('./lib/util');
|
|
|
|
class Auth {
|
|
constructor (salt, secret) {
|
|
this.salt = salt;
|
|
this.secret = secret;
|
|
}
|
|
|
|
/**
|
|
* Port of django.core.signing.signer.unsign
|
|
* @param {string} signedString String in the form value:time:signature
|
|
* @return {string} Unsigned string
|
|
*/
|
|
unsign (signedString) {
|
|
// Validate
|
|
if (typeof signedString !== 'string') return;
|
|
if (signedString.indexOf(':') === -1) return;
|
|
|
|
// Decode
|
|
var components = signedString.split(':');
|
|
var value = components.slice(0, -1).join(':');
|
|
var signature = components.slice(-1)[0];
|
|
var challenge = signer.base64Hmac(this.salt, value, this.secret);
|
|
|
|
// Compare signature to challenge
|
|
if (util.md5(signature) !== util.md5(challenge)) return;
|
|
return value;
|
|
}
|
|
|
|
/**
|
|
* Return the usable content portion of a signed, compressed cookie
|
|
* generated by Django's signing module
|
|
* See: github.com/django/django/blob/stable/1.8.x/django/core/signing.py
|
|
* @param {string} s Signed (and optionally compressed) cookie
|
|
* @return {object} Unpacked cookie
|
|
*/
|
|
unpack (s) {
|
|
// Validate
|
|
if (typeof s !== 'string') return;
|
|
|
|
// Storage objects
|
|
const decompress = (s[0] === '.');
|
|
const b64data = s.split(':')[0];
|
|
|
|
// Base64 decode
|
|
var result = util.b64Decode(b64data);
|
|
|
|
try {
|
|
// Handle decompression
|
|
if (decompress) {
|
|
var charData = result.split('').map(function (c) {
|
|
return c.charCodeAt(0);
|
|
});
|
|
var binData = new Uint8Array(charData);
|
|
var data = pako.inflate(binData);
|
|
result = String.fromCharCode.apply(null, new Uint16Array(data));
|
|
}
|
|
|
|
// Convert to object
|
|
result = JSON.parse(result);
|
|
} catch (e) {
|
|
return;
|
|
}
|
|
|
|
return result;
|
|
}
|
|
}
|
|
|
|
module.exports = Auth;
|