koa-middleware
发布于 8 年前 作者 NextZeus 3940 次浏览 来自 分享

Youtube观看网址

code (app.js)

//https://www.youtube.com/watch?v=RVxx2T7SPw8
var koa = require('koa');
var parse = require('co-body');

var r = require('rethinkdbdash')();
var _ = require('koa-route');

var fs = require('co-fs');

var jwt = require('jsonwebtoken');
var logger = require('koa-logger');

var app = koa();

app.use(logger());


var responseTime = require('koa-response-time');
app.use(responseTime());

var mongo = require('koa-mongo');

app.use(mongo({
	uri:'mongodb://admin:123456@localhost:27017'
}));

//jwt middleware
app.use(function *(next){
	if(!this.url.match(/\/$|\/session$/)){
		var token = this.get('x-auth-token');

		try{
			var jwtPayload = yield function(callback){
				jwt.verify(token,'secret',callback);
			};
			this.userId = jwtPayload.userId;
		} catch (e){
			e.status = 401;
			throw e;
		}
	}

	yield next;
	console.log('exiting middleware');
});

app.use(_.get('/',function*(){
	this.type = 'text/html';
	this.body = yield fs.readFile('index.html');
}));


app.use(_.post('/session',function *(){
	var creds = yield parse(this);
	var users = yield r.table('usres').getAll(
		creds.username, {index : 'username'}
	).run();

	var user = users[0];

	if(user && user.password === creds.password){
			this.status = 200;
			this.set('x-auth-token',
				jwt.sign({userId : user.id}, 'secret')
			);
	} else {
		var e =  new Error('invalid credentials');
		this.status = 401;
		throw e;
	}
}));


app.listen(3000);

//node --harmony app.js  


1 回复

早起到公司 看看Youtube的视频教程,每天进步一点点。 [今天北京的雨下的是真大啊😄]

回到顶部