knoxxnxt-koa-auth
v6.1.0-1.1.1
Published
Koa helpers for auth
Downloads
4
Maintainers
Readme
koa-auth
Koa middleware for @knoxxnxt/auth
Installation
$ npm i @knoxxnxt/koa-auth
Usage
var koa = require('koa-framework');
var auth = require('@knoxxnxt/auth')();
// any session middleware with the same api as generic-session
var session = require('koa-header-session');
// koa app
var app = koa();
// add session middleware
app.use(session({ defer: true }));
// load user if session exists
app.use(koaAuth.middleware.loadUser);
// mount the auth app at a certain path
var koaAuth = require('@knoxxnxt/koa-auth')(auth);
koaAuth.mount(app, { prefix: '/auth' });
// add some routes
var middleware = koaAuth.middleware;
var router = app.router();
app.mount(router);
// middleware for all routes
router.use(middleware.assertState({ authenticated: true }));
routher.get('/user', middleware.assertState({ status: 'enabled' }), function *() {
this.body = this.state.user || {};
});
// run app
app.listen(3000);
Session
There is no bundled session middleware. This is to allow different session strategies to be employed in app land. Any session middleware with an api compatible with koa-generic-session
are supported.
Known supported session middleware:
Routes
Depending on your application, you may want to enable or disable certain routes. You may use the id
or the path
of the item.
Disabling routes
Setting the disabled
property allows all routes except for those disabled.
koaAuth.mount(app, {
routes: {
disabled: ['adminActivate', '/invite']
}
});
Enabling routes
Setting the enabled
property disables all routes except for those explicitly enabled. This is the RECOMMENDED approach in most cases.
// disable all admin routes, invites, self-registration etc
// only enable login, reset, change password
koaAuth.mount(app, {
routes: {
enabled: ['/login', '/logout', '/resume', '/password/change', '/password/reset-request', '/password/reset-response']
}
});
Custom routes
This is an example of adding token based registration by using a custom route
var _ = require('lodash');
const TOKENS = {
SPECIAL20: { discount: 0.2 },
JABAJABA50: { discount: 0.5 }
};
var tokenRegistration = {
description: 'User registration using tokens',
path: '/token-register',
method: 'POST',
schema: _.merge({}, koaAuth.AuthRouter.spec.register.schema, {
body: {
properties: {
token: { type: 'string', required: true, enum: Object.keys(TOKENS) }
}
}
}),
state: { authenticated: false },
session: { set: true },
fn: function *(body) {
var user = { email: body.email, pass: body.pass };
// token specific logic
// in this case, we are attaching a discount rate to a user
user.properties = {
discount: TOKENS[body.token].discount
};
return yield auth.methods.register(user);
}
};
var router = koaAuth.mount(app, {
routes: {
custom: { tokenRegistration }
}
});
Middleware
loadUser
Loads a user based on the session
Note: Load this middleware before all your app routes
// load your session middleware
app.use()
app.use(koaAuth.middleware.loadUser);
assertState
Asserts the user is allowed to access a record. It can be used to validate the following:
- Authentication status
- User status: string or array
- User role: string or array
// public route
app.get(
'/public',
koaAuth.middleware.assertState({ authenticated: false }),
function *() { this.status = 200; }
);
// private route
app.get(
'/private',
koaAuth.middleware.assertState({ authenticated: true }),
function *() { this.status = 200; }
);
// status
app.get(
'/status/enabled/role/boss',
koaAuth.middleware.assertState({ status: auth.constants.STATUS.ENABLED }),
function *() { this.status = 200; }
);
// multiple statuses
app.get(
'/status/registered-or-enabled',
koaAuth.middleware.assertState({
status: [
auth.constants.STATUS.ENABLED,
auth.constants.STATUS.ENABLED
]
}),
function *() { this.status = 200; }
);
// status + role
app.get(
'/status/enabled/role/boss',
koaAuth.middleware.assertState({
status: auth.constants.STATUS.ENABLED,
role: 'boss'
}),
function *() { this.status = 200; }
);
// multiple roles
app.get(
'/role/boss-or-mgr',
koaAuth.middleware.assertState({
role: ['boss', 'manager']
}),
function *() { this.status = 200; }
);
Middleware
beforeFn
Add a hook to execute before the route relevant auth method is called
Example: Block more than 10 change password requests in a session
router.hooks.beforeFn.add(function *(id, args, method) {
// `this` is bound to route's `this` object
if ('changePassword' === id) {
// do something special here...
let session = yield this.session;
let attempt = session.attempt++;
this.assert(attempt <= 10, 403, 'Max attempts reached');
}
});
afterFn
beforeFn
Add a hook to execute after the route relevant auth method is called
Example: Overwrite response body
router.hooks.beforeFn.add(function *(id, args, method) {
// `this` is bound to route's `this` object
this.body = { example: 'code' };
});
Debugging
Set environment variable DEBUG
to koa-auth:*
or *
for verbose messages.
Changelog
v6.1.0-1.1.0 (22 December 2015)
- added before and after hooks for routes
v6.1.0-1.0.1 (7 December 2015)
- updated dependencies
v6.1.0-1.0.0 (12 October 2015)
- version bumped to match latest auth lib
v6.0.0-1.3.0 (7 August 2015)
assertState
now supports multiple statuses
v6.0.0-1.2.1 (3 August 2015)
- Fixed context for
spec[].fn
- Now context is the same as a koa request context
v6.0.0-1.2.0 (3 August 2015)
- Expose internal functionality to allow user to easily add custom auth routes
v6.0.0-1.1.0 (31 July 2015)
- Added options
routes.enabled
androutes.disabled
for more fine grained control over what routes are created
v6.0.0-1.0.1 (29 July 2015)
- Bumped dependency
@knoxxnxt/auth-http-sec
v6.0.0-1.0.0 (23 July 2015)
- Changed name to @knoxxnxt/koa-auth
- Updated
@knoxxnxt/auth*
dependencies to 6.x versions - Removed koa-mount dependency
v5.0.0-3.0.0 (6 May 2015)
- Bumped
koa-framework
version.- BREAKING CHANGE:
koa-framework
version 3.x.x is no longer supported.
- BREAKING CHANGE:
v5.0.0-2.0.0 (10 Apr 2015)
- Bumped
js_auth-http-spec
- Added
/resume
method - Added ability to skip state checks as specified by the spec
- Added
v5.0.0-1.0.2 (20 Feb 2015)
- Bumped
js_auth-http-spec
v5.0.0-1.0.1 (18 Feb 2015)
- Fix middleware bug not applying due to
id
being removed from the spec description
v5.0.0-1.0.0 (16 Feb 2015)
- Updated
auth
andauth-http-spec
to version 5.0.x
v4.0.0 (3 Feb 2015)
- Initial commit