Skip to content

Instantly share code, notes, and snippets.

@alexaivars
Last active March 8, 2017 10:12
Show Gist options
  • Select an option

  • Save alexaivars/3592a3cdd44b29c0e778f56e0138cd0c to your computer and use it in GitHub Desktop.

Select an option

Save alexaivars/3592a3cdd44b29c0e778f56e0138cd0c to your computer and use it in GitHub Desktop.
const error = require('debug')('server:error');
const store = require('./data');
const Koa = require('koa');
const Router = require('koa-router');
const omit = require('./utils/omit');
const app = new Koa();
const api = new Router();
const cors = require('./middleware/cors');
const mount = require('koa-mount')
const bodyParser = require('koa-bodyparser')();
const {
getStatusText,
INTERNAL_SERVER_ERROR,
UNAUTHORIZED
} = require('http-status-codes');
const auth = async (ctx, next) => {
const match = ctx.get('Authorization').match(/^Bearer\s(\S+)$/);
if(!match) { ctx.throw(UNAUTHORIZED); }
const user = await store.getUser(match[1]);
if(!user) { ctx.throw(UNAUTHORIZED); }
ctx.state.user = user;
return next();
}
app.use(async (ctx, next) => {
try {
await next();
} catch (err) {
const status = err.status || INTERNAL_SERVER_ERROR;
const title = err.message || getStatusText(INTERNAL_SERVER_ERROR);
const detail = err.stack || 'Ops something went boom!'
ctx.body = { errors: [{
status,
title,
source: { pointer: ctx.href },
detail
}]};
ctx.status = status;
error(err);
}
});
api.get('/me', auth, async (ctx, next) => {
const { id } = ctx.state.user;
const attributes = omit(ctx.state.user, 'id');
ctx.body = {
id,
type: 'user',
attributes
}
});
api.get('/refresh', auth, async (ctx, next) => {
const match = ctx.get('Authorization').match(/^Bearer\s(\S+)$/);
if(!match) { ctx.throw(UNAUTHORIZED); }
const token = await store.refreshToken(ctx.state.user.id, match[1]);
if(!token) { ctx.throw(UNAUTHORIZED); }
ctx.body = {
id: token,
type: 'token'
}
return next();
});
api.post('/authenticate', bodyParser, async (ctx, next) => {
if(!ctx.request.body ||
!ctx.request.body.username ||
!ctx.request.body.password) {
ctx.throw(UNAUTHORIZED);
}
try {
const token = await store.getAuthToken(ctx.request.body.username, ctx.request.body.password);
if(!token) { ctx.throw(UNAUTHORIZED); }
ctx.body = {
id: token,
type: 'token'
}
} catch (e) {
error(e);
ctx.throw(UNAUTHORIZED);
}
});
app.use(cors);
app.use(mount('/api', api.routes()));
app.use(mount('/api', api.allowedMethods()));
app.listen(3000);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment