Localhost keeps loading in nodejs - node.js

I'm making a authentication system, here is my index.html file i'm using nodejs, express and for database mongodb.
Before it working fine but somehow now its give me no result on visual studio i find no error but the issue is it not giving me the result the keeps loading on the localhost page, i try to change the port but same issue.
const express = require('express');
const cookieParser = require('cookie-parser');
const app = express();
const port = 7000;
// for database
const db = require('./config/mongoose');
const user=require('./models/user');
// for passport authentication
const passport=require('passport');
const passportLocalStrategy=require('./config/passport-local');
const session = require('express-session');
const MongoStore = require('connect-mongo');
app.use(express.urlencoded());
app.use(cookieParser());
// for layouts
const layouts=require('express-ejs-layouts');
app.use(layouts);
// extract style and scripts from sub pages into the layout
app.set('layout extractStyles', true);
app.set('layout extractScripts', true);
//for static files
app.use(express.static('./assets'));
const path=require('path');
// set up the view engine
app.set('view engine', 'ejs');
app.set('views',path.join(__dirname,'views'));
//app.set('views', './views');
app.use(session({
name:'Authentication',
secret:'Dheeraj',
saveUninitialized:false,
resave:false,
cookie:{
maxAge:(1000*60*60)
},
store:( MongoStore.create({
mongoUrl: 'mongodb://localhost/NODEJS_AUTHENTICATION',
autoRemove : 'disabled'
},
function(err){
console.log(err || "connect-mongodb")
}))
}));
app.use(passport.initialize());
app.use(passport.session());
app.use(passport.setUserToLocals);
const passportOauth2Strategy = require('./config/passport-google-oauth2');
const flash=require('connect-flash');
app.use(flash());
app.use(function(req,res,next){
res.locals.flash ={
'success': req.flash('success'),
'error': req.flash('error')
}
next();
});
//use express router
app.use('/',require('./routes'));
app.listen(port, function(err){
if (err){
console.log(`Error in running the server: ${err}`);
}
console.log(`Server is running on port: ${port}`);
});

Related

ReferenceError: done is not defined

const express = require('express');
const cookieParser = require('cookie-parser');
const port = 8000;
const app = express();
const expressLayout = require('express-ejs-layouts');
const db = require('./config/mongoose')
// used for session cookie
const session = require('express-session')
const passport = require('passport')
const passportLocal = require('./config/passport-local-strategy')
app.use(express.urlencoded())
app.use(cookieParser());
// where to look static files like css,js
app.use(express.static('./assets'))
// this line must be above the routes line (line no. 11 in this case) because in the routes all the views are going to be render and before that we have to tell to the browser the layout
app.use(expressLayout)
// extract style and scripts from sub pages into the layout
app.set('layout extractStyles', true);
app.set('layout extractScripts', true);
// set up the view engine
app.set('view engine', 'ejs');
app.set('views', './views');
app.use(session({
name: 'iFacebook',
// TODO change the secret before deployment in production mode
secret: 'Coder',
saveUninitialized: false,
resave: false,
cookie: {
maxAge : (1000*60*100)
}
}))
app.use(passport.initialize());
app.use(passport.session())
// use express router
// require('./routes/index) is similar to require('./routes) in this case, it by default fetch routes
app.use('/', require('./routes/index'))
app.listen(port, (err) => {
if (err) {
console.log(`Error in running the server : ${err}`);
}
console.log(`Server is listening at ${port}`);
})
I am using passport and passport-local strategy and this error comes and even i did not know from which file this error comes. I am sharing the index.js file code which is the server file. This is the first time i am using this even on the documentation i did not found anything

MissingSchemaError: Schema hasn't been registered for model "Store"

I'm using the Wes Boss Node.js tutorial and have been encountering a number of issues with schema errors.
My database is currently running on mLab and MongoDB Compass. It was fine yesterday when I left for work, and I had just added my first bit of data to the DB successfully. This morning I go to continue where I left off, and everything is suddenly broken.
I've tried deleting the node_modules directory, running npm cache clean, and npm install. I have tried changing the order of the dependencies. I thought it might be that the connection just needed restarted, so I closed the connection, exited Compass, re-opened and re-connected to the DB. I tried deleting the "sessions" table and re-connecting. No such luck.
I've tried plugging the database's server address into my browser's URL bar and I receive a message indicating that the connection was successful.
Error:
MissingSchemaError: Schema hasn't been registered for model "Store". Use mongoose.model(name, schema)
at MissingSchemaError (C:\Users\Misha\Desktop\dang-thats-delicious\node_modules\mongoose\lib\error\missingSchema.js:20:11)
app.js:
const express = require('express');
const session = require('express-session');
const mongoose = require('mongoose');
const MongoStore = require('connect-mongo')(session);
const path = require('path');
const cookieParser = require('cookie-parser');
const bodyParser = require('body-parser');
const passport = require('passport');
const promisify = require('es6-promisify');
const flash = require('connect-flash');
const expressValidator = require('express-validator');
const routes = require('./routes/index');
const helpers = require('./helpers');
const errorHandlers = require('./handlers/errorHandlers');
const app = express();
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'pug');
app.use(express.static(path.join(__dirname, 'public')));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(expressValidator());
app.use(cookieParser());
app.use(session({
secret: process.env.SECRET,
key: process.env.KEY,
resave: false,
saveUninitialized: false,
store: new MongoStore({ mongooseConnection: mongoose.connection })
}));
app.use(passport.initialize());
app.use(passport.session());
app.use(flash());
app.use((req, res, next) => {
res.locals.h = helpers;
res.locals.flashes = req.flash();
res.locals.user = req.user || null;
res.locals.currentPath = req.path;
next();
});
app.use((req, res, next) => {
req.login = promisify(req.login, req);
next();
});
app.use('/', routes);
app.use(errorHandlers.notFound);
app.use(errorHandlers.flashValidationErrors);
if (app.get('env') === 'development') {
app.use(errorHandlers.developmentErrors);
}
app.use(errorHandlers.productionErrors);
module.exports = app;
index.js:
const express = require('express');
const router = express.Router();
const storeController = require('../controllers/storeController');
const { catchErrors } = require('../handlers/errorHandlers');
router.get('/', storeController.homePage);
router.get('/add', storeController.addStore);
router.post('/add', catchErrors(storeController.createStore));
module.exports = router;
start.js:
require('./models/Store');
const mongoose = require('mongoose');
const Store = mongoose.model('Store');
require('dotenv').config({ path: 'variables.env' });
mongoose.connect(process.env.DATABASE);
mongoose.Promise = global.Promise;
mongoose.connection.on('error', (err) => {
console.error(`${err.message}`);
});
require('./models/Store');
const app = require('./app');
app.set('port', process.env.PORT || 7777);
const server = app.listen(app.get('port'), () => {
console.log(`Express running → PORT ${server.address().port}`);
});
Well, I think I solved my own problem. My storeController.js file needed require('../models/Store'); at the top, right below const mongoose = require('mongoose');
However, now I'm getting another error, and I believe it's related to removing my stored sessions from the DB:
express-session deprecated req.secret; provide secret option at app.js:38:9
Going to attempt to re-create the DB and see what happens.

How to render route before rendering static files in node js?

I want to render app.use('/', callback function) before rendering the static files from public folder.
Basically I am doing the authentication before accessing the website, so once it gets authenticated it should load the index.html (static file) from the public folder.
How should i do it?
I am using W3ID from IBM to authenticate the site.
const express = require('express');
const session = require('express-session');
const passport = require('passport');
const WebAppStrategy = require("ibmcloud-appid").WebAppStrategy;
const CALLBACK_URL = "public/index.html";
var path = require('path');
var bodyParser = require('body-parser');
var port = process.env.VCAP_APP_PORT || 8080;
var mongoose = require('mongoose');
//var MongoStore = require('connect-mongo')(session);
const app = express();
// mongodb connection
mongoose.connect("mongodb://admin:admin123#ds261430.mlab.com:61430/events");
var db = mongoose.connection;
// mongo error
db.on('error', console.error.bind(console, 'connection error:'));
// parse incoming requests
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(express.static(path.join(__dirname, 'public')));
app.set('views', path.join(__dirname, 'views'));
// Set view engine as EJS
app.engine('html', require('ejs').renderFile);
app.set('view engine', 'html');
// include routes
app.use(session({
secret: "123456",
resave: true,
saveUninitialized: true
}));
app.use(passport.initialize());
app.use(passport.session());
passport.use(new WebAppStrategy({
tenantId: "73585f35-8d9c-4f6f-9ab2-d07ca0c1d371",
clientId: "863fce57-a717-4586-b8a2-0bf221ef4e68",
secret: "MzkxMTMxMWMtNmYxNi00ZjNhLWFiNzctZjFlM2NkMDM1ZTkz",
oauthServerUrl: "https://appid-oauth.eu-gb.bluemix.net/oauth/v3/73585f35-8d9c-4f6f-9ab2-d07ca0c1d371",
redirectUri: "https://csi.eu-gb.mybluemix.net/" + CALLBACK_URL
}));
passport.serializeUser(function(user, cb) {
cb(null, user);
});
passport.deserializeUser(function(obj, cb) {
cb(null, obj);
});
app.get(CALLBACK_URL, passport.authenticate(WebAppStrategy.STRATEGY_NAME));
app.use('/',passport.authenticate(WebAppStrategy.STRATEGY_NAME), function(req, res) {`enter code here`
// do your authentication
});
// listen on port 8080
app.listen(port);
You can do this by just putting your app.use('/',...) above the app.use('/',express.static('...')).
Or
You can do this by passing option {index:false} to express.static like
app.use('/',express.static('path here',{index:false}));
This option will set express.static to not send the index.html by default.

PassportJS Multi-tenancy with ExpressJS

I tried to implement a solution where I have a single ExpressJS app and two Mongoose models for users, one for standard users and the other for administrators. I'm using passport-local-mongoose for the user models. However, I was having an issue where authentication would succeed but the user would not stay in session (req.user would be undefined). I thought that there would be a conflict having two Passport Local strategies with one ExpressJS app. I've been searching for examples and nothing is working. Please see my code below:
index.js
'use strict';
const express = require('express');
const bodyParser = require('body-parser');
const Passport = require('passport').Passport,
appPass = new Passport(),
adminPass = new Passport();
const mongoose = require('mongoose');
const cookieSession = require('cookie-session');
const path = require('path');
const keys = require('./config/keys');
require('./models/User');
require('./models/AdminUser');
require('./models/EM');
mongoose.Promise = global.Promise;
mongoose
.connect(keys.mongoURI)
.then(() => console.log('DB connection successful'))
.catch(err => console.error(err));
// Create new instances of express
const app = express();
const adminApp = express();
// View engine setup
adminApp.set('views', path.join(__dirname, 'views/admin'));
adminApp.set('view engine', 'pug');
// Tell express to use the body-parser middleware and to not parse extended bodies
adminApp.use(bodyParser.urlencoded({ extended: true }));
adminApp.use(bodyParser.json());
const AdminUser = mongoose.model('AdminUser');
adminPass.use(AdminUser.createStrategy());
adminPass.serializeUser(AdminUser.serializeUser());
adminPass.deserializeUser(AdminUser.deserializeUser());
adminApp.use(
cookieSession({
maxAge: 30 * 24 * 60 * 60 * 1000,
keys: [keys.adminCookieKey]
})
);
adminApp.use(adminPass.initialize());
adminApp.use(adminPass.session());
adminApp.use(express.static('public'));
require('./routes/adminRoutes')(adminApp);
adminApp.listen(5001, function(err) {
if (err) {
console.log(err);
}
console.log('Admin server started on port 5001');
});
// app.use(cors());
// View engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'pug');
// Tell express to use the body-parser middleware and to not parse extended bodies
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
const User = mongoose.model('User');
appPass.use(User.createStrategy());
appPass.serializeUser(User.serializeUser());
appPass.deserializeUser(User.deserializeUser());
app.use(
cookieSession({
maxAge: 30 * 24 * 60 * 60 * 1000,
keys: [keys.cookieKey]
})
);
app.use(appPass.initialize());
app.use(appPass.session());
app.use(express.static('public'));
require('./routes/authRoutes')(app);
require('./routes/portalRoutes')(app);
require('./routes/apiRoutes')(app);
if (process.env.NODE_ENV === 'production') {
// Express will serve up production assets
// like our main.js file, or main.css file!
app.use(express.static('client/build'));
// Express will serve up the index.html file
// if it doesn't recognize the route
app.get('*', (req, res) => {
res.sendFile(path.resolve(__dirname, 'client', 'build', 'index.html'));
});
}
const PORT = process.env.PORT || 5000;
app.listen(PORT, function(err) {
if (err) {
console.log(err);
}
console.log('Server started on port 5000');
});
module.exports = {
adminPass: adminPass,
appPass: appPass
};
adminRoutes.js
var Index = require('../index');
var admin = require('../controllers/AdminController.js');
module.exports = app => {
// route to admin dashboard page
app.get('/adminDB', admin.adminDB);
// route to admin login page
app.get('/adminLogin', admin.adminLogin);
// route for admin login action
app.post(
'/adminLogin',
Index.adminPass.authenticate('local'),
admin.adminDoLogin
);
// route for admin logout action
app.get('/adminLogout', admin.adminLogout);
};
When I run this, I get an error that authenticate can't be called on undefined. May be I'm more far off from the proper solution having gone this route but I have no idea how to fix the req.user problem using the previous approach. Does anyone know how to implement multi-tenancy, ideally with only one ExpressJS app?

CANNOT GET / in Node app

I've checked the other related questions and can't pinpoint what's causing the issue (don't have a lot of experience here). I'm trying to launch this app locally basically with its default settings (other than some Twilio keys), have the dependencies installed, mongo is running, but localhost:5000 returns CANNOT GET /.
> node server.js
listening on port 5000
server.js:
// modules =================================================
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var http = require('http').Server(app);
var io = require('socket.io')(http); //real-time chat
var passport = require('passport');
var LocalStrategy = require('passport-local').Strategy;
var cookieParser = require('cookie-parser');
// configuration ===========================================
// public folder for images, css,...
app.use(express.static(__dirname + '/public'))
// config files
// database
var db = require('./config/db');
// models
var User = require('./app/models/users');
var Message = require('./app/models/messages');
//parsing
app.use(bodyParser.json()); // for parsing application/json
app.use(bodyParser.urlencoded({ extended: true })); //for parsing url encoded
//AUTH========================================================
app.use(cookieParser());
app.use(require('express-session')({
secret: 'white rabbit',
resave: false,
saveUninitialized: false
}));
app.use(passport.initialize());
app.use(passport.session());
// passport config
var Member = require('./app/models/members');
passport.use(new LocalStrategy(Member.authenticate()));
passport.serializeUser(Member.serializeUser());
passport.deserializeUser(Member.deserializeUser());
// view engine ejs
app.set('view engine', 'ejs');
//chat namespace
var chatSocket = io.of('/chat')
//routes
require('./app/routes/routes')(app, chatSocket);
//Heroku port
app.set('port', (process.env.PORT || 5000));
//ADMIN====================================================
//create an admin account if none exists
var admin = Member.find({admin: true}, function(err, admins) {
if (err) throw err
else if(admins.length == 0){
//no admin. create default account
Member.register(new Member({username: "admin", admin: true}), "mypassword", function(err, admin){
if(err) throw err;
console.log('Defaut account created successfully!');
})
}
else{
//at least one admin exists
console.log('Admin account already exists : ');
console.log(admins)
}
});
//START ===================================================
http.listen(app.get('port'), function(){
console.log('listening on port ' + app.get('port'));
});
//SOCKET ==================================================
require('./app/controllers/socket')(chatSocket, User, Message);
You didn't set any route that points to /
Point to that route by using app.get
app.get("/", function(req, res) {
res.send("home");
});
There are available routes in /app/routes/*.js files of the repository you cloned.

Resources