54 lines
1.4 KiB
JavaScript
54 lines
1.4 KiB
JavaScript
'use strict';
|
|
|
|
module.exports.create = function () {
|
|
var PromiseA = require('bluebird');
|
|
var request = PromiseA.promisify(require('request'));
|
|
var pending = {};
|
|
|
|
function loopback(session, opts) {
|
|
var crypto = require('crypto');
|
|
var token = crypto.randomBytes(8).toString('hex');
|
|
var keyAuth = crypto.randomBytes(32).toString('hex');
|
|
pending[token] = keyAuth;
|
|
|
|
var host;
|
|
if (!opts) {
|
|
opts = session;
|
|
host = 'api.oauth3.org';
|
|
} else {
|
|
host = 'api.' + ((session.token || {}).aud || 'oauth3.org');
|
|
}
|
|
|
|
opts.token = token;
|
|
opts.keyAuthorization = keyAuth;
|
|
opts.iat = Date.now();
|
|
|
|
return request({
|
|
method: 'POST'
|
|
, url: 'https://'+host+'/api/org.oauth3.tunnel/loopback'
|
|
, json: opts
|
|
})
|
|
.then(function (result) {
|
|
if (result.body.error) {
|
|
var err = new Error(result.body.error.message);
|
|
return PromiseA.reject(Object.assign(err, result.body.error));
|
|
}
|
|
return result.body.success;
|
|
});
|
|
}
|
|
|
|
loopback.server = require('http').createServer(function (req, res) {
|
|
var parsed = require('url').parse(req.url);
|
|
var token = parsed.pathname.replace('/.well-known/cloud-challenge/', '');
|
|
if (pending[token]) {
|
|
res.setHeader('Content-Type', 'text/plain');
|
|
res.end(pending[token]);
|
|
} else {
|
|
res.statusCode = 404;
|
|
res.end();
|
|
}
|
|
});
|
|
|
|
return loopback;
|
|
};
|