Saturday, May 11, 2024
 Popular · Latest · Hot · Upcoming
74
rated 0 times [  80] [ 6]  / answers: 1 / hits: 22659  / 9 Years ago, tue, february 17, 2015, 12:00:00

i have the following method to auth my users:



app.all('/*', function(req, res, next) {
// CORS headers
res.header(Access-Control-Allow-Origin, *); // restrict it to the required domain
res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS');
// Set custom headers for CORS
res.header('Access-Control-Allow-Headers', 'Content-type,Accept,X-Access-Token,X-Key');
if (req.method == 'OPTIONS') {
res.status(200).end();
} else {
next();
}
});

var auth = require('./auth.js');
router.post('/login', auth.login);
app.all('/api/*', [require('./middlewares/validateRequest')]);
// If no route is matched by now, it must be a 404
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});


And my Auth.js



    var jwt = require('jwt-simple');

var auth = {

login: function(req, res) {

var username = req.body.username || '';
var password = req.body.password || '';

if (username == '' || password == '') {
res.status(401);
res.json({
status: 401,
message: Invalid credentials
});
return;
}

// Fire a query to your DB and check if the credentials are valid
var dbUserObj = auth.validate(username, password);

if (!dbUserObj) { // If authentication fails, we send a 401 back
res.status(401);
res.json({
status: 401,
message: Invalid credentials
});
return;
}

if (dbUserObj) {

// If authentication is success, we will generate a token
// and dispatch it to the client

res.json(genToken(dbUserObj));
}

},

validate: function(username, password) {
// spoofing the DB response for simplicity
var dbUserObj = { // spoofing a userobject from the DB.
name: 'arvind',
role: 'admin',
username: '[email protected]'
};

return dbUserObj;
},

validateUser: function(username) {
// spoofing the DB response for simplicity
var dbUserObj = { // spoofing a userobject from the DB.
name: 'arvind',
role: 'admin',
username: '[email protected]'
};

return dbUserObj;
}
}

// private method
function genToken(user) {
var expires = expiresIn(7); // 7 days
var token = jwt.encode({
exp: expires
}, require('../config/secret')());

return {
token: token,
expires: expires,
user: user
};
}

function expiresIn(numDays) {
var dateObj = new Date();
return dateObj.setDate(dateObj.getDate() + numDays);
}

module.exports = auth;


This server runs on port 8080.



So when i attempt to go to http://localhost:8080/login i get the following error message:



    Error: Not Found
at app.use.bodyParser.urlencoded.extended (/var/www/example/backend/server.js:34:15)
at Layer.handle [as handle_request] (/var/www/example/backend/node_modules/express/lib/router/layer.js:82:5)
at trim_prefix (/var/www/example/backend/node_modules/express/lib/router/index.js:302:13)
at /var/www/example/backend/node_modules/express/lib/router/index.js:270:7
at Function.proto.process_params (/var/www/example/backend/node_modules/express/lib/router/index.js:321:12)
at next (/var/www/example/backend/node_modules/express/lib/router/index.js:261:10)
at next (/var/www/example/backend/node_modules/express/lib/router/route.js:100:14)
at next (/var/www/example/backend/node_modules/express/lib/router/route.js:104:14)
at next (/var/www/example/backend/node_modules/express/lib/router/route.js:104:14)
at next (/var/www/example/backend/node_modules/express/lib/router/route.js:104:14)


However it seems that the rest of my auth is working because if i go to:



http://localhost:8080/api/user


I get: {status:401,message:Invalid Token or Key}



Can anyone tell me why my login does not work?



Full server script:



    // BASE SETUP
// =============================================================================
var express = require('express'),
bodyParser = require('body-parser');
var app = express();
var router = express.Router();
var es = require('express-sequelize');

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended: true
}));

// =============================================================================

//Secure

app.all('/*', function(req, res, next) {
// CORS headers
res.header(Access-Control-Allow-Origin, *); // restrict it to the required domain
res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS');
// Set custom headers for CORS
res.header('Access-Control-Allow-Headers', 'Content-type,Accept,X-Access-Token,X-Key');
if (req.method == 'OPTIONS') {
res.status(200).end();
} else {
next();
}
});

var auth = require('./auth.js');
router.post('/login', auth.login);
app.all('/api/*', [require('./middlewares/validateRequest')]);
// If no route is matched by now, it must be a 404
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});

var env = app.get('env') == 'development' ? 'dev' : app.get('env');
var port = process.env.PORT || 8080;

var Sequelize = require('sequelize');

// db config
var env = dev;
var config = require('./database.json')[env];
var password = config.password ? config.password : null;

// initialize database connection
var sequelize = new Sequelize(
config.database,
config.user,
config.password,
{
logging: console.log,
define: {
timestamps: false
}
}
);

//Init models
var division_model = require('./lb_models/division/division_model')(express,sequelize,router);
var user_model = require('./lb_models/user/user_model')(express,sequelize,router);
var team_model = require('./lb_models/Team')(express,sequelize,router);

app.use('/api', router);
app.use(division_model);
app.use(user_model);
app.use(team_model);


// START THE SERVER
app.listen(port);
console.log('Magic happens on port ' + port);

More From » node.js

 Answers
43

Try moving your app.use(bodyParser…) statements above the login route. The order of middleware matters. At the time login is called the req object hasn't run through the bodyParser middleware yet.



Also, your router instance is mounted at /api so the router methods will never get called for /login. The following line should be place above your 404 catchall:



app.use('/', router);


Before, you had used app.use('/api', router), which means that your router routes will only be looked at for any request that starts with '/api'. Also, you had place the 'use' statement too far down.


[#67791] Sunday, February 15, 2015, 9 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
brennanm

Total Points: 510
Total Questions: 103
Total Answers: 95

Location: Nicaragua
Member since Tue, Dec 8, 2020
4 Years ago
;