hostr/api/app.js

82 lines
2.1 KiB
JavaScript
Raw Normal View History

2015-08-22 16:16:15 +01:00
import Router from 'koa-router';
2015-08-22 13:35:06 +01:00
import stats from 'koa-statsd';
2015-07-09 23:01:43 +01:00
import cors from 'kcors';
2015-08-22 16:16:15 +01:00
import StatsD from 'statsy';
2015-07-09 23:01:43 +01:00
import auth from './lib/auth';
import * as user from './routes/user';
import * as file from './routes/file';
import debugname from 'debug';
const debug = debugname('hostr-api');
2015-08-22 16:16:15 +01:00
const router = new Router();
2015-07-09 23:01:43 +01:00
2015-08-30 18:35:05 +02:00
const statsdOpts = {prefix: 'hostr-api', host: process.env.STATSD_HOST};
2015-08-22 18:24:39 +01:00
router.use(stats(statsdOpts));
2015-08-23 22:12:32 +01:00
const statsd = new StatsD(statsdOpts);
router.use(function* statsMiddleware(next) {
2015-08-09 17:21:39 +01:00
this.statsd = statsd;
yield next;
});
2015-08-09 13:46:09 +01:00
2015-08-22 16:16:15 +01:00
router.use(cors({
2015-07-09 23:01:43 +01:00
origin: '*',
2015-08-23 22:12:32 +01:00
credentials: true,
2015-07-09 23:01:43 +01:00
}));
2015-12-07 19:36:50 +00:00
router.use('*', function* authMiddleware(next) {
2015-07-09 23:01:43 +01:00
try {
yield next;
if (this.response.status === 404 && !this.response.body) {
this.throw(404);
}
} catch (err) {
if (err.status === 401) {
2015-08-09 17:21:39 +01:00
this.statsd.incr('auth.failure', 1);
2015-07-09 23:01:43 +01:00
this.set('WWW-Authenticate', 'Basic');
this.status = 401;
this.body = err.message;
2015-08-23 22:12:32 +01:00
} else if (err.status === 404) {
2015-07-09 23:01:43 +01:00
this.status = 404;
this.body = {
error: {
message: 'File not found',
2015-08-23 22:12:32 +01:00
code: 604,
},
2015-07-09 23:01:43 +01:00
};
} else {
if (!err.status) {
debug(err);
2015-08-23 01:05:20 +01:00
this.raven.captureError(err);
2015-07-09 23:01:43 +01:00
throw err;
} else {
this.status = err.status;
this.body = err.message;
}
}
}
this.type = 'application/json';
});
2015-08-22 16:16:15 +01:00
router.get('/user', auth, user.get);
router.get('/user/token', auth, user.token);
router.get('/token', auth, user.token);
router.get('/user/transaction', auth, user.transaction);
router.post('/user/settings', auth, user.settings);
router.get('/file', auth, file.list);
router.post('/file', auth, file.post);
router.get('/file/:id', file.get);
router.put('/file/:id', auth, file.put);
router.delete('/file/:id', auth, file.del);
router.delete('/file/:id', auth, file.del);
// Hack, if no route matches here, router does not dispatch at all
2015-08-23 22:12:32 +01:00
router.get('/(.*)', function* errorMiddleware() {
2015-08-22 16:16:15 +01:00
this.throw(404);
});
2015-07-09 23:01:43 +01:00
2015-08-23 01:05:20 +01:00
export const ws = new Router();
ws.all('/user', user.events);
2015-08-22 16:16:15 +01:00
export default router;