Below is my server.js (app.js). I am using express with passport, for user authentication. But whenever I restart my node server user logsout.
I am very new to nodejs, I was wondering how I could implement a cookie based authentication. So that user does not log out even if the server starts. I'm sure theres some config change which I have not able to find.
// server.js
// set up ======================================================================
// get all the tools we need
var express = require('express');
var app = express();
var port = process.env.PORT || 80;
var mongoose = require('mongoose');
var passport = require('passport');
var flash = require('connect-flash');
var morgan = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var session = require('express-session');
var configDB = require('./config/database.js');
// configuration ===============================================================
mongoose.connect(configDB.url); // connect to our database
require('./config/passport')(passport); // pass passport for configuration
// set up our express application
app.use(morgan('dev')); // log every request to the console
app.use(cookieParser()); // read cookies (needed for auth)
app.use(bodyParser()); // get information from html forms
app.set('view engine', 'ejs'); // set up ejs for templating
// required for passport
app.use(session({ secret: 'yassers' })); // session secret
app.use(passport.initialize());
app.use(passport.session()); // persistent login sessions
app.use(flash()); // use connect-flash for flash messages stored in session
// routes ======================================================================
require('./app/routes.js')(app, passport); // load our routes and pass in our app and fully configured passport
// launch ======================================================================
app.listen(port);
console.log('The magic happens on port ' + port);
Its logout when you restart your start because its stored in MemoryStore(RAM). Use mongoStore to store your session mongodb. Try below code:
var session = require('express-session');
var MongoStore = require('connect-mongo')(session);
var mongoStore = new MongoStore({
url: 'your mongo db url'
});
app.use(session({
secret: 'your secret',
saveUninitialized: true, // don't create session until something stored
resave: false, //don't save session if unmodified
store: mongoStore,
cookie: {
domain: 'domain name',
maxAge: 1000 * 24 * 60
}
}));
Related
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
I need to validate non-empty fields for a login (post request), but I get this error:
TypeError: req.checkBody is not a function
at D:\IDoo projects\ExpressGenerado\config\routes.js:76:9
This is my route file:
app.post('/login',function(req,res){
req.checkBody('email', 'Email is required').notEmpty();
req.checkBody('password', 'Password is required').notEmpty();
var errors = req.validationErrors();
if (errors) {
res.render('signup',{message: req.flash('loginMessage')});
}
else{
passport.authenticate('local-login', {
successRedirect : '/profile', // redirect to the secure profile section
failureRedirect : '/login', // redirect back to the signup page if there is an error
failureFlash : true // allow flash messages
})(req,res);
}
});
And my entry point app file, after adding app.use(expressValidator) my web hangs up and doesn't validate, it does nothing:
var express = require('express');
var expressValidator = require ('express-validator');
var app = express();
var multer = require('multer')
var constants = require('constants');
var constant = require('./config/constants');
var port = process.env.PORT || 8042;
var passport = require('passport');
var flash = require('connect-flash');
var path = require('path');
var morgan = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var session = require('express-session');
var dateFormat = require('dateformat');
var now = new Date();
app.use(expressValidator);
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));
require('./config/passport')(passport); // pass passport for configuration
app.use(morgan('dev')); // log every request to the console
app.use(cookieParser()); // read cookies (needed for auth)
app.use(express.static(path.join(__dirname, 'public')));
app.set('views', path.join(__dirname, 'app/views'));
app.set('view engine', 'ejs');
app.use(session({ secret: 'zomaareenstukjetekstDatjenietzomaarbedenkt' }));
app.use(passport.initialize());
app.use(passport.session()); // persistent login sessions
app.use(flash()); // use connect-flash for flash messages stored in session
require('./config/routes.js')(app, passport); // load our routes and pass in our app and fully configured passport
app.listen(port);
console.log('The magic happens on port ' + port);
You're doing this:
app.use(expressValidator);
However, expressValidator is a function that returns a middleware function, so you need to use it like this:
app.use(expressValidator());
I'm trying to run my node server.js there but it's not working.
I have sent all my files over the FTP in a folder called api (wwwroot is my website, so i need to run this server inside api folder).
Do i need to do something else or what?
Here's my server.js code:
//Dependecies
var express = require('express');
var app = express();
var port = process.env.PORT || 3030;
var morgan = require('morgan');
var cookieParser = require('cookie-parser');
var session = require('express-session')
var mongoose = require('mongoose');
var bodyParser = require('body-parser');
var passport = require('passport');
var flash = require('connect-flash');
var MongoStore = require('connect-mongo')(session);
var cors = require('./cors');
//Database Configurations
var configDB = require('./config/database.js');
mongoose.connect(configDB.url);
//Passport Strategies
require('./config/passport')(passport);
//Morgan Logger
app.use(morgan('dev'));
//Cookie Parser
app.use(cookieParser());
//bodyParser
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
//Session
app.use(session({
secret: 'keyboard cat',
resave: true,
saveUninitialized: true,
cookie: { maxAge: null, secure: false },
store: new MongoStore({
url: configDB.url,
collection: 'sessions'
})
}));
//Connect Flash
app.use(flash());
//CORS Setup
app.use(cors());
//Passport
app.use(passport.initialize());
app.use(passport.session());
//Require the Routes
require('./app/routes.js')(app, passport);
//Start Server
app.listen(port);
console.log('Server is Running!');
EDIT :
When i type in the console, it stops for a bit and print "Bad Request".
Commonly, the 400 BAD request HTTP error code means that the request could not be understood by the server due to malformed syntax. You could check your request url, or post body.
Additionally, you can use the FTP tool to check whether there is a web.config file in your root directory on Azure Web Apps environment. If not, you can manually create one, you can refer to https://tomasz.janczuk.org/2011/08/hosting-express-nodejs-applications-in.html for a sample for an express based application.
Meanwhile, you can refer to https://learn.microsoft.com/en-us/azure/app-service-web/app-service-web-nodejs-best-practices-and-troubleshoot-guide for more info about troubleshooting on node.js applications on Azure Web Apps.
Any further concern, please feel free to let me know.
Maybe in express, there are some thing changed. But I don't know how to send the session:
var session = require('express-session');
app.use('/', routes);
to another .js file router.
var express = require('express');
var router = express.Router();
module.exports = router;
generally seesion we configure in configure section like this
var express = require('express')
var parseurl = require('parseurl')
var session = require('express-session')
var app = express()
app.use(session({
secret: 'keyboard cat',
resave: false,
saveUninitialized: true
}))
in controller level we can access the session like
req.session
we can access seesion
to regenerate the session
req.session.regenerate(function(err) {
// will have a new session here
})
destroy seesion
req.session.destroy(function(err) {
// cannot access session here
})
store the value in session
req.session.key = value;
retrieving value from session
req.session.key
refer the given link
https://github.com/expressjs/session
we can pass api object to route configuration like this ;
var api = require('express');
require('../api/routes/authorization.routes.js')(api);
in route configuration
module.exports = function (api) {
api.route('/api/authorization/token')
.post( authorization.token);
};
I am trying to using Redis with my exsiting application
Here is my app.js code
var express = require('express'),
request = require('request'),
http = require('http'),
path = require('path');
var app = express();
var routes = require('./routes');
var passport = require('passport');
var flash = require('connect-flash');
var cookieParser = require('cookie-parser');
var session = require('express-session');
var busboy = require('connect-busboy');
var policies = require('./policies/admin');
var config = require('./config');
require('./libs/passport')(passport);
app.configure(function () {
app.use(express.session({ secret: 'secertkey', cookie: { maxAge : 2592000000 } })); // session secret
app.use(passport.initialize());
app.use(passport.session()); // persistent login sessions
});
Which is working fine.
I want to use Rediss along with passport,
Is this possible and how can i do
Thanks
Pass the express-session store into connect-redis to create a RedisStore constructor.
var session = require('express-session');
var RedisStore = require('connect-redis')(session);
app.use(session({
store: new RedisStore(options),
secret: 'keyboard cat'
}));
for reference
https://www.npmjs.com/package/connect-redis