Our site have two section :
1. admin (content management)
2. site
Admin section will have url '/admin' and site section have url '/'.
Example : My site name is www.example.com, then admin section url is "www.example.com/admin" and site url is "www.example.com".
I want to create url based session means request from admin section will have different session than request from site section.
How can i do it?
Assuming you're using express, you can separate your routers for your routes and apply the session middleware to each router.
routes/index.js
var express = require('express'),
router = express.Router(),
session = require('express-session');
router.use(session({
secret: 'index route secret',
resave: false,
saveUninitialized: true
}));
module.exports = router;
routes/admin.js
var express = require('express'),
router = express.Router(),
session = require('express-session');
router.use(session({
secret: 'admin route secret',
resave: false,
saveUninitialized: true
}));
module.exports = router;
app.js
var express = require('express'),
app = express();
app.use('/', require('./routes/index'));
app.use('/admin', require('./routes/admin'));
app.listen(3000);
documentation
Related
I am build a small application with node.js and express. In this application there are 2 routes on the backend, one for the users and one for the bugs that users can add.
My goal is to save the user on the session with sessionExpress and then retrieve it when whenever a bug is added to the system.
My code:
app.get('/api/login',(req,res)=>{
const user = req.body
userService.checkLogin(user)
.then(user=>{
req.session.user = user
res.send(user)
}).catch(err=>res.end(err))
})
here I'm saving the user to the session.
app.post('/api/bug/', (req, res) => {
const bug = req.body
console.log(req.session.user)
bugService.add(bug)
.then(bug => res.json(bug))
})
On a different route, I'm trying to get the user back but req.session.user return undefined!
Any help would be much appreciated!
If any more code is needed please let me know
const express = require('express');
const bodyParser = require('body-parser')
const session = require('express-session')
const cookieParser = require('cookie-parser')
var app = express()
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({ extended: false }))
app.use(express.static("public"));
app.use(session({
secret: 'secret',
resave: false,
saveUninitialized: true,
cookie: { secure: false,maxAge:null }
}))
app.use(cookieParser());
If you are running it from http, can you do trust proxy: 1 and set secure to true. Otherwise cookie-parser will not recognise the cookies.
And from the front-end make sure you are making requests withCredentials.
You are registering the middleware in the wrong order. cookie parser should come before the session since express session uses cookies to save the session.
Note that you application router should come AFTER both of them
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.
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
}
}));
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 using npm subdomain, inside my app I have routes that fake a subdomain
// looks like app.localhost:3000
router.get('/subdomain/app', app.dashboard);
So I have a login page on a subdomain and a login page on a non subdomain page. They don't share sessions, so I have to login twice. I want to setup redis, but I don't know how.
// here is my session middleware, I tried using .localhost
app.use(session({ secret: 'something', domain: '.localhost', }));
I have seen where people are using redis like
app.use(express.session({
store:new RedisStore({
host: config.redis.session.host,
port: config.redis.session.port,
db: config.redis.session.db
}),
secret: config.session_secret
}));
This seems like it could solve my issue but I have no clue how to setup a redisStore and where the config data comes from?
Can someone explain to me how to use redis so that when a user logs in on either app.example.io or example.io that he/she is logged in for good, no need to log in twice?
You need to require following modules.
connect-redis
express-session
cookie-parser
Then use the following sample code:
var express = require('express');
var cookieParser = require('cookie-parser');
var session = require('express-session');
var RedisStore = require('connect-redis')(session);
var app = express();
app.use(cookieParser());
app.use(session({
secret: "thisismysecretkey",
store: new RedisStore({ host: 'localhost', port: 6379})
}));
app.get('/', function (req, res) {
res.send('Hello World!')
})
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)
})
Source : How to save and retrieve session from Redis
Here is how I did it, this is the most important piece - domain: .yourdomain.io Make sure to have that preceeding dot before your domain.
var express = require('express'),
app = express(),
cookieParser = require('cookie-parser'),
bodyParser = require('body-parser'),
expressSession = require('express-session'),
sessionMiddleware = null,
redis = require('redis'),
conn_redis = {
path: '/var/run/redis/redis.sock',
socket_keepalive: true
}
app.use(cookieParser())
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({
extended: true
}))
const connectRedis = require('connect-redis')(expressSession),
uid = require('uid-safe').sync
sessionMiddleware = expressSession({
store: new connectRedis(conn_redis),
secret: 'xxxxxxxxxxxxxxxxxxxxx',
name: 'session_name',
resave: false,
rolling: true,
saveUninitialized: false,
logErrors: true,
cookie: {
path: '/',
domain: '.yourdomain.io'
expires: new Date(Date.now() + 3600000),
maxAge: 3600000
}
})