Expressjs - All Routes Are 404 - javascript

In My Express App, for some reason, all of the routes are returning 404.
Server.js
/**
* Module dependencies
*/
var express = require('express')
var passport = require('passport')
var env = process.env.NODE_ENV || 'development'
var config = require('./config/config')[env]
var mongoose = require('mongoose')
var fs = require('fs')
require('./helpers')
require('express-namespace')
mongoose.connect(config.db)
// Bootstrap models
fs.readdirSync(__dirname + '/app/models').forEach(function (file) {
if (~file.indexOf('.js')) require(__dirname + '/app/models/' + file)
})
// Bootstrap passport config
require('./config/passport')(passport, config)
var app = express()
// Bootstrap application settings
require('./config/express')(app, config, passport)
// Bootstrap routes
require('./config/routes')(app, passport)
// Start the app by listening on <port>
var port = config.port || process.env.PORT || 3000
app.listen(port)
console.log('Express app started on port '+port)
// Expose app
module.exports = app
Routes.js
/**
* Module dependencies.
*/
var mongoose = require('mongoose')
var passportOptions = {
failureFlash: 'Invalid email or password.',
failureRedirect: '/login'
}
// controllers
var home = require('home')
var functions = require('function')
/**
* Expose
*/
module.exports = function (app, passport) {
console.log("SR");
app.get('/', function(req,res){
console.log("//////");
})
app.get('/functions/get',functions.get)
app.post('/functions/submit',functions.sub)
app.get('/login',passport.authenticate('google',{
"scope":"https://www.googleapis.com/auth/userinfo.email https://www.googleapis.com/auth/userinfo.profile",
"hd":"kinokiapp.com"
}))
app.get('/google/callback',passport.authenticate('google', { failureRedirect:"/" }),function(req,res){
res.end("auth")
})
console.log("ER");
}
Home.js
/*!
* Module dependencies.
*/
console.log("HIH");
exports.index = function (req, res) {
res.render('home', {
title: 'Node Express Mongoose Boilerplate'
})
}
function.js
var mongoose = require('mongoose')
var KIFunction = mongoose.model("KIFunction")
exports.get = function(req, res) {
res.type('text/kinoki-function')
res.status(200);
var exclude
try {
exclude = JSON.parse(req.query.n)
} catch (e) {
exclude = []
}
for (var i = 0; i < exclude.length; i++) {
if (typeof exclude[i] != 'string') {
continue;
}
exclude[i] = mongoose.Types.ObjectId(exclude[i])
}
KIFunction.random({
"_id":{
"$nin":exclude
},
approved1:true,
approved2:true,
}).limit(10).exec(function(err,functions){
if (err || functions.length == 0) {return res.end("false")}
var out = ''
functions.forEach(function(f){
out += "{0}#{1}#{2}#{3}|".format(f.steps, f.string, f.difficulty, f._id)
})
res.end(out.substring(0, out.length - 1),"utf8")
})
}
exports.sub = function(req,res){
var fstr = req.body.str
if (!(req.body.hasOwnProperty("str")) || !(fstr.match(KIFunction.functionRegex()))) {
res.status(400)
res.end("false")
return
}
new KIFunction({
string:fstr
}).save(function(err){
if(err) {
res.status(200)
return res.end("false")
}
res.status(200)
res.end("true")
})
}
the output is:
23 Aug 08:21:16 - [nodemon] starting node server.js HIH SR ER
Express app started on port 3000
GET / 404 571ms - 863b
config/config.js
/*!
* Module dependencies.
*/
var path = require('path')
var rootPath = path.resolve(__dirname + '../..')
/**
* Expose config
*/
module.exports = {
development: {
root: rootPath,
db: 'mongodb://localhost/kinoki_dev',
rootURL:"http://localhost/",
logger: 'dev'
},
test: {
root: rootPath,
db: 'mongodb://localhost/kinoki_test',
rootURL:"http://localhost/",
port: 9273,
logger: false
},
ci: {
root: rootPath,
db: ("mongodb://" + process.env.WERCKER_MONGODB_HOST + ":" + process.env.WERCKER_MONGODB_PORT + "/kinoki_ci"),
port: 2547,
rootURL:"http://localhost/",
logger: false
},
production: {
root: rootPath,
dbpass:"xyz",
db: 'mongodb://user:pass#mymongoserver.com:39768/kinoki',
rootURL:"http://kinokiapp.com/",
logger: 'dev'
}
}
config/express.js
/*!
* Module dependencies.
*/
var express = require('express')
var mongoStore = require('connect-mongo')(express)
var helpers = require('view-helpers')
var pkg = require('../package')
var flash = require('connect-flash')
var env = process.env.NODE_ENV || 'development'
var config = require("./config")[env]
/*!
* Expose
*/
module.exports = function (app, config, passport) {
// Add basic auth for staging
if (env === 'staging') {
app.use(express.basicAuth(function(user, pass){
return 'username' == user & 'password' == pass
}))
app.use(function (req, res, next) {
if (req.remoteUser && req.user && !req.user._id) {
delete req.user
}
next()
})
}
app.set('showStackError', true)
// use express favicon
app.use(express.favicon(config.root + '/public/favicon.ico'))
app.use(express.static(config.root + '/public'))
if(config.logger){
app.use(express.logger(config.logger))
}
// views config
app.set('views', config.root + '/app/views')
app.set('view engine', 'jade')
app.configure(function () {
// bodyParser should be above methodOverride
app.use(express.bodyParser())
app.use(express.methodOverride())
// cookieParser should be above session
app.use(express.cookieParser())
app.use(express.session({
secret: pkg.name,
store: new mongoStore({
url: config.db,
collection : 'sessions'
})
}))
// Passport session
app.use(passport.initialize())
app.use(passport.session())
// Flash messages
app.use(flash())
// expose pkg and node env to views
app.locals({
pkg:pkg,
env:env
})
// View helpers
app.use(helpers(pkg.name))
// routes should be at the last
app.use(app.router)
// custom error handler
app.use(function (err, req, res, next) {
if (err.message
&& (~err.message.indexOf('not found')
|| (~err.message.indexOf('Cast to ObjectId failed')))) {
return next()
}
console.error(err.stack)
res.status(500).render('500')
})
app.use(function (req, res, next) {
res.status(404).render('404', { url: req.originalUrl })
})
})
// development specific stuff
app.configure('development', function () {
app.locals.pretty = true;
})
// staging specific stuff
app.configure('staging', function () {
app.locals.pretty = true;
})
}
config/passport.js
/*!
* Module dependencies.
*/
var mongoose = require('mongoose')
var GoogleStrategy = require('passport-google-oauth').OAuth2Strategy
var User = mongoose.model('User')
var config = require('./config')[process.env.NODE_ENV]
/**
* Expose
*/
module.exports = function(passport, config) {
// serialize sessions
passport.serializeUser(function(user, done) {
done(null, user.id)
})
passport.deserializeUser(function(id, done) {
User.findOne({
_id: id
}, function(err, user) {
done(err, user)
})
})
passport.use(new GoogleStrategy({
clientID: process.env.GOOGLE_ID,
clientSecret: process.env.GOOGLE_SECRET,
callbackURL: config.rootURL + 'google/callback'
},
function(accessToken, refreshToken, profile, done) {
User.findOne({
id: profile.id
}, function(err, user) {
if (err) {
return done(err)
}
if (!user) {
user = new User({
id: profile.id,
profile: profile,
accessToken:accessToken,
refreshToken:refreshToken
})
user.save(function(err) {
if (err) {
return done(err)
}
done(null, user)
})
} else {
done(null,user)
}
})
}
))
passport.reqAuth = function(req,res,next){
if(req.isAuthenticated())
return next()
else
res.redirect('/login')
}
}
config/routes.js
/**
* Module dependencies.
*/
var mongoose = require('mongoose')
var passportOptions = {
failureFlash: 'Invalid email or password.',
failureRedirect: '/login'
}
// controllers
var home = require('home')
var functions = require('function')
/**
* Expose
*/
module.exports = function (app, passport) {
console.log("SR");
app.get('/', function(req,res){
console.log("//////");
})
app.get('/functions/get',functions.get)
app.post('/functions/submit',functions.sub)
// app.get('/login',passport.authenticate('google',{
// "scope":"https://www.googleapis.com/auth/userinfo.email https://www.googleapis.com/auth/userinfo.profile",
// "hd":"kinokiapp.com"
// }))
// app.get('/google/callback',passport.authenticate('google', { failureRedirect:"/" }),function(req,res){
// res.end("auth")
// })
console.log("ER");
}
Does Anyone Know why all the routes are returning 404 (all of them are 404, i just don't have the logs).
Please let me know if you need more code.

Express 404's if a request gets to the end of the middleware chain without anything sending a response. So a common reason for this is a missing app.use(app.router).
In your case passport.deserializeUser(id, fn) throws an error within passport.session(). Express passes the request directly to your custom error handler, bypassing app.router. Since the error is not 'not found' it renders 404.
I would probably just return a user of null in the event that User.findOne(... doesn't find a user. You will need to make sure any templates that are shown to both logged-in and non-logged-in users handles both cases.
Also I use this often, it might come in handy:
function restrictToLoggedIn(req, res, next){
if(req.user && req.user !== null){
return next()
} else {
res.send(401, 'Must be logged in');
};
};
app.get('/'
, restrictToLoggedIn
, function(req, res, next){
// req.user is guranteed to be populated
res.locals.user = req.user;
res.render('home');
});
edit: leaving troubleshooting for posterity...
If app.use(app.router) already exists in your ./config/express, check the previous middlewares. You can set a single catchall route at the top of your routes.js to make sure that anything that hits the router sends 200: app.all('*', function(req,res){ res.send(200, req.originalUrl) });
Finally, confirm that require('function') is loading properly. I always use require('./function.js').
You can comment out your app.use(passport... middleware functions to test whether that's at fault.
If none of this helps please post your config/* javascript files.

Related

isAuthenticated() in Passport js always return false

I have been browsing the forum but I am unable to find the error in my code , it always results in false and I am not able to solve it , Please help me...
Is there any other way to authenticate user instead of passport so that I can use it.I am adding more sentences as it is not allowing me to post my query,Sorry..
const http = require("http"),
hostname = "127.0.0.1",
port = 3000,
bodyParser = require("body-parser"),
mongoose = require("mongoose"),
express = require("express"),
passport = require("passport"),
localStrategy = require("passport-local"),
passportLocalMongoose = require("passport-local-mongoose"),
User = require("./models/user");
app = express();
mongoose.connect("mongodb://localhost/drive", { useNewUrlParser: true });
app.set("view engine", "ejs");
app.use(express.static("public"));
app.use(passport.initialize());
app.use(passport.session());
app.use(
require("express-session")({
secret: "Beta tumse na ho payega",
resave: false,
saveUninitialized: false
})
);
passport.use(new localStrategy(User.authenticate()));
passport.serializeUser(User.serializeUser());
passport.deserializeUser(User.deserializeUser());
app.use(bodyParser.urlencoded({ extended: true }));
const server = http.createServer((req, res) => {
res.statusCode = 200;
res.setHeader("Content-Type", "text/plain");
});
app.get("/", function(req, res) {
res.render("index");
});
app.get("/register", function(req, res) {
res.send("hello");
});
app.get("/login", function(req, res) {
res.render("login");
});
app.post(
"/login",
passport.authenticate("local", {
successRedirect: "/",
failureRedirect: "/login"
}),
function(req, res) {}
);
app.get("/logout", function(req, res) {
req.logout();
res.redirect("/");
});
function isLoggedIn(req, res, next) {
if (req.isAuthenticated()) {
return next();
} else {
console.log("Not logged");
res.redirect("/login");
}
}
app.get("/secret", isLoggedIn, function(req, res) {
res.send("You are logged in");
});
app.post("/register", function(req, res) {
if (req.body.password === req.body.cpassword) {
User.register(
new User({ username: req.body.username }),
req.body.password,
function(err, user) {
if (err) console.log(err);
else
passport.authenticate("local")(req, res, function() {
res.send("signed up");
});
}
);
} else res.send("Password Mismatch");
});
//DRIVE SCHEMA
//var driveSchema = mongoose.Schema({
// title: String,
// created: { type: Date, default: Date.now }
//});
app.listen(port, hostname, function() {
console.log("Server is running at " + hostname + "/" + port);
});
//./models/user.js file
const mongoose = require("mongoose"),
passportLocalMongoose = require("passport-local-mongoose");
var UserSchema = new mongoose.Schema({
username: String,
password: String
});
UserSchema.plugin(passportLocalMongoose);
module.exports = mongoose.model("User", UserSchema);
I have used passport and jwt library, to authenticate and maintain session for the user. There is no need to maintain user session on server side.
apis/apis.js : This file has all apis end points. /login url will authenticate user using passport and send a token to the client using jwt
const passport = require('passport')
const expRoute = require('express').Router();
let exporter = process.exporter;
expRoute.post('/login', (req, res, next) => {
passport.authenticate(
'local',
{
// successRedirect: '/',
// failureRedirect: '/login',
successFlash: 'Welcome!',
failureFlash: 'Invalid username or password.'
},
(err, user, info) => {
if (err) {
return res.status(500).json(err)
}
else if (user) {
return res.status(200).json({
token: exporter.generateToken(user)
})
}
else {
return res.status(400).json(info)
}
}
)(req, res, next);
})
expRoute.get('/view', exporter.authenticateToken, (req, res) => {
let param = req.finalTokenExtractedData
if (param && exporter.isObjectValid(param, 'tokenId', true, true)) {
let condition = {
_id: param.tokenId
}
let options = {
_id: 0,
password: 0,
__v: 0
}
process.USER.findOne(condition, options) // mongo find
.then((data) => {
res.status(200).json({
result: data,
msg: 'success'
})
})
.catch((mongoErr) => {
exporter.logNow(`USER mongo Error: ${mongoErr}`)
res.status(400).json({
msg: 'user not found'
})
})
}
else {
res.status(404).json({
msg: 'invalid token'
})
}
})
module.exports = expRoute
common/env.js: This file will initialise all connections such mongo, require few files will be used as global
process.CONFIG = require('../configs/config.json')
process.exporter = require("../lib/exporter.js")
process.dbInit = (globalName, mongoUrl, collectionName) => {
require("../models/db-init.js")(mongoUrl, collectionName)
.then((modelObj) => {
process[globalName] = modelObj // will be used as global
})
.catch((dbInitErr) => {
process.exporter.logNow(`dbInit Error: ${dbInitErr}`)
process.exit()
});
}
lib/exporter.js: This file has exporter class which consist of all major functions like mongo connection, authenticateToken, verifyPassword, etc.
const fs = require('fs'),
redis = require("redis"),
path = require("path"),
mongoose = require('mongoose'); mongoose.set('useCreateIndex', true);
const Schema = mongoose.Schema;
var bcrypt = require('bcryptjs')
var jwt = require('jsonwebtoken')
class Exporter {
mongoConnection(mongoURI, schemaObj) {
return new Promise(async (resolve, reject) => {
if (!mongoURI || typeof mongoURI == 'undefined' || mongoURI.length < 1)
return reject('invalid mongo connection url');
return resolve(mongoose.createConnection(mongoURI, { useNewUrlParser: true }))
})
}
createMongoSchema(schemaObj) {
return (new Schema(schemaObj));
}
createMongoModel(mongoDB, collectionName, newSchema) {
if (newSchema)
return mongoDB.model(collectionName, newSchema)
return mongoDB.model(collectionName)
}
authenticateToken(req, res, next) {
const bearerHeader = req.header('authorization')
if (typeof bearerHeader != 'undefined') {
const bearer = bearerHeader.split(' ')
const bearerToken = bearer[1]
jwt.verify(bearerToken, process.CONFIG.jwt.token.activated, (err, data) => {
if (err)
res.status(400).json({
msg: "Invalid token or please try to login again"
})
else {
process.exporter.getSingleHashKeysValuesFromRedis('expired_token', bearerToken)
.then((redisTokendata) => {
if (redisTokendata)
res.status(400).json({
msg: "token expired"
})
else {
req.finalTokenExtractedData = data
// if (req.originalUrl.trim() == process.logoutURL.trim())
req.jwtToken = {
token: bearerToken,
secret: process.CONFIG.jwt.token.activated
}
next()
}
})
.catch((redisTokenError) => {
process.exporter.logNow(`redis token error: ${redisTokenError}`)
res.status(400).json({
msg: "Some went wrong while checking token. Please try later."
})
})
}
})
}
else
res.status(400).json({
msg: "invalid token"
})
}
generateToken(data) {
let expiry = new Date();
// expiry.setDate(expiry.getDate() + 7)
expiry.setMinutes(expiry.getMinutes() + 5)
return jwt.sign({
tokenId: data._id,
exp: parseInt(expiry.getTime() / 1000),
}, process.CONFIG.jwt.token.activated)
}
createPassword(password) {
return new Promise((resolve, reject) => {
if (typeof password == 'undefined' && password == '')
return reject('password empty')
bcrypt.hash(password, 10, async (bErr, hash) => {
if (bErr)
reject(bErr)
else
resolve(hash)
})
})
}
verifyPassword(enteredPassword, savePassword) {
return bcrypt.compareSync(enteredPassword, savePassword)
}
}
module.exports = (new Exporter());
index.js: This is file which you will execute node index.js.
const express = require('express');
const path = require('path');
const bodyParser = require('body-parser');
const passport = require('passport');
require('./common/env')
require('./configs/passport')
const app = express()
const cors = require('cors')
app.use(cors());
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({ extended: true}))
app.use(passport.initialize())
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
next();
});
let apis = require('./apis/api')
app.use('/user', apis)
/**
* 404 Handler
*/
app.use((req, res, next)=>{
return res.status(404).send("Endpoint "+req.url +" not found");
})
/**
* if any error or exception occurred then write into a JS file so that app can be restarted
*/
process.on('uncaughtException', (err) => {
console.error(err.stack);
});
app.listen(3000, function(server) {
console.log("App listening at 3000");
});
When index.js file has been executed successfully and listening to a port 3000, then use this URL http://localhost:3000/user/login for authentication, it will accept your username and password, then authenticate using passport and send a token to the client as response. The token can contain user data in encrypted form and have expiry time.
Reference link: https://github.com/arjun-707/login-logout-jwt-nodejs
You need the express-session module.
server.js
// Require a possible config.js file with your configuration variables
const Config = require('./models/config.js');
// If the config module is formed as a class
const config = new Config();
const express = new('express');
const app = express();
const session = require('express-session');
const MongoStore = require('connect-mongo')(session);
const uuid = require('uuid/v4');
const mongoose = require('mongoose');
// Require your custom passport local strategy file
const passport = require('./models/sessions');
mongoose.connect('mongodb://localhost:27017/your_db_name', {
useNewUrlParser: true
});
// Set the session options
app.use(session({
// Use UUIDs for session IDs
genid: (req) => {
return uuid()
},
// If you want to store the session in MongoDB using mongoose
// Require your personal mon
store: new MongoStore({
mongooseConnection: mongoose.connection
}),
// Define the session secret in env variable or in config file
secret: process.env.SESSION_SECRET || config.sessionSecretKey,
resave: false,
saveUninitialized: true
}));
// Initialize the passport module
app.use(passport.initialize());
// Tell to passport to use session
app.use(passport.session());
./models/session.js
const passport = require('passport');
const LocalStrategy = require('passport-local').Strategy;
const bcrypt = require('bcrypt-nodejs');
// Your custom MongoDB connection module
const db = require('./db');
// Configure passport.js to use the local strategy
passport.use(new LocalStrategy({
usernameField: 'username'
},
(username, password, done) => {
db.User.find({
username: username // But it could use email as well
}).then(res => {
const user = JSON.parse(JSON.stringify(res[0]));
if (!user) {
return done(null, false, {
message: 'Invalid credentials.\n'
});
}
if (!bcrypt.compareSync(password, user.password)) {
return done(null, false, {
message: 'Invalid credentials.\n'
});
}
return done(null, user);
}).catch(error => done(error));
}
));
// Tell passport how to serialize the user
passport.serializeUser((user, done) => {
done(null, user._id);
});
// Tell passport how to deserialize the user
passport.deserializeUser((id, done) => {
db.User.find({
_id: id
}).then(res => {
const response = typeof res !== undefined && res.length != 0 ? JSON.parse(JSON.stringify(res[0])) : null;
done(null, response)
}).catch(error => done(error, false))
});
// Export passport for external usage
module.exports = passport;
./models/db.js
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const uuid = require('uuid/v4');
// Connect to MongoDB
mongoose.connect('mongodb://localhost:27017/your_db_name', {
useNewUrlParser: true
});
// Define the models container
let models = {};
// Prepare your user schema
const userSchema = Schema({
username: {
type: String,
required: true
},
password: {
type: String,
required: true
}
});
// Assign the user schema
models.User = mongoose.model('User', userSchema);
// Export for external usage
module.exports = models;
/*
In that way you can wrap in "models" all schemas:
const newSchema = Schema({
name: String
});
models.Newschema = mongoose.model('Newschema', newSchema);
module.exports = models;
And use it externally like:
const db = require('./models/db');
db.User.find({}).then(docs => {}).catch(err => {});
db.Newschema.find({}).then(docs => {}).catch(err => {});
Etc....
*/
./models/config.js
class Config {
constructor() {
this.sessionSecretKey = "my-awesome-secretkey";
/* And other configurations */
}
}
module.exports = Config;
/*
Externally use like:
const Config = require('./models/config');
const config = new Config();
let sessionSecretKey = config.sessionSecretKey;
*/
Then you can use the req.isAuthenticated() after the login:
// POST the username and password to '/login' router
app.post('/login', (req, res, next) => {
passport.authenticate('local', (err, user, info) => {
if (info) {
return res.send(info.message)
}
if (err) {
return next(err);
}
if (!user) {
return res.sendStatus(404); // Is a shortcut
// OR -> res.status(404).end();
// OR -> res.status(404).send('Not found'); as you like
}
req.login(user, (err) => {
if (err) return next(err);
// Store the user object retrieved from MongoDB in `req.session`
req.session.user = user;
return res.sendStatus(200); // Is a shortcut
// OR -> res.status(200).end();
// OR -> res.status(200).send('OK'); as you like
})
})(req, res, next);
});
// The logout logic
app.get('/logout', verifySession, function (req, res) {
req.session.destroy(function (err) {
req.logout();
res.redirect('/');
});
});
// Verify the session to protect private routers
function verifySession(req, res, next) {
if (req.isAuthenticated()) {
next();
} else {
// Forbidden
res.redirect('/');
// OR -> res.sendStatus(403);
// OR -> res.status(403).end();
// OR -> res.status(403).send('Forbidden'); as you like
}
}
Of course you have to run npm install with all the dependencies required defined in package.json file or manually instal with npm i express-session#latest --s for all the dependencies required: npm i module-name#latest --s.
Don't forget the
const server = app.listen(config.port || 3000, () => {
console.log(`Server running on ${server.address().port} port.`);
});
At the end of server.js file. I hope that it will be useful for you.

Express / Passport SAML Authentication Redirects Leading to Infinite Loop

Trying to use passport-saml connecting to ADFS.
The SAML Response is coming back with Successful status codes.
We get the following success code back:
"<samlp:StatusCode Value="urn:oasis:names:tc:SAML:2.0:status:Success" /></samlp:Status>"
But our Passport IsAuthenicated is always generating a false.
I have listed out all of our files used for this below and would appreciate any help.
server.js file:
const express = require('express');
const http = require('http');
const path = require('path');
const passport = require('passport');
const morgan = require('morgan');
const cookieParser = require('cookie-parser');
const bodyParser = require('body-parser');
const session = require('express-session');
const errorhandler = require('errorhandler');
var env = process.env.NODE_ENV || 'development';
const config = require('./config/config')[env];
console.log('Using configuration', config);
require('./config/passport')(passport, config);
var app = express();
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
app.use(cookieParser());
app.enable('trust proxy'); // add this line
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));
app.use(session(
{
resave: true,
saveUninitialized: true,
secret: 'default',
proxy: true // add this line
}));
app.use(passport.initialize());
app.use(passport.session());
app.use(morgan('combined'));
function ensureAuthenticated(req, res, next) {
if (//req.isAuthenticated()
true
) {
console.log('req.isAuthenticated = ' + req.isAuthenticated());
return next(); }
else{
console.log('req.isAuthenticated = ' + req.isAuthenticated());
res.redirect('/login');
}
}
app.set('port', config.app.port);
require('./config/routes')(app, config, passport);
//ensure that ensureAuthenticated is in the get function call before master build
//ie app.get('/*', ensureAuthenticated, (req, res)
app.use(express.static(path.join(__dirname, 'public')));
app.get('/*', ensureAuthenticated, (req, res) => {
res.sendFile(path.join(__dirname, 'public/index.html'));
});
app.listen(app.get('port'), function () {
console.log('Express server listening on port ' + app.get('port'));
});
routes.js
module.exports = function (app, config, passport) {
app.get('/', function (req, res) {
res.redirect('/home')
});
app.get('/login',
passport.authenticate(config.passport.strategy,
{
successRedirect: '/',
failureRedirect: '/login'
})
);
app.post('/',
passport.authenticate(config.passport.strategy,
{
failureRedirect: '/',
failureFlash: true
}),
function (req, res) {
res.redirect('/');
}
);
app.get('/logout', function (req, res) {
req.logout();
// TODO: invalidate session on IP
res.redirect('https://redrectsite.com/?wa=signout1.0');
});
};
config.js
module.exports = {
development: {
app: {
name: 'Passport SAML strategy example',
port: process.env.PORT || 80
},
passport: {
strategy: 'saml',
saml: {
callbackUrl: process.env.SAML_CALLBACK_URL || 'https://oursite.com',
entryPoint: process.env.SAML_ENTRY_POINT || 'https://oursite.com/adfs/ls/idpinitiatedsignon',
issuer: process.env.SAML_ISSUER || 'https://oursite.com',
identifierFormat: null,
signatureAlgorithm: 'sha256',
authnContext: 'http://schemas.microsoft.com/ws/2008/06/identity/authenticationmethod/windows',
disableRequestedAuthnContext: true
//cert: process.env.SAML_CERT || null
}
}
}
};
passport.js
const SamlStrategy = require('passport-saml').Strategy;
module.exports = function (passport, config) {
passport.serializeUser(function (user, done) {
done(null, user);
});
passport.deserializeUser(function (user, done) {
done(null, user);
});
passport.use(new SamlStrategy(
{
callbackUrl: config.passport.saml.callbackUrl,
entryPoint: config.passport.saml.entryPoint,
issuer: config.passport.saml.issuer,
cert: config.passport.saml.cert,
identifierFormat: config.passport.saml.identifierFormat,
signatureAlgorithm: config.passport.saml.signatureAlgorithm,
authnContext: config.passport.saml.authnContext,
disableRequestedAuthnContext: config.passport.saml.disableRequestedAuthnContext
},
function (profile, done) {
return done(null,
{
id: profile.uid,
email: profile.email,
displayName: profile.cn,
firstName: profile.givenName,
lastName: profile.sn
});
})
);
};
I had a similar issue. If you look at what isAuthenticated() does, it's actually just checking a property within the request.session object.
https://github.com/jaredhanson/passport/blob/2327a36e7c005ccc7134ad157b2f258b57aa0912/lib/http/request.js#L86
req.isAuthenticated = function() {
var property = 'user';
if (this._passport && this._passport.instance) {
property = this._passport.instance._userProperty || 'user';
}
return (this[property]) ? true : false;
};
I'm not sure if it's passport or express-session, but once you get to the authentication method, the user object is stored at request.session.passport.user so if you like, you can directly verify that it's non-null instead of using the packaged isAuthenticated() method, which seems to check the wrong path.
My code started working after changing it to the following.
if (_.get(req, 'session.passport.user', null)) {
return next();
}
(lodash _.get for easier null-checking of the nested properties)

Best practise to define a PostgreSQL database connection variable globally in a node.js web application?

I am creating a node and express REST application with a PostgreSQL database.
My question is how to define the connection variable globally in a minimalist express application (for a Hello World example)?
I have the following file structure with the following key files included.
{PROJECT_ROOT}\bin\www
{PROJECT_ROOT}\app.js
{PROJECT_ROOT}\routes\index.js
{PROJECT_ROOT}\db\db.js
{PROJECT_ROOT}\db\location.js
{PROJECT_ROOT}\OTHER FILES
The db.js should contain definition of a variable for a connection to the PostgreSQL database globally. This variable should be shared by other modules whenever necessay so that duplicated connections should be avoided.
db.js
var promise = require('bluebird');
/**
*Use dotenv to read .env vars into Node
*/
require('dotenv').config();
const options = {
// Initialization Options
promiseLib: promise,
connect(client, dc, useCount) {
const cp = client.connectionParameters;
console.log('Connected to database:', cp.database);
}
};
const pgp = require('pg-promise')(options);
const connectionString = process.env.PG_CONN_STR;
const db = pgp(connectionString);
module.exports = {
pgp, db
};
location.js defines the business logic to manipulate the gcur_point_location table.
var db_global = require('./db');
var db = db_global.db;
// add query functions
module.exports = {
getAllLocations: getAllLocations,
getLocation: getLocation,
createLocation: createLocation,
updateLocation: updateLocation,
removeLocation: removeLocation
};
function getAllLocations(req, res, next) {
db.any('select * from gcur_point_location')
.then(function (data) {
res.status(200)
.json({
status: 'success',
data: data,
message: 'Retrieved ALL GCUR Point Locations'
});
})
.catch(function (err) {
return next(err);
});
}
function getLocation(req, res, next) {
var locationId = parseInt(req.params.id);
db.one('select * from gcur_point_location where locationid = $1', locationId)
.then(function (data) {
res.status(200)
.json({
status: 'success',
data: data,
message: 'Retrieved ONE Location by Id'
});
})
.catch(function (err) {
return next(err);
});
}
function createLocation(req, res, next) {
req.body.age = parseInt(req.body.age);
db.none('insert into gcur_point_location(locationname, locationstatus, lng, lat)' +
'values(${locationname}, ${locationstatus}, ${lng}, ${lat})',
req.body)
.then(function () {
res.status(200)
.json({
status: 'success',
message: 'Inserted one Location'
});
})
.catch(function (err) {
return next(err);
});
}
function updateLocation(req, res, next) {
db.none('update gcur_point_location set locationname=$1, locationstatus=$2, lng=$3, lat=$4 where locationid=$5',
[req.body.locationname, req.body.locationstatus, parseFloat(req.body.lng),
parseFloat(req.body.lat), parseInt(req.params.id)])
.then(function () {
res.status(200)
.json({
status: 'success',
message: 'Updated Location'
});
})
.catch(function (err) {
return next(err);
});
}
function removeLocation(req, res, next) {
var locationId = parseInt(req.params.id);
db.result('delete from gcur_point_location where locationid=$1', locationId)
.then(function (result) {
/* jshint ignore:start */
res.status(200)
.json({
status: 'success',
message: `Removed ${result.rowCount} Location`
});
/* jshint ignore:end */
})
.catch(function (err) {
return next(err);
});
}
Likewise, munipulation of different tables will be defined in individual js files. All of them will require the db.js.
routes/index.js
var express = require('express');
var router = express.Router();
var db = require('../db/location');
/* GET home page. */
router.get('/', function(req, res, next) {
res.render('index', { title: 'Express' });
});
router.get('/api/locations', db.getAllLocations);
router.get('/api/location/:id', db.getLocation);
router.post('/api/location', db.createLocation);
router.put('/api/location/:id', db.updateLocation);
router.delete('/api/location/:id', db.removeLocation);
module.exports = router;
app.js
var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', indexRouter);
app.use('/users', usersRouter);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
next(createError(404));
});
// error handler
app.use(function(err, req, res, next) {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
// render the error page
res.status(err.status || 500);
res.render('error');
});
module.exports = app;
I would like to have some ideas about whether the above code is a good or a bad practise or any potential failure?
Most of the code makes sense to me, though I would implement your own ORM and model layers, so you can remove some of the code for PSQL queries and follow MVC design pattern. If all you are building is an express api server, then you do not need the View portion.
I usually have a file called ORM, which has something similar to the following:
var orm = {
all: function(tableInput, cb) {
var queryString = "SELECT * FROM " + tableInput + ";";
connection.query(queryString, function(err, result) {
if (err) {
throw err;
}
cb(result);
});
},
create: function(table, cols, vals, cb) {
var queryString = "INSERT INTO " + table;
queryString += " (";
queryString += cols.toString();
queryString += ") ";
queryString += "VALUES (";
queryString += printQuestionMarks(vals.length);
queryString += ") ";
console.log(queryString);
connection.query(queryString, vals, function(err, result) {
if (err) {
throw err;
}
cb(result);
});
},
// An example of objColVals would be {name: panther, sleepy: true}
update: function(table, objColVals, condition, cb) {
var queryString = "UPDATE " + table;
queryString += " SET ";
queryString += objToSql(objColVals);
queryString += " WHERE ";
queryString += condition;
console.log(queryString);
connection.query(queryString, function(err, result) {
if (err) {
throw err;
}
cb(result);
});
}
};
// Export the orm object for the model (cat.js).
module.exports = orm;
Then I define a model file for each table you have in psql as following:
// Import the ORM to create functions that will interact with the database.
var orm = require("../config/orm.js");
var cat = {
all: function(cb) {
orm.all("cats", function(res) {
cb(res);
});
},
// The variables cols and vals are arrays.
create: function(cols, vals, cb) {
orm.create("cats", cols, vals, function(res) {
cb(res);
});
},
update: function(objColVals, condition, cb) {
orm.update("cats", objColVals, condition, function(res) {
cb(res);
});
}
};
// Export the database functions for the controller (catsController.js).
module.exports = cat;
A controller:
var express = require("express");
var router = express.Router();
// Import the model (cat.js) to use its database functions.
var cat = require("../models/cat.js");
// Create all our routes and set up logic within those routes where required.
router.get("/", function(req, res) {
cat.all(function(data) {
var hbsObject = {
cats: data
};
console.log(hbsObject);
res.render("index", hbsObject);
});
});
router.post("/api/cats", function(req, res) {
cat.create(["name", "sleepy"], [req.body.name, req.body.sleepy], function(result) {
// Send back the ID of the new quote
res.json({ id: result.insertId });
});
});
router.put("/api/cats/:id", function(req, res) {
var condition = "id = " + req.params.id;
console.log("condition", condition);
cat.update(
{
sleepy: req.body.sleepy
},
condition,
function(result) {
if (result.changedRows === 0) {
// If no rows were changed, then the ID must not exist, so 404
return res.status(404).end();
}
res.status(200).end();
}
);
});
// Export routes for server.js to use.
module.exports = router;
This follows MVC design pattern which is very easy to read and understand. So my whole folder structure would look something like this:
Best practices for structuring a database layer with pg-promise are shown in pg-promise-demo.
For a complete, real-world example of using that approach, see LISK database layer.

Random redirection

i have a Problem with my project. I want to make a little download system for pictures, so i made a router for /download/:filename. I have the pictures in /userdata/${userId}/ and if i request /download/ with a param like test it logs in my console, but if i use a param wich exists in the userdata folder like Download.jpg it redirects me back to the homepath of the user: /file/${userId} here is my code:
app.js
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var index = require('./routes/index');
const admin = require("./routes/admin");
import file from "./routes/file";
import download from "./routes/download";
const session = require("express-session");
var app = express();
app.set("trust proxy", 1);
app.use(session({
secret: "bla",
resave: false,
cookie: {
maxAge: 120000000
},
saveUninitialized: false
}));
function checkIfLoggedin(req,res,next){
if(!(req.originalUrl === "/") && !req.session.loggedIn){
res.redirect('/');
return;
}
next();
};
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use(checkIfLoggedin);
app.use('/', index);
app.use("/admin", admin);
app.use("/file", file);
app.use("/download", download);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
// error handler
app.use(function(err, req, res, next) {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
// render the error page
res.status(err.status || 500);
res.render('error');
});
module.exports = app;
index.js router
var express = require('express');
var router = express.Router();
const bcrypt = require('bcrypt-nodejs');
var dbPassword;
import mysql from "mysql";
//
/* GET home page. */
router.get('/', function(req, res, next) {
if (req.session.user != undefined) {
res.redirect("/file/"+req.session.user.userId);
}
else{
res.render('index', {});
}
});
router.post('/', function(req,res,next) {
console.log("1");
const enteredUsername = req.body.username;
const enteredPassword = req.body.password;
const con = mysql.createConnection({
host: "localhost",
user: "user",
password: "pass",
database: "db"
});
con.query('SELECT * FROM users WHERE username = ?;', [`${enteredUsername}`], (error, results, fields) => {
if (results.length > 0) {
console.log("2");
console.log(error);
let dbPassword = results[0].password;
bcrypt.compare(enteredPassword, dbPassword, (err,response) => {
console.log(err);
console.log(response);
console.log("3");
if (response == true) {
req.session.user = {
userId: results[0].userId,
username: results[0].username,
isAdmin: results[0].isAdmin,
};
req.session.loggedIn = true;
console.log("file");
if (req.session.user.isAdmin) {
res.redirect("/admin");
}
else{
res.redirect("/file/" + req.session.user.userId);
}
}
else{
req.session.loggedIn = false;
console.log("false");
res.send("Falsches Passwort");
}
});
}
else{
res.send("Falsche Daten");
}
});
});
router.get("/logout", (req,res,next) => {
if (req.session.user.userId) {
req.session.destroy();
res.redirect("/");
}
});
module.exports = router;
file.js
import express from "express";
import fs from "fs";
const router = express.Router();
const userDataPath = "/srv/www/www.precode.tech/www/userdata/";
router.get("/:userId", (req,res,next) => {
//console.log(req.params.userId == req.session.user.userId);
if (req.params.userId == req.session.user.userId) {
const userDataFiles = fs.readdirSync(userDataPath+req.session.user.userId);
res.render("file", {files : userDataFiles, user: req.session.user});
}
else{
res.status(403).render("unauthorized");
}
//res.send(`${req.params.userId} ${req.session.user.userId}`);
});
/*router.get("/:userId/download/:filename", (req,res,next) => {
console.log(req.params.filename);
if (req.params.userId == req.session.user.userId) {
let filePath = `${__dirname}/../userdata/${req.session.user.userId}/`;
res.download(filePath, req.params.filename);
next();
};
});*/
export default router;
download.js
import express from "express";
const router = express.Router();
/*router.get("/", (req,res,next) => {
res.send("download");
});*/
router.get("/:filename", (req,res,next) =>{
console.log(req.params.filename);
});
export default router;
It would be very nice, if you have ideas or see the problem.
Thank you :)
EDIT: It should not redirect to the base path of the user, the get request on download should allways console.log the item
I did not find the flaw, but let's cleanup the code and fix middleware attaching sequence (at least I saw cookie parser attached after session middleware, I suspect only that part) and check.
But let's check my code review / cleanup.
Really hope it helps.
app.js:
const express = require('express');
const path = require('path');
//const favicon = require('serve-favicon');
const logger = require('morgan');
const cookieParser = require('cookie-parser');
const bodyParser = require('body-parser');
const session = require("express-session");
const mysql = require('mysql');
const db = mysql.createConnection({
host: "localhost",
user: "user",
password: "pass",
database: "db"
});
const app = express();
app.set("trust proxy", 1);
// set view engine and renderer
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
// serve static files
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico'))); // no need for it since express static will serve all static files in public folder
app.use(express.static(path.join(__dirname, 'public')));
// connect morgan to profile requests
app.use(logger('dev'));
// parse cookies first
app.use(cookieParser());
// then handle session
app.use(session({
secret: "bla",
resave: false,
cookie: {
maxAge: 120000000
},
saveUninitialized: true
}));
// handle requests data
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use((req, res, next) => {
req.db = db; // attach db connection to request context
next();
});
// public routes that does not need auth check
app.use('/', require('./routes/index'));
const checkIfLoggedin = (req, res, next) => {
if (!req.session.loggedIn) {
return res.redirect('/');
}
res.locals.user = req.session.user;
next();
};
// internal routes that needs auth check
app.use(
'/admin',
checkIfLoggedin,
require('./routes/admin'));
app.use(
'/files',
checkIfLoggedin,
require('./routes/files'));
/* no need for this route, it's covered in files.js
app.use(
'/download',
checkIfLoggedin,
download);
*/
// catch 404 and forward to error handler
app.use((error, req, res, next) => {
if (error) return next(error);
const err = new Error('Not Found');
err.status = 404;
next(err);
});
// error handler
app.use((error, req, res, next) => {
// set locals, only providing error in development
res
.status(error.status || 500)
.render('error', {
message: error.message,
error: req.app.get('env') === 'development' ? error : {}
});
});
module.exports = app;
routes/index.js:
const express = require('express');
const router = express.Router();
const logger = require('winston');
const bcrypt = require('bcrypt-nodejs');
const _ = require('lodash'); // install it: npm i --save lodash
/* GET home page. */
router.get('/', (req, res) => {
if (_.get(req, 'session.user.userId')) {
return res.redirect("/files/" + req.session.user.userId);
}
res.render('index', {});
});
router.post('/auth', (req, res, next) => {
const {username, password} = req.body;
const db = req.db;
const query = 'SELECT * FROM users WHERE username = ? LIMIT 1';
const fields = [username];
db.query(
query,
fields,
(err, result) => {
if (err) {
logger.error(err);
const error = new Error('System fehler');
return next(error);
}
const user = _.get(result, '0');
if (!user) {
req.session.loggedIn = false;
const error = new Error('Benutzer nicht gefunden');
error.status = 403;
return next(error);
}
bcrypt.compare(password, user.password,
(err, isEqual) => {
if(err || !isEqual) {
if (err) logger.error('Error in password compare:', err);
const error = new Error('Passwort ungültig');
error.status = 403;
return next(error);
}
req.session.user = _.pick(user, ['id', 'userId', 'username', 'isAdmin']);
req.session.loggedIn = true;
if (user.isAdmin) {
return res.redirect("/admin");
}
res.redirect("/files/" + user.userId);
});
});
});
router.get("/logout", (req, res) => {
// simply destroy session and redirect,
// no need for session check
req.session.destroy();
res.redirect("/");
});
module.exports = router;
routes/files.js:
const express = require('express');
const router = express.Router();
const logger = require('winston');
const fs = require('fs');
const path = require('path');
const async = require('async');
const userDataPath = path.join(__dirname, '..', 'userdata');
// no need to check userId with session.user.userId
// since middleware attached in app.js will guard this route
// and redirect user to '/'
router.get('/:userId', (req, res, next) => {
if(req.params.userId != req.session.user.userId) {
const error = new Error("You cannot access other user's files");
error.status = 403;
return next(error);
}
const directory = path.join(userDataPath, req.params.userId);
logger.info('Reading directory:', directory);
fs.readdir(
directory,
(err, entries) => {
if (err) {
logger.error(err);
const error = new Error('System error');
return next(error);
}
const directories = [];
const files = [];
async.eachLimit(
entries, 10,
(entry, done) => {
fs.stat(path.join(dir, entry), (error, stat) => {
if (stat.isFile()) files.push(entry);
if (stat.isDirectory()) directories.push(entry);
done();
});
},
() => {
res.render("files", {
directories,
files
});
});
});
});
router.get('/:userId/download/:filename', (req, res, next) => {
if(req.params.userId != req.session.user.userId) {
const error = new Error("You cannot access other user's files");
error.status = 403;
return next(error);
}
res.download(path.join(userDataPath, req.params.userId, req.params.filename));
});
module.exports = router;
P.S. If it works behind nginx, apache and etc make sure userdata folder is not accessible publicly.

Passport: passport-local, express and rethinkdb

I'm having issues getting Passport to work with RethinkDB. I'm trying to authenticate using passport-local and based my solution on this tutorial: Passport Tutorial with RethinkDB
I keep getting the response Bad Request
The structure of my node modules are as follows:
- server
- auth
- auth-controller.js
- auth-router.js
- index.js
- db
- index.js
- views
- index.html
- index.js
auth/auth-controller.js
var authController = {};
authController.getUser = function (req, res) {
if (req.user && req.user.id) {
res.json(req.user);
return;
}
res.status(400).json(null);
};
authController.logout = function (req, res) {
req.logout();
res.redirect('/');
};
authController.login = function (req, res) {
res.redirect('/');
};
module.exports = authController;
auth/auth-router.js
var express = require('express');
var authControllers = require('./auth-controller');
var auth = require('./index');
var authRouter = express.Router();
// Local
authRouter.use('/login/callback/local', auth.authenticate('local'), function (req, res) {
res.redirect('/');
});
authRouter.post('/login/local', auth.authenticate('local'));
// All
authRouter.use('/user', authControllers.getUser);
authRouter.use('/logout', authControllers.logout);
module.exports = authRouter;
auth/index.js
var config = require('config');
var passport = require('passport');
var LocalStrategy = require('passport-local').Strategy;
var r = require('../db');
passport.serializeUser(function (user, done) {
return done(null, user.id);
});
passport.deserializeUser(function (id, done) {
r
.table('Users')
.get(id)
.run(r.conn)
.then(function (user) {
done(null, user);
});
});
var loginCallbackHandler = function (objectMapper) {
return function (accessToken, refreshToken, profile, done) {
if (accessToken !== null) {
r
.table('Users')
.getAll(profile.username, { index: 'username' })
.run(r.conn)
.then(function (cursor) {
return cursor.toArray()
.then(function (users) {
if (users.length > 0) {
return done(null, users[0]);
}
return r.table('Users')
.insert(objectMapper(profile))
.run(r.conn)
.then(function (response) {
return r.table('Users')
.get(response.generated_keys[0])
.run(r.conn);
})
.then(function (newUser) {
done(null, newUser);
});
});
})
.catch(function (err) {
console.log('Error Getting User', err);
});
}
};
};
var callbackURL = 'http://' + config.get('url') + ':' + config.get('ports').http + '/auth/login/callback/login';
// Local
passport.use(new LocalStrategy({
callbackURL: callbackURL
},
loginCallbackHandler(
function (profile) {
return {
'username': profile.username,
'password': profile.password
};
}
)
));
passport.checkIfLoggedIn = function (req, res, next) {
if (req.user) {
return next();
}
return res.status(401).send('You\'re not logged in');
};
module.exports = passport;
db/index.js
var r = require('rethinkdb');
require('rethinkdb-init')(r);
var config = require('config');
r.connections = [];
r.getNewConnection = function () {
return r.connect(config.get('rethinkdb'))
.then(function (conn) {
conn.use(config.get('rethinkdb').db);
r.connections.push(conn);
return conn;
});
};
r.init(config.get('rethinkdb'), [
{
name: 'Users',
indexes: ['username']
}
]).then(function (conn) {
r.conn = conn;
r.connections.push(conn);
r.conn.use(config.get('rethinkdb').db);
});
module.exports = r;
views/index.html
<body>
<h1>Passport/RethinkDB Example</h1>
{{#user}}
<img style='width: 100px; height: 100px;' src='{{ avatarUrl }}'>
<p>You are logged in as <span style="font-weight: bold;">{{ login }}</span>. Account created through <span style="font-weight: bold;">{{ type }}</span>.</p>
<a href='/auth/user'>See user data</a>
</br>
<a href='/auth/logout'>Logout</a>
{{/user}}
{{^user}}
<p>You are not logged in.</p>
<form action="/auth/login/local" method="post">
Username: <input type="text" name="username" value="sam"><br>
Password: <input type="text" name="password" value="123"><br>
<input type="submit" value="Submit">
</form>
{{/user}}
</body>
index.js
var config = require('config');
var express = require('express');
var session = require('express-session');
var engines = require('consolidate');
var app = express();
var auth = require('./auth');
var authRouter = require('./auth/auth-router');
// Middleware
app
.use(session({
secret: '#########',
resave: false,
saveUninitialized: true
}))
.use(auth.initialize())
.use(auth.session());
// Views
app
.set('views', __dirname + '/views')
.engine('html', engines.mustache)
.set('view engine', 'html');
// Routes
app
.use('/auth', authRouter)
.get('/', function (req, res) {
res.render('index.html', { user: req.user });
})
.use(express.static(__dirname + '/../client'))
.use('*', function (req, res) {
res.status(404).send('404 Not Found').end();
});
app.listen(config.get('ports').http);
What have I done to cause the Bad Request issue and is there an easy way to debug this?
The Bad Request occurs when I submit the username and password from the form... this is the url I believe it happens at ../auth/login/local
You don't show your server code. I had a similar problem once and it was because my bodyparser wasn't set up in the server:
const bodyParser = require('body-parser');
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({ extended: true }))
Or something like that. POST requests send info through the body. If that doesn't work, it would be nice to see your server code.

Categories

Resources