forked from HackerYou/json-proxy
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
179 lines (160 loc) · 4.32 KB
/
server.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
'use strict'
const queryString = require('querystring');
const request = require('request');
const xml2json = require('xml2json');
const express = require('express');
const app = express();
const mongoose = require('mongoose');
const DB_PATH = 'mongodb://localhost/cache';
const Cache = require('./models/Cache.js');
const bodyParser = require('body-parser');
app.use(function(req, res, next) {
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('Content-Type', 'application/json');
res.setHeader('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Content-length, Accept, Cache-Control');
res.setHeader('Cache-Control','no-cache, no-store, must-revalidate');
res.setHeader('Pragma','no-cache');
res.setHeader('Expires','0');
res.header('Access-Control-Allow-Methods', 'POST, GET, OPTIONS');
next();
});
app.use(bodyParser.json())
mongoose.connect(DB_PATH);
function pullParams(queryObj,pattern) {
var obj = {};
//Pattern for is the request looks like `params[format]`
for(let key in queryObj) {
var patternMatch = key.match(pattern);
if(patternMatch) {
//Get captured pattern
var newKey = patternMatch[1];
obj[newKey] = queryObj[key];
}
}
return obj;
}
const getRequest = (url, data, headers) => {
return request.get({
url: `${url}?${data}`,
headers
});
}
app.all('/', (req,res) => {
let query = '';
if(req.method !== "POST") {
query = queryString.parse(req.url.substring(2));
}
else {
query = req.body;
}
if(!query.xmlToJSON) {
query.xmlToJSON = false;
}
if(query.reqUrl) {
var url = query.reqUrl;
if(req.method !== 'POST') {
var params = pullParams(query,/params\[(.*)\]/);
var userHeaders = pullParams(query,/proxyHeaders\[(.*)\]/);
}
else {
var params = query.params;
var userHeaders = query.proxyHeaders;
}
var data = queryString.stringify(params);
var headers = Object.assign({},userHeaders,{
'User-Agent': 'Proxy.hackeryou.com',
});
if (query.useCache === "true") {
const cacheUrl = `${url}?${data}`
const cached = Cache.findOne({endpoint: cacheUrl}, (err, doc) => {
if (err) console.log(err);
if (doc) {
console.log('Retrieved from cache.');
res.status(200)
.send(JSON.parse(doc.response));
return;
} else {
const requestStream = getRequest(url, data, headers);
let reqRes = '';
requestStream.on('data', (buff) => {
reqRes += buff.toString();
});
requestStream.on('end', () => {
const cache = new Cache();
cache.endpoint = cacheUrl;
cache.response = JSON.stringify(reqRes);
cache.date = new Date();
cache.save()
.then(() => {
console.log('Saved in cache.')
res.status(200)
.send(reqRes.toString());
})
.catch((err) => {
console.log('Error saving in cache: ' + err);
res.status(500)
.send(err);
});
});
}
});
} else {
if(req.method === "POST") {
//TODO This is like super specific just for spotify right now!
request.post({
url: url,
headers: Object.assign(headers,{
'Content-Type': 'application/x-www-form-urlencoded',
'Accept':'application/json'
}),
body: data
},(err,response,body) => {
// console.log(response)
if(query.xmlToJSON === 'true') {
body = xml2json.toJson(body);
}
if(response && response.statusCode === 200) {
res.status(200)
.send(body);
}
else {;
res.status(400)
.send(body);
}
});
}
else {
request.get({
url: url + '?' + data,
headers: headers
},(err,response,body) => {
if(query.xmlToJSON === 'true') {
body = xml2json.toJson(body);
}
if(response && response.statusCode === 200) {
res.status(200)
.send(body);
}
else {;
res.status(400)
.send(body);
}
});
}
}
}
else {
res.end('{"error": "Must be a GET request and contain a reqUrl param"}');
}
});
// app.use(express.static(`${__dirname}/oauth/client`))
// app.get(['/oauth','/oauth*'], (req, res) => {
// if(req.originalUrl.match(/client/gi)) {
// //What is this all aboot?!?
// res.sendFile(`${__dirname}/${req.originalUrl.replace('/oauth/oauth/','/oauth/')}`);
// }
// else {
// res.sendFile(`${__dirname}/oauth/index.html`);
// }
// });
app.listen(4500);