NodeJS : secure some routes with middleware - javascript

I have two files : server.js and user.js , I want to secure some routes in user.js with a middle-ware written in server.je.
server.js
// :::::: G E T T H E P A C K A G E W E N E E D : : : : : : : :
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var morgan = require('morgan');
var mongoose = require('mongoose');
var cors=require('cors');
var jwt = require('jsonwebtoken'); // used to create, sign, and verify tokens
var config = require('./config'); // get our config file
// ─── GET an instance of the router for api routes ────────────────────────────────────────────────────────────────────────
var apiRoutes = express.Router();
var users =require('./app/routes/users');
//
// ────────────────────────────────────────────── II ──────────────────────────────────────────────────────────────────────
// :::::: CONFIGURATION : : : : : : : :
var port = process.env.PORT || 1991; // used to create, sign, and verify tokens
mongoose.connect(config.database, { useMongoClient: true }); // connect to database
app.set('superSecret', config.secret); // secret variable
//
// ────────────────────────────────────────────── III ──────────────────────────────────────────────────────────────────────
// :::::: USE BODY PARSER SO WE CAN GET INFO FROM POST AND/OR URL PARAMETERS : : : : : : : :
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
// :::::: USE MORGAN TO LOG REQUESTS TO THE CONSOLE: : : :
app.use(morgan('dev'));
app.use(cors());
// ──────────────────────────────────────────────────────────────
// :::::: R O U T E S : : : : : : : :
// ──────────────────────────────────────────────────────────────
// ─── A P I ROUTES ────────────────────────────────────────
// :::::: MIDDLEWARE to secure route begin with /api: : : :
apiRoutes.use(function(req, res, next) {
console.log('hah');
var token = req.body.token || req.query.token || req.headers['x-access-token'];
if (token) {
// verifies secret and checks exp
jwt.verify(token, app.get('superSecret'), function(err, decoded) {
console.log([err,decoded]);
if (err) { //failed verification.
return res.json({"error": true, success:false, message:'Faild to authenticate token'});
}
req.decoded = decoded;
next(); //no error, proceed
});
} else {
// forbidden without token
return res.status(403).send({
success: false,
message: 'No token provided.'
});
}
});
apiRoutes.get('/', function(req, res) {
res.json({ message: 'Welcome to the coolest API on earth!' });
});
app.use('/api', apiRoutes);
app.use('/user', users);
// ──────────────────────────────────────────────────
// :::::: S T A R T the server: : : : : :
app.listen(port);
console.log('Magic happens at http://localhost:' + port);
user.js
const express=require('express');
const router=express.Router();
const passport= require('passport');
const jwt=require('jsonwebtoken');
var userRoutes = express.Router();
var config = require('../../config'); // get our config file
var User = require('../../app/models/User'); // get our mongoose model
//
// ─── ROUTE TO REGISTER USER ──────────────────────────────────────────────────────────────────────
//
userRoutes.post('/signup', function(req, res) {
if (!req.body.email || !req.body.password || !req.body.firstname || !req.body.lastname || !req.body.gender || !req.body.isTrainer) {
res.json({ success: false, msg: 'set up required fields' });
} else {
var newUser = new User({
email: req.body.email,
password: req.body.password,
firstname: req.body.firstname,
lastname: req.body.lastname,
gender: req.body.gender,
isTrainer: req.body.isTraine
});
User.find({ email: req.body.email}, function(err, user){
if (err) {
res.send({ success: false, msg:'authentication error'})
}
else if (user.length != 0) {
res.send({success: false, msg:'Email already exists'})
console.log(user);
}else {
// save the user
newUser.save(function(err) {
if (err) {
console.log(err);
}else {
res.send({ success: true, msg: 'Your account created successfully! ' });
}
});
}
})
}
});
userRoutes.post('/signin', function(req, res) {
User.findOne({
email: req.body.email
}, function(err, user) {
if (err) throw err;
if (!user) {
res.send({ success: false, msg: 'Check your email' });
} else {
// check if password matches
user.comparePassword(req.body.password, function(err, isMatch) {
if (isMatch && !err) {
// if user is found and password is right create a token
var token = jwt.sign(user, config.secret,{
expiresIn: 0
});
// return the information including token as JSON
res.json({
success: true,
token: token,
username: user.username
});
} else {
res.send({ success: false, msg: 'Check your password!' });
}
});
}
});
});
userRoutes.get('/users', function(req, res) {
User.find({}, function(err, users) {
res.json(users);
});
});
module.exports= userRoutes;
I want to secure the /user/users with the middle-ware so only user with token can access to. some suggestion please to do that or to change code structure

I would create a helper module that looks like this (e.g. auth.js):
module.exports=function(req,res,next){
//check user
if(valid){
next();
}else{
res.end("auth error");
}
};
So you can simply do this everywhere:
app.use("/top-secret",require("auth.js"));
app.get("/top-secret/main",...);
If you extend the helper module with some closures, it gets realy useful, e.g.:
module.exports.minLevel=function(level){
return function(req,res,next){
if(validUser && level<=user.level){
next();
}else{
res.end("auth error");
}
};
};
Use case
app.use("/admin",require("auth.js").minLevel(5));

Related

Passport.JS deserializeUser Is Never Reached

I have tried almost every method known to stack Overflow but my issue is persisting as the days goes by and I'm really hoping for some help here. As you can tell from the title, Passport-local does not call deserializeUser for some odd reason. My files are set up as shown below.
User.js
const express = require('express');
const app = express();
const router = express.Router();
// const db = require('../config/db');
const session = require('express-session');
const SqlDbStore = require('express-mysql-session')(session);
const passport = require('passport');
const bodyParser = require('body-parser');
const crypto = require('crypto');
const cookieParser = require('cookie-parser')
//----------------------------------------- BEGINNING OF PASSPORT MIDDLEWARE AND SETUP ---------------------------------------------------
app.use(session({
key: 'session_cookie_name',
secret: 'session_cookie_secret',
store: new SqlDbStore({
host: 'localhost',
port: 3306,
user: 'xxxxxxxxxx',
password: 'xxxxxxxxx',
database: 'xxxxxxxxxx',
}),
resave: false,
saveUninitialized: false,
cookie:{
maxAge:1000*60*60*24,
secure: false
}
}));
app.use(passport.initialize());
app.use(passport.session());
require('../config/ppc.js')(passport);
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.use(cookieParser());
/*passport middleware*/
function genPassword(password) {
var salt=crypto.randomBytes(32).toString('hex');
var genhash=crypto.pbkdf2Sync(password, salt, 10000, 60, 'sha512').toString('hex');
return {salt:salt, hash:genhash}
};
function checkAuthentication(req,res,next){
if(req.isAuthenticated()){
//req.isAuthenticated() will return true if user is logged in
next();
} else{
res.redirect("/login");
}
};
//----------------------------------------- END OF PASSPORT MIDDLEWARE AND SETUP ---------------------------------------------------
router.post('/register', (req, res) => {
const firstName = req.body.firstName;
const lastName = req.body.lastName;
const email = req.body.email;
const saltHash = genPassword(req.body.password);
const salt = saltHash.salt;
const hash = saltHash.hash;
db.query('SELECT * FROM Users WHERE UsersEmail = ? ', [email], (err, results) => {
if (err){
console.log(err)
} else if (results.length > 0) {
res.json({ message: 'Email is already registered!' });
} else {
db.query('INSERT INTO Users (UsersFirstName, UsersLastName, UsersEmail, UsersPasswordHash, UsersPasswordSalt) VALUES (?, ?, ?, ?, ?)', [firstName, lastName, email, hash, salt], (err, results) => {
if (err){
console.log(err);
};
res.send(results);
});
}
})
});
router.post('/login', function(req, res, next){
// console.log(req.body);
passport.authenticate('local', function(err, user){
// console.log('Error: ' + err);
// console.log('User ID: ' + user.id + '\nUser Email: ' + user.email + '\nUser Salt: ' + user.salt + '\nUser Hash: ' + user.hash);
// console.log(err, user);
if(err) {
res.json({message: err.message});
}
if(!user) {
res.json({message: info.message});
}
req.logIn(user, (err) => {
if(err) {
res.json({message: err.message});
} else {
return res.redirect('/');
}
});
})(req, res, next);
});
module.exports = router;
PPC.js
module.exports = function (passport) {
const LocalStrategy = require('passport-local').Strategy;
const db = require('./db');
const crypto = require('crypto');
db.connect((err) => {
if (!err) {
console.log("BD Connected");
} else {
console.log("BD Conection Failed");
console.log(err.message);
res.json({message: err.message})
}
});
const customFields={
usernameField: 'email',
passwordField:'password',
};
/*Passport JS*/
const verifyCallback=(email,password,done)=>{
db.query('SELECT * FROM Users WHERE UsersEmail= ?', [email], function(error, results, fields) {
if (error) {
console.log('query error: ' + error);
return done(error);
}
if(results.length==0) {
return done(null,false, { loggedIn: false, message: 'Account is not recognized.'});
}
const isValid=validPassword(password, results[0].UsersPasswordHash, results[0].UsersPasswordSalt);
user={id:results[0].UsersID, email:results[0].UsersEmail, hash:results[0].UsersPasswordHash, salt:results[0].UsersPasswordSalt};
if(isValid) {
return done(null,user, { loggedIn: true, email: email});
} else{
return done(null,false, { loggedIn: false, message: 'Password is incorrect.'});
}
});
};
const strategy = new LocalStrategy(customFields, verifyCallback);
passport.use(strategy);
passport.serializeUser((user,done)=>{
console.log('Inside serialize');
done(null, user.id);
});
passport.deserializeUser((userId, done) => {
console.log('Inside deserialize');
db.query('SELECT * FROM Users WHERE UsersID = ?', [userId], function(error, results) {
done(null, results[0]);
});
});
function validPassword(password, hash, salt){
const hashVerify=crypto.pbkdf2Sync(password, salt, 10000, 60, 'sha512').toString("hex");
return hash === hashVerify;
};
}
I am totally unsure as to what I did wrong here. One thing I will say is, when I change all app.use() to router.use() in my User.Js, I got a consider upgrading MySQL error when I am using mysql2. Regardless, I don't think mysql is my issue because I am able to register to the DB fine using mysql2 and app.use. I believe my issue most likely lies in the router.post(/login).
I ended up just moving to my own encryption method which uses bcrypt. It was the easiest and securest way to go about this process especially with out wasting to much time. If I ever find the solution in the future, I’ll post it on GitHub and will post the link here.
More information on Bcrypt.

can not retrieve values from req.session

i'm new to nodejs, i'm using express-session for my project
I can't retrieve session values nowhere than my login route
I see many people have the same problems
Any recommend or help would be awesome ! you all have a nice day !
Here's my login route
route.post('/verify', (req, res) => {
const email = req.body.email;
const pass = req.body.password;
userModel.findOne({ email: email }, (err, data) => {
if (err) {
console.log(err);
res.status(500).json({
success: false,
message: error.message
});
}
else {
if (data !== null) {
if (!bcryptjs.compareSync(pass, data.password)
) {
res.status(400).json({
success: false,
message: "Wrong Password"
})
}
else {
req.session.currentUser = {
email: data.email,
};
console.log(req.session);
res.status(200).json({
success: true,
message: "Login Success",
data: {
email: data.email,
name: data.name,
id:data.id,
}
})
}
}
else {
res.status(404).json({
success: false,
message: "Email doesn't exist"
})
}
}
})
})
Here's my server.js setup:
const express = require('express');
const bodyParser = require('body-parser');
const mongoose = require('mongoose');
const cors = require('cors');
const session = require('express-session');
const bcryptjs = require('bcryptjs');
const passport = require('passport');
var Schema = mongoose.Schema;
require('./passport/facebook-auth')(passport);
require('dotenv').config();
const passportSetup = require('./passport/google-auth');
const authRoutes = require('./routes/auth-routes');
const userRoutes = require('./user/user.routes')
const userModel = require('./user/user.schema');
// connect to mongodb
mongoose.connect('mongodb://' + process.env.USER + ':' + process.env.PASS + '#localhost:27017/' + process.env.DATABASE + '?authSource=admin', { useNewUrlParser: true, useUnifiedTopology: true }, (e) => {
//FIXME: tim cach viet khac
if (e)
throw e;
else {
console.log("MongoDB Connected...");
// basic init
const server = express();
server.use(session({
secret: 'keyboard cat',
resave: true,
saveUninitialized: false,
}));
server.use(express.static('public'));
// set up cors to allow us to accept requests from our client
server.use(cors({
origin: "http://localhost:3000", // allow to server to accept request from different origin
methods: "GET,HEAD,PUT,PATCH,POST,DELETE",
credentials: true // allow session cookie from browser to pass through
})
);
server.use(bodyParser.json());
// set up session cookies
// initialize passport
server.use(passport.initialize());
server.use(passport.session());
// set up route
server.use('/auth', authRoutes);
server.use('/users', userRoutes);
server.listen(process.env.PORT || 5000, (err) => {
if (err)
throw err;
else
console.log("Server listening on port 5000...");
console.log('hadm x tanhng...');
console.log('ununneee here we come');
});
}
})
after logging in , the session is destroyed automatically
thank you once again

Error: Uncaught, unspecified "error" event. (Not a valid BCrypt hash.)

I am trying to create an api for login in nodejs.but when i check the login route via Http requester it showing nothing in output and command line showing error Error: Uncaught, unspecified "error" event. (Not a valid BCrypt hash.) and i find out that password is not stored in database in encrypted/hash form.
The project structure:
server.js file:
var express = require('express');
var app = express();
var port = process.env.PORT||8080;
var morgan = require('morgan');
var mongoose = require('mongoose');
var bodyParser = require('body-parser');
var router = express.Router();
var appRoutes = require('./app/routes/api')(router);
var path = require('path');
app.use(morgan('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(express.static(__dirname + '/public'));
app.use('/api',appRoutes);
mongoose.connect('mongodb://localhost:27017/tutorial', function(err){
if(err) {
console.log('Not connected to the Database: '+ err);
}
else {
console.log('Succesfully connected to Mongodb');
}
});
app.get('*',function(req,res){
res.sendFile(path.join(__dirname + '/public/app/views/index.html'));
});
app.listen(port, function () {
console.log('Running the server on port ' + port);
});
/app/models/user.js:
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var bcrypt = require('bcrypt-nodejs');
var UserSchema = new Schema({
username: { type: String, lowercase: true, required: true, unique: true },
password: { type: String, required: true },
email: { type: String, lowercase: true, required: true, unique: true }
});
UserSchema.pre('save', function(next) {
var user = this;
bcrypt.hash(user.password, null, null, function(err, hash) {
if (err) return next(err);
user.password = hash;
next();
});
next();
});
UserSchema.methods.comparePassword = function(password) {
return bcrypt.compareSync(password, this.password);
};
module.exports = mongoose.model('User', UserSchema);
/app/routes/api.js:
var User =require('../models/user');
module.exports = function(router) {
//http://localhost:8080/api/users
//User Registration Route
router.post('/users', function(req,res){
var user = new User();
user.username = req.body.username;
user.password = req.body.password;
user.email = req.body.email;
if (req.body.username == null || req.body.username == '' || req.body.email == null || req.body.email == ''|| req.body.password == null || req.body.password == '' ){
res.send('Ensure Username, Email and Password is provided');
} else {
user.save(function(err){
if(err){
res.send('Username or Email already exist');
}
else {
res.send('User created!!!')
}
});
}
});
//User login Route
//http://localhost:8080/api/authenticate
router.post('/authenticate',function(req,res) {
User.findOne({ username: req.body.username }).select('email username password').exec(function(err,user){
if (err) throw err;
if (!user){
res.json({ success: false, message: 'Could not authenticate user'});
}else if(user){
var validPassword = user.comparePassword(req.body.password);
if(!validPassword){
res.json({ success: false, message: 'Could not authenticate user'});
}else {
res.json({ success: true, message: 'User Authenticate!!!'});
}
}
});
});
return router;
}
HTTP requester (it is working fine for register api in /app/models/api.js){and user is succesfully registered}
Terminal:
Database:(where password is not stored in hash i dont know why maybe this is main problem)
Your code calls next() twice in your pre-save function, remove it as followed:
UserSchema.pre('save', function(next) {
var user = this;
bcrypt.hash(user.password, null, null, function(err, hash) {
if (err) return next(err);
user.password = hash;
next();
});
next(); // function to remove
});

express js cannot GET /page

I am very stuck with a routing error on express.js. I am using jade to render my page views. I have read all the docs and refactored many times to no avail.
This is the plain contents of the link that is pointing to the '/sell' route.
index.jade
include layout
html
button.btn.btn-primary(type='submit', href='/sell') Add Item
When clicking this button the browser returns the following as a 404:
Cannot GET /sell
The problem here is that all other routes work correctly, if you are to modify the above href to other pages i.e. '/' , '/sign_in', etc no error occurs. The problem appears to be isolated to the '/sell' route.
The controller with the '/sell' route is below:
server.js
var dotenv = require('dotenv');
dotenv.load();
var session = require('express-session')
var nodemailer = require('nodemailer');
var passport = require('passport');
var LocalStrategy = require('passport-local').Strategy;
var bcrypt = require('bcrypt');
var async = require('async');
var crypto = require('crypto');
var cookieParser = require('cookie-parser');
var flash = require('express-flash');
var express = require('express');
var app = express();
var mongoose = require('mongoose');
var root = __dirname;
var path = require('path');
var User = require('./models/user');
var bodyParser = require('body-parser');
var errorHelper = require('mongoose-error-helper').errorHelper;
var validator = require('validator');
var Item = require("./models/item")
var username, email, password, owner, product_name, condition, details, price;
mongoose.connect(process.env.MONGODB_CONGO_DEV);
// Middleware
app.set('views', 'app/views');
app.set('view engine', 'jade');
app.set('port', process.env.PORT || 3000);
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true}));
app.use(cookieParser());
app.use(session( {
secret: 'session secret key',
resave: false,
saveUninitialized: true
}));
app.use(flash());
app.use(passport.initialize());
app.use(passport.session());
// Routing
app.get('/', function(req,res) {
res.render('index', {
title: 'Congo',
message: 'Congo',
user: req.user
});
});
app.get('/sell', function(req,res) {
res.render('item', {
title: 'Congo - Sell',
message: 'Sell',
user: req.user
});
});
app.get('/sign_in', function(req,res) {
res.render('sign_in', {
title: 'Congo',
message: 'sign in motherfucker',
user: req.user
});
});
app.post('/sign_in', function(req, res, next) {
passport.authenticate('local', function(err, user, info) {
if (err) return next(err)
if (!user) {
req.flash('error', 'Incorrect login details');
return res.redirect('/sign_in')
};
req.logIn(user, function(err) {
if (err) return next(err);
res.
return res.redirect('/');
});
})(req, res, next);
});
app.get('/sign_up', function(req, res) {
res.render('sign_up', {
title: 'Congo',
message: 'sign up',
user: req.user
});
});
app.post('/sign_up', function(req, res) {
var user = new User({
username: req.body.username,
email: req.body.email,
password: req.body.password
});
if (req.body.confirm != req.body.password) {
req.flash('error', 'Password do not match')
res.redirect('/sign_up')
};
else if (validator.isEmail(req.body.email) === false) {
req.flash('error', 'Invalid email address')
res.redirect('/sign_up')
};
else {
user.save(function(err) {
if (err) {
req.flash('error', 'Email already in use')
res.redirect('/sign_up')
} else {
req.logIn(user, function(err) {
res.redirect('/');
});
}
});
};
});
app.get('/logout', function(req, res){
req.logout();
res.redirect('/');
});
app.get('/forgot', function(req, res) {
res.render('forgot', {
user: req.user,
message: 'you wally'
});
});
app.get('/profile', function(req, res) {
res.render('profile', {
user: req.user,
message: 'User profile'
});
});
app.post('/forgot', function(req, res, next) {
async.waterfall([
function(done) {
crypto.randomBytes(20, function(err, buf) {
var token = buf.toString('hex');
done(err, token);
});
},
function(token, done) {
User.findOne({ email: req.body.email }, function(err, user) {
if (!user) {
req.flash('error', 'No account with that email address exists.');
return res.redirect('/forgot');
};
user.resetPasswordToken = token;
user.resetPasswordExpires = Date.now() + 3600000; // 1 hour
user.save(function(err) {
done(err, token, user);
});
});
},
function(token, user, done) {
var smtpTransport = nodemailer.createTransport('SMTP', {
service: 'Gmail',
auth: {
user: 'harryandrew.dix#gmail.com',
pass: process.env.GMAIL_PASS
};
});
var mailOptions = {
to: user.email,
from: 'passwordreset#demo.com',
subject: 'Node.js Password Reset',
text: 'You are receiving this because you (or someone else) have requested the reset of the password for your account.\n\n' +
'Please click on the following link, or paste this into your browser to complete the process:\n\n' +
'http://' + req.headers.host + '/reset/' + token + '\n\n' +
'If you did not request this, please ignore this email and your password will remain unchanged.\n'
};
smtpTransport.sendMail(mailOptions, function(err) {
req.flash('info', 'An e-mail has been sent to ' + user.email + ' with further instructions.');
done(err, 'done');
});
};
], function(err) {
if (err) return next(err);
res.redirect('/forgot');
});
});
app.get('/reset/:token', function(req,res) {
User.findOne({resetPasswordToken: req.params.token, resetPasswordExpires: { $gt: Date.now()}}, function(err,user) {
if (!user) {
req.flash('error', 'Password reset token invalid or expired.');
return res.redirect('/forgot');
}
res.render('reset', {
user: req.user,
message: 'reset dem pass'
});
});
});
app.post('/reset/:token', function(req, res) {
async.waterfall([
function(done) {
User.findOne({ resetPasswordToken: req.params.token, resetPasswordExpires: { $gt: Date.now() } }, function(err, user) {
if (!user) {
req.flash('error', 'Password reset token is invalid or has expired.');
return res.redirect('back');
};
user.password = req.body.password;
user.resetPasswordToken = undefined;
user.resetPasswordExpires = undefined;
user.save(function(err) {
req.logIn(user, function(err) {
done(err, user);
});
});
});
},
function(user, done) {
var smtpTransport = nodemailer.createTransport('SMTP', {
service: 'Gmail',
auth: {
user: 'harryandrew.dix#gmail.com',
pass: process.env.GMAIL_PASS
};
});
var mailOptions = {
to: user.email,
from: 'passwordreset#demo.com',
subject: 'Your password has been changed',
text: 'Hello,\n\n' +
'This is a confirmation that the password for your account ' + user.email + ' has just been changed.\n'
};
smtpTransport.sendMail(mailOptions, function(err) {
req.flash('success', 'Success! Your password has been changed.');
done(err);
});
};
], function(err) {
res.redirect('/');
});
});
// app.post('/add_item', function(req, res) {
// var item = new Item({
// owner: req.user.id,
// product_name: req.body.product_name,
// condition: req.body.condition,
// details: req.body.details,
// price: req.body.price
// });
// item.save(function(err) {
// if (err) {
// req.flash('error', 'Something went wrong, make sure you are signed in.')
// res.redirect('/add_item');
// } else {
// req.logIn(item, function(err) {
// res.redirect('/user_profile');
// });
// };
// });
// });
var server = app.listen(3000, function() {
var host = server.address().address;
var port = server.address().port;
console.log('Example app listening at http://%s:%s',host,port);
});
item.jade
include layout
html
block content
form(method='POST')
legend(style='font-family: Raleway; font-size: 30px;') Item Details
.form-group
label(for='product_name') Product Name
input.form-control(type='text', name='product_name', placeholder='include product name, brand, condition, colour etc.', required autofocus)
.form-group
label(for='condition') Condition
input.form-control(type='text', name='condition', placeholder='e.g. New, Used', required)
.form-group
label(for='image') Image
input.form-control(type='file', name='image')
.form-group
label(for='details') Details
textarea.form-control(name='details', cols='40', rows='5')
.form-group
label(for='price') Price
.input-group
.input-group-addon £
input.form-control(type='text', placeholder='Amount', required)
.input-group-addon .00
br
br
button#btnSubmit.btn.btn-primary(type='submit') Post Item
I think it's acting as form post and tries to reach app.post('/sell')
Change it:
button.btn.btn-primary(type='submit', href='/sell') Add Item
to:
a.btn.btn-primary(href='/sell') Add Item
also remove some parts of middleware and keep only these lines:
app.set('views', 'app/views');
app.set('view engine', 'jade');
app.set('port', process.env.PORT || 3000);
app.use(logger('dev'));
and then navigate in Your browser to /sell route, check if it's working.
if Yes - so problem with one of middlewares that we have deleted to check.
You should add a logger middleware and see what error the server gives when you try to go to that route. Another thing to try would be to rename the sell route and see if that works. That could indicate a conflict with another one of your routes, although it's not clear where this would be from looking at your code.

Node js post authentication req.username & password is undefined

So after more or less 4 hours i have finally made some of my calls to work :P
Now i have a problem here is a picture of what i am sending my server using postman:
If you cannot tell from the picture i am using form-data sending
username = arvind#myapp.com
password = pass123
Pretty standard.
The result of this is:
{
"status": 401,
"message": "Invalid credentials"
}
Now my server looks like this:
Server.js
// 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');
app.all('/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(division_model);
app.use(user_model);
app.use(team_model);
// START THE SERVER
app.listen(port);
console.log('Magic happens on port ' + port);
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: 'arvind#myapp.com'
};
return dbUserObj;
},
validateUser: function(username) {
// spoofing the DB response for simplicity
var dbUserObj = { // spoofing a userobject from the DB.
name: 'arvind',
role: 'admin',
username: 'arvind#myapp.com'
};
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;
using the debugger in line 4 in the auth.js i am able to find that both username & password is undefined. (therefore turned into empty strings)
Can anyone tell me why this is happening ?
Try putting the Header as Content-Type: application/json in POSTMan.

Categories