How can I use session variables across whole app - node.js

I'd like to access session variables assigned just after login further in mysql queries on different path. However when I do that what I receive is "undefined" value. Here's my login script.
users.post('/login', (req, res) => {
User.findOne({
where: {
email: req.body.email
}
})
.then(user => {
if (user) {
if (bcrypt.compareSync(req.body.password, user.password)) {
let token = jwt.sign(user.dataValues, process.env.SECRET_KEY, {
expiresIn: 1440
})
req.session.Osoba=user.Osoba
res.send(token)
}
} else {
res.status(400).json({ error: 'Taki użytkownik nie istnieje' })
}
})
.catch(err => {
res.status(400).json({ error: err })
})
})
Here's session middleware (it's actually at the beggining of the main node file, just after requiring all packages and before any routes):
app.use(session({
secret: 'secret',
resave: false,
saveUninitialized: true,
cookie: { secure: true }
}))
Here's the line which gives me undefined.
app.get('/wypozyczanie', async (req, res) => {
if (req.session) {console.log(req.session.Osoba)}
})

Try your session middleware as bellow.
app.use(session({
key: 'sess_key',
secret: 'secret',
saveUninitialized: true,
resave: true,
rolling: true,
cookie: {
expires: 3600000, //1 hour. Sewt as you want
secure: false
}
}));
Make sure req.session.Osoba is assigned before you are using it.

Related

express-session cookie still exist despite logout

I have this logout route with expressJS using express-session :
router.post('/logout', (req, res) => {
req.session.user = null;
req.session.destroy((err) => {
if (err) {
return res.status(400).end();
} else {
return res.status(200).end();
}
});
});
Although the user is logged out Correctly and the sid changes, The cookie still exists!! which freaking me out.
I want to completely remove the cookie to calm my heart.
This is the config of the express-session package
app.use(
session({
store: new MariaDBStore({
pool: require('./config/db_pool')
}),
name: 'sid',
secret: process.env.KEY,
saveUninitialized: false,
resave: false,
cookie: {
path: '/',
httpOnly: true,
secure: process.env.NODE_ENV === 'development' ? false : true
}
})
);
I git the answer from #Joe comment above and this like
Answer from here
using this close completely removes the cookie.
the options of res.clearCookie are not optional .
res.clearCookie('sid', { path: '/' });

isAuthenticated passport not working (always FALSE)

This is a project with stack MEAN.
I use passport for authentication, but it doesn't work well.
After logging in, reloading the page, access is immediately requested, not recognizing that the user is authenticated.
This is my code (service, model js, component angular, app.js)
// app.component.ts
constructor(private _modalService: NgbModal, private _user:UserService, private _router:Router) {
this._user.userLogged().subscribe(
data => console.log(data),
error => this._router.navigate(['/login'])
)
}
// user.service.ts
login(body:any) {
return this._http.post('http://127.0.0.1:3000/users/login', body, {
observe: 'body',
withCredentials: true,
headers: new HttpHeaders().append('Content-type', 'application/json')
});
}
userLogged() {
return this._http.get('http://127.0.0.1:3000/users/user-logged', {
observe: 'body',
withCredentials: true,
headers: new HttpHeaders().append('Content-type', 'application/json')
});
}
// users.js
router.post('/login', function (req, res, next) {
passport.authenticate('local',function (err, user, info) {
if (err) return res.status(501).json(err);
if (!user) return res.status(501).json(info);
req.logIn(user, function (err) {
if (err) return res.status(501).json(err);
return res.status(200).json({message: "login ok"});
});
})(req, res, next);
});
router.get('/user-logged', isValidUser, function (req,res,next) {
return res.status(200).json(req.user);
});
function isValidUser(req,res,next) {
if (req.isAuthenticated()) return next();
return res.status(401).json({message: 'Non autorizzato'});
}
// app.js
var passport = require('passport');
var session = require('express-session');
const MongoStore = require('connect-mongo');
app.use(session({
name: 'myname.sid',
resave: false,
saveUninitialized: false,
secret: 'secret',
cookie: {
maxAge: 36000000,
httpOnly: false,
secure: false,
},
store: MongoStore.create({mongoUrl: 'mongodb://localhost/iHospital'})
}));
require('./passport-config');
app.use(passport.initialize());
app.use(passport.session());

How to send express-session to client not in same url?

Can I please get some help, I have been searching all over the internet for this and I cannot seem to find the answer that I am looking for.
So I would love to implement expression-session and mongoDB as the store, so session creation I managed to get that done and also saving the session within the store i.e MongoDB managed to get that done.
The problem now comes to when I have to send the session cookie to the client, so I have my server(NodeJS) running on port 5000 and I have the client(ReactJS) running on port 3000, so now how can I send that cookie to the client and flag it as httpOnly cookie?
This is how I tried to setup express-session
mongoose
.connect(MongoURI, {
useNewUrlParser: true,
useCreateIndex: true
})
.then(() => console.log("MongoDB connected..."))
.catch((err) => console.log(err));
const mongoDBstore = new MongoDBStore({
uri: MongoURI,
collection: "mySessions"
});
app.use(express.urlencoded({ extended: false }));
app.use(express.json());
app.use(
session({
name: COOKIE_NAME,
secret: 'SESS_SECRET',
resave: true,
saveUninitialized: false,
store: mongoDBstore,
cookie: {
maxAge: 1000 * 60 * 60 * 3,
sameSite: false,
secure: false
}
})
);
This is where I wanted to send the cookie once user logs in
router.post("/login", (req, res) => {
const { email, password } = req.body;
if (!email || !password) {
return res.status(400).json({ msg: "Please enter all fields" });
}
User.findOne({ email }).then((user) => {
if (!user) return res.status(400).json({ msg: "User does not exist" });
bcrypt.compare(password, user.password).then((isMatch) => {
if (!isMatch) return res.status(400).json({ msg: "Invalid credentials" });
const sessUser = { id: user.id, name: user.name, email: user.email };
req.session.user = sessUser;
res.json({ msg: " Logged In Successfully", sessUser });
});
});
});

Session not saving after login

I have a problem with express-session. When I try to login I have to save my userdata in cookies and after redirect get it on home page. Now after redirect my cookie is clearing and I have default cookie without some data
const authRoute = require('./routes/auth')
mongoose.connect(
process.env.DB_CONNECT,
{ useUnifiedTopology: true, useNewUrlParser: true },
() => {
console.log('Connected to DB')
});
//Middleware
app.use(express.json())
app.use(cors())
app.use(session({
name: 'sid',
resave: false,
saveUninitialized: false,
store: new MongoStore({ mongooseConnection: mongoose.connection }),
secret: process.env.SESS_SECRET,
cookie: {
maxAge: 1000 * 60 * 60 * 2,
sameSite: true,
secure: false
}
}))
app.use('/api/user', authRoute)
Routes file
router.get('/login', (req, res) => {
console.log(req.session);
if (req.session.user) {
res.status(200).send(req.session.user)
} else res.status(403).send({ error: 'You need to login first' })
})
router.post('/login', async (req, res) => {
...
req.session.user = { id: user._id, username: user.name, email: user.email }
req.session.save()
//CREATE AND ASSIGN TOKER
const token = jsw.sign({ _id: user._id }, process.env.TOKEN_SECRET)
res.header('auth-toker', token).send(user)
})
Try disabling the Windows Defender or other anti virus software. Those may not allow the connection to go through

Session data are lost using express session

I'm working in devMode with angularjs and express-session with cors middleware and I run frontend from localhost:4200 and backend from localhost:8080
In login request I set user data in session and then when I call "/api/contacts", the session user data is undefined.
I tried to save session with session.save() but it does not work.
I noticed that between calls sessionID changes.
I searched for hours on google but I have not found any solution.
this is the frontend call to "/api/contacts"
this.http.get(environment.apiUrl + '/api/contacts', {
withCredentials: true,
})
this is part of server.js
app.use(cors({origin: [
"http://localhost:4200"
], credentials: true,
}));
let sess = session({
secret: 'my secret',
resave: false,
saveUninitialized: false,
store: new MemoryStore({
checkPeriod: 60000 * 5 // prune expired entries every 24h
}),
cookie: {
secure: app.get('env') === 'production'?true:false,
maxAge: 60000 * 5 ,
}
})
app.use(sess)
// Initialize the app.
var server = app.listen(process.env.PORT || 8080, function () {
});
const authMiddleware = (req, res, next) => {
// here req.session.user IS undefined
if(req.session && req.session.user) {
next();
} else {
res.status(403).send({
status: 403,
errorMessage: 'You must be logged in.'
});
}
};
app.get("/api/contacts", authMiddleware,(req, res) => {
// some code will run if authMiddleware pass
});
app.post('/api/login', validatePayloadMiddleware, (req, res) => {
if (req.body.username === "xx.xxxx#xxxx.xxx" && req.body.password === "xxxxxxx")
{
let user = {
id: req.sessionID,
username: req.body.username,
firstName: "Fabio",
lastName: "Spadaro",
};
req.session.user = user;
req.session.save((err) => {
console.log(err)
});
return res.status(200).json(user);
}
else
{
let body = {
error: true,
errorMessage: 'Permission denied!'
};
return res.status(403).json(body);
}
});

Resources