-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathakagi.js
113 lines (100 loc) · 2.44 KB
/
akagi.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
var express = require('express');
var bodyParser = require('body-parser');
try{
var config = require('./config.js');
} catch(e) {
console.log('Please confirm that a config.js file is present in the working directory');
process.exit(1);
}
var app = express();
if(config.http.compress){
var compress = require('compression');
app.use(compress({
threshold:512
}));
}
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.use(function (req, res, next) {
res.header("X-powered-by", "Akagi");
next();
})
app.use(function (req, res, next) {
if(config.http.allowAll){
req.auth = { status: true, uid: '' };
next();
} else {
var db = require('./lib/db');
if(typeof req.headers['authorization'] !== 'string'){
req.auth = { status: false, uid: null };
next();
return;
}
var authKeys = req.headers['authorization'].split(' ');
if(authKeys.length < 2 || authKeys[0].toLowerCase() !== 'basic'){
// Proto Error
req.auth = { status: false, uid: null };
next();
return;
}
try{
var userToken = (new Buffer(authKeys[1], 'base64')).toString('utf8');
var fields = userToken.split(':');
var uid = fields[0], token = fields[1];
req.authUser = {
username: uid,
password: token
};
db.checkToken(uid, token, function(err, result, type){
if(err){
req.auth = { status: false, uid: null };
next();
return;
}
if(result === true){
req.auth = { status: true, uid: uid, type: type };
next();
return;
} else {
req.auth = { status: false, uid: null };
next();
return;
}
});
} catch (e) {
req.auth = { status: false, uid: null };
next();
return;
}
}
});
if(typeof config.http.cors === 'object' && config.http.cors !== null){
app.use(function(req, res, next){
res.header('Access-Control-Allow-Origin', config.http.cors.allow);
next();
});
}
var port = process.env.PORT || config.http.port || 8080;
var api = require('./lib/api');
api.init(config);
app.use('/api', api.router);
// Default Sanity Check
app.get('/',function(req, res) {
res.json({
'message': 'Akagi, up and ready!'
});
});
app.get('*',function(req, res) {
res.status(404, 'Not Found');
res.json({
'error': 'No API binding at resource'
});
});
app.delete('*',function(req, res) {
res.status(405, 'Method not allowed');
res.json({
'error': 'Cannot perform delete at resoursce'
});
});
app.listen(port);
console.log('Akagi running on port ' + port);