hello, I have problem with authenticating user with session.Session id is reseted after every reload of page and req.session.username is undefined. I am using react frontend on one IP and node on another one. Tried almost everything from other posts about this issue, but cant set it right. could you please help me? Thank youconst express = require("express"); const app = express(); const bodyParser = require("body-parser"); const MongoClient = require("mongodb").MongoClient; const bcrypt = require("bcrypt"); const session = require("express-session"); const MongoStore = require("connect-mongo")(session); app.use( session({ cookieName: "session", secret: "XXXXX?.XXXXXX?EOXXXX", duration: 24 * 60 * 60 * 1000, activeDuration: 1000 * 60 * 5, saveUninitialized: true, resave: true, cookie: { path: "/", maxAge: 60000, httpOnly: false, secure: false }, store: new MongoStore({ url: "mongodb://admin:xxxxx@xxxxxx.mlab.com:xxxx/DBNAME" }) }) ); app.use((req, res, next) => {req.username = req.session.username; next()}) app.use(bodyParser.urlencoded({ extended: false })); app.use(bodyParser.json()); 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(); }); MongoClient.connect( "mongodb://admin:xxxxx@xxxxxx.mlab.com:xxxx/DBNAME", (err, client) => { if (err) return console.log(err); db = client.db("DBNAME"); app.listen(8000, () => { console.log("listening on 8000"); }); } ); app.get("/test", (req, res) => { res.send({ session: req.session.username }); }); app.post("/login", (req, res, next) => { let username = req.body.content.username; let password = req.body.content.password; db.collection("users") .find() .toArray(function (err, results) { for (let i = 0; i < results.length; i++) { if (results[i].username === username) { bcrypt.compare(password, results[i].password, function (err, res) { if (res) { console.log("login"); req.session.username = username } else { console.log("incorrect"); } }); } } }); });
Submitted September 21, 2018 at 10:21PM by mikebun2
No comments:
Post a Comment