module.exports = function(RED) { var https = require('https'); var http = require('http'); var url = require('url'); var OPERATIONS = { 'oauth:authorize': { method:'GET', path:'/index.php/apps/oauth2/authorize', query:['client_id','state','response_type','redirect_uri'] }, 'oauth:token': { method:'POST', path:'/index.php/apps/oauth2/api/v1/token', body:['grant_type','code','refresh_token','client_id','client_secret'] } }; function OAuth2Node(config) { RED.nodes.createNode(this, config); var node = this; this.configNode = RED.nodes.getNode(config.nextcloud); this.operation = config.operation || 'oauth:token'; if (!this.configNode) { node.error("No NC config node"); return; } node.on('input', function(msg) { var op = OPERATIONS[msg.operation || node.operation]; if (!op) { node.error("Unknown: "+(msg.operation||node.operation), msg); return; } var baseUrl = (node.configNode.baseUrl||'').replace(/\/+$/,''); var uname = node.configNode.credentials.username; var pw = node.configNode.credentials.password; var path = op.path; var qp = []; if (op.query) op.query.forEach(function(q) { var v = msg[q]!==undefined ? msg[q] : ''; if (v!==undefined&&v!=='') qp.push(encodeURIComponent(q)+'='+encodeURIComponent(v)); }); var fu = baseUrl+path+(qp.length?'?'+qp.join('&'):''); var pu = url.parse(fu); var h = {'Accept':'application/json', 'Authorization':'Basic '+Buffer.from(uname+':'+pw).toString('base64')}; var bo={}; if (op.body) op.body.forEach(function(b){ var v=msg[b]!==undefined?msg[b]:''; if(v!==undefined&&v!=='') bo[b]=v; }); var bs=null; if (Object.keys(bo).length>0) {h['Content-Type']='application/json'; bs=JSON.stringify(bo);} var o = {hostname:pu.hostname,port:pu.port||(pu.protocol==='https:'?443:80), path:pu.path,method:op.method,headers:h,rejectUnauthorized:false}; node.log(op.method+' '+fu); var t = pu.protocol==='https:'?https:http; var r = t.request(o,function(res){ var b='';res.on('data',function(c){b+=c;}); res.on('end',function(){msg.statusCode=res.statusCode;msg.operation=msg.operation||node.operation; try{msg.payload=JSON.parse(b);}catch(e){msg.payload=b;}node.send(msg);}); }); r.on('error',function(e){msg.error=e.message;node.error(op.method+' '+fu+' - '+e.message,msg);}); if(bs) r.write(bs); r.end(); }); } RED.nodes.registerType("oauth2", OAuth2Node); };