0.0.3 • Published 9 years ago
koa-simple-auth v0.0.3
Simple User Auth - barebones user authorization
Mongoose User Schema
var userSchema = mongoose.Schema({
email: {
type: String,
trim: true,
lowercase: true,
required: 'email address is required',
unique: true
},
passwordhash: {
type: String,
required: 'password is required'
},
state: {}
});
Session middleware must be loaded before loading koa-simple-auth. The example below uses cookie based koa-session, but you can easily replace that module with one that uses mongoDB or redis to cache user session data.
You do not set "passwordhash" path, instead set the virtual path "password", during validation a bCrypt hash will automatically be created and saved to "passwordhash", the plain text password is never saved.
- "password" virtual path must be 6-64 characters long.
Use the "state" path to save custom user data.
- This path is of "mixed" type, so when you update this variable you will need to call user.markModified('state.somevariable') before calling user.save() or user.savePromise().
User model contains a "savePromise" method, that wraps the asyncronous save method in a promise.
Example: server.js
var koa = require('koa');
var mount = require('koa-mount');
var session = require('koa-session');
var simple_auth = require('koa-simple-auth');
var routes = require('./routes');
var app = koa();
app.keys = [
'some secrete keys',
'used to generate session hash'
];
app.use(session(app));
app.use(simple_auth);
app.use(mount('/', routes.middleware()));
app.listen(process.env.PORT || 3000, function(){
console.log('node listening on port ' + (process.env.PORT || 3000));
});
Example: routes.js
var Router = require('koa-router');
var auth = require('koa-simple-auth');
var koaBody = require('koa-body')();
var router = module.exports = new Router();
var catch_api_error = function *(next){
try{
yield next;
} catch(err){
this.body = JSON.stringify({ "error": err.message });
}
};
router.post('/login',
catch_api_error,
koaBody,
auth.login,
function *() {
this.body = JSON.stringify({ authenticated: true });
}
);
router.post('/register',
catch_api_error,
koaBody,
auth.register,
function *() {
this.body = JSON.stringify({ authenticated: true });
}
);
router.get('/unregister',
catch_api_error,
koaBody,
auth.unregister,
function *() {
this.body = JSON.stringify({ authenticated: false });
}
);
router.get('/logout',
auth.logout,
function *() {
this.body = JSON.stringify({ authenticated: false });
}
);