jueves, 11 de junio de 2015



EJEMPLO DE AUTENTICACION EN NODE JS

/** MIDDLEWARE LOGIN
TIP: Iniciar el servidor de autenticador con NODE_ENV='ambiente(desa,prod)' node Autenticador **/


var connect = require('connect');
var app = connect();

function loggerHello(req, res, next){
foo();
res.setHeader('Content-Type', 'text/plain');
res.end('Hello World Pana');
}

function logger(req, res, next){
//res.setHeader('Content-Type', 'text/plain');
//res.end('Este es el logger');
console.log('#logger en acción', req.method, req.url); next(); } function logger(req, res, next){ console.log('Iniciando... ', req.method, req.url); next(); } function authWithDB(user, pass, cb){ if(pass !== 'luis15'){ return cb('Credenciales incorrectas.');
}
cb();
}

function restrict(req, res, next){
var authorization = req.headers.authorization;
if(!authorization){
return next(new Error('No autorizado'));
}

var parts = authorization.split(' ');
var scheme = parts[0];
var auth = new Buffer(parts[1], 'base64').toString().split(':');
var user = auth[0];
var pass = auth[1];

authWithDB(user, pass, function (err) {
if(err){
return next(err);
}
next();
});
}

function admin(req, res, next){

console.log('ACCEDIENDO A: ',req.url);

switch(req.url){

case '/':
res.end('try /users');
break;

case '/users':
res.setHeader('Content-Type', 'application/json');
res.end(JSON.stringify(['Luis', 'JoseLuis', 'Jp']));
break;
}
}

function errorHandler() {

var env = process.env.NODE_ENV || 'desarrollo';
return function (err, req, res, next){
res.statusCode = 500;

switch (env){

case 'desarrollo':
res.setHeader('Content-Type', 'application/json');
res.end(JSON.stringify(err));
break;
default:
res.end('Server error');
}
};
}

app
.use(logger)
.use('/admin', restrict)
.use('/admin', admin)
.use(loggerHello)
.listen(3000);

1 comentario:

Subscribe to RSS Feed Sígueme en twitter!