-
Notifications
You must be signed in to change notification settings - Fork 1
/
wordpressresttest.js
77 lines (73 loc) · 2.38 KB
/
wordpressresttest.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
var fs = require('fs');
var url = require('url');
var http = require('http');
var WordPressRest = require('../lib/wordpressrest');
var dbfilename = 'wordpressrest.js.db';
try { var wordpress_tokens = JSON.parse(fs.readFileSync(dbfilename)).wordpress_tokens; } catch(e) {}
var wordpressrest = new WordPressRest({'wordpress_tokens': wordpress_tokens});
var server = http.createServer(function(req, res) {
var pathname = url.parse(req.url).pathname;
console.log(pathname);
if(pathname.match("/wordpress/authorize$")) {
wordpressrest.authorize(req, function(response){
this.writeHead(response.statusCode, response.headers);
response.pipe(this);
}.bind(res));
}
else if(pathname.match("/wordpress/authorized$")) {
delete req.headers['accept-encoding'];
wordpressrest.get_access_token(req, function(res, dbfilename, response) {
if(response.error) {
res.end(JSON.stringify(response));
}
else if(response.statusCode != 200) {
res.writeHead(response.statusCode, response.headers);
response.pipe(res);
}
else {
var body = [];
response.on('data', function(chunk) {
this.push(chunk);
}.bind(body));
response.on('end', function(res, body, dbfilename) {
var tokens = JSON.parse(Buffer.concat(body).toString());
if(this.wordpress_tokens) {
for(var k in tokens) {
this.wordpress_tokens[k] = tokens[k]
}
}
else {
this.wordpress_tokens = tokens;
}
fs.writeFile(dbfilename, JSON.stringify({'wordpress_tokens': this.wordpress_tokens}));
res.end(JSON.stringify({'oauth2': 'authorized'}));
}.bind(this, res, body, dbfilename));
}
}.bind(wordpressrest, res, dbfilename));
}
else if(pathname.match("/wordpress")) {
if(!wordpressrest.wordpress_tokens) {
var redirect_url = new url.Url();
redirect_url.pathname = '/wordpress/authorize';
res.writeHead(303, {
'Location': url.format(redirect_url)
});
res.end();
}
else {
var wurl = url.parse(req.url, true);
wurl.pathname = pathname.substring(pathname.indexOf('/', 1));
delete wurl.protocol;
delete wurl.hostname;
delete wurl.host;
req.url = url.format(wurl);
wordpressrest.call_wordpress(req, null, function(response){
this.writeHead(response.statusCode, response.headers);
response.pipe(this);
}.bind(res));
}
}
else {
res.end('nothing here!!');
}
}).listen(3000);