Set user info with cookie-session - node.js

I'm using cookie-session to store all my session information.
After my users login, I store his information inside req.session.user like this
req.session.user = _.omit(client.dataValues, [
"password",
"createdAt",
"updatedAt"
]);
Using console.log I can see that everything is setted ok, but when I try to use req.session.user in another route, I get undefined.
My cookie is setted like this
app.use(
cookiesession({
name: "name",
keys: ["key1", "key2"],
maxAge: 24 * 60 * 60 * 1000,
httpOnly: false,
options: {
secure: false,
secret: "secrete",
overwrite: true
}
})
);

Related

Parse server rest password receiving email problem

I'm trying to implement the rest Password in my application so to do that I have added an email adapter to my server, like:
var parseServer = new ParseServer({
...
verifyUserEmails: false,
emailVerifyTokenValidityDuration: 24 * 60 * 60,
preventLoginWithUnverifiedEmail: false,
emailAdapter: !hasSMTPInfo ? undefined : {
module: 'parse-smtp-template',
options: {
port: env.EMAIL_PORT,
host: env.EMAIL_HOST,
user: env.EMAIL_USER,
password: env.EMAIL_PASSWORD,
fromAddress: env.EMAIL_FROMADDRESS,
template: false,
templatePath: env.EMAIL_TEMPLATEPATH
}
},
Rq: I have used the documentation of parse server api email from [documentation][1]
then I have implement the code of flutter part like:
final user = User(null, null, email);
await user.requestPasswordReset().then((value) async {
print(value.statusCode);
AlertUtils.showSuccessDialog('Veuillez vérifier votre boîte de réception')
.then((_) => Get.toNamed('/login'));
}).catchError((err) {
onDone.call();
AlertUtils.showErrorDialog(err.message.toString());
});
my problem is the status of response is 200 so every thing are right but I can't get any emails of restarting pw.
[1]: https://www.npmjs.com/package/parse-smtp-template

BadRequestError: checks.state argument is missing - What changed?

Tabled a development project back in November and picked it back up.
The authorization that was working is not working any longer and gives me the following error.
BadRequestError: checks.state argument is missing
at /base/node_modules/express-openid-connect/middleware/auth.js:121:31
at processTicksAndRejections (internal/process/task_queues.js:95:5)
Originally I was running my server in development over http, but I thought maybe the issue was that my local server was not HTTP, so now I'm accessing it over HTTPs with a self signed certificate, if perhaps that is the issue.
I am using an ngrok proxy to support the callback to my development environment and have
OIDC_RP_URI=https://myproxy.ngrok.io
OIDC_COOKIE_DOMAIN=myproxy.ngrok.io
auth = {
authRequired: true, // validate<boolean>('DISABLE_SSO', Boolean(env.DISABLE_SSO), isBoolean, false),
baseURL: validate<string>('OIDC_RP_URI', env.OIDC_RP_URI, isString),
clientID: validate<string>('OIDC_CLIENT_ID', env.OIDC_CLIENT_ID, isString),
issuerBaseURL: validate<string>('OIDC_OP_URI', env.OIDC_OP_URI, isString),
routes: {
callback: validate<string>('OIDC_REDIRECT_PATH', env.OIDC_REDIRECT_PATH, isString),
logout: '/logout',
postLogoutRedirect: 'https://xx/Logout'
},
secret: validate<string>('EXPRESS_SESSION_SECRET', env.EXPRESS_SESSION_SECRET, isString),
session: {
cookie: {
domain: validate<string>('OIDC_COOKIE_DOMAIN', env.OIDC_COOKIE_DOMAIN, isString),
httpOnly: true,
path: '/',
sameSite: 'None' as const, // 'Lax' as const,
secure: true
},
absoluteDuration: 60 * 60 * 8,
rollingDuration: 60 * 60
}

Not being able to remove cookies on nextjs in production

I am creating an application in NextJs and I set the cookie authorization when the user make login:
res.setHeader("Set-Cookie", [
cookie.serialize("authorization", `Bearer ${jwtGenerated}`, {
httpOnly: true,
secure: process.env.NODE_ENV !== "development",
sameSite: true,
maxAge: 60 * 60 * 12,
path: "/",
})
]);
This part of the code works perfectly, it sets the cookie in the browser. However when I log out, I make a request to the url /api/logout that executes this code:
import cookie from "cookie";
export default (req, res) => {
res.setHeader("Set-Cookie", [
cookie.serialize("authorization", "false", {
httpOnly: true,
secure: process.env.NODE_ENV !== "development",
sameSite: true,
maxAge: 5,
path: "/",
})
]);
return res.status(200).json({ roles: null, auth: false });
};
however it seems that it does not work in production. When I'm at localhost it removes cookies and changes their value. However in production nothing is changed. The expiration remains the same, value and everything else.
Am I doing something wrong? Is there any other way to remove this cookie when the user make logout?
Are you using Vercel as the deployment platform? This bug is caused because Next.js's serverless features always return a 304 Not Modified. Quite frankly I don't know why this happens on the server, but I believe that it has something to do with HTTP requests on Next.js's internals.
In order to fix this problem, I made the logout request a POST request with a static key. This will prevent 304 Not Modified error from happening.
import cookie from "cookie";
export default (req, res) => {
if (req.method !== 'POST') return res.status(405).json({ status: 'fail', message: 'Method not allowed here!' });
if (req.body.key === 'static_key') {
res.setHeader("Set-Cookie", [
cookie.serialize("authorization", "false", {
httpOnly: true,
secure: process.env.NODE_ENV !== "development",
sameSite: true,
maxAge: 5,
path: "/",
})
]);
return res.status(200).json({ roles: null, auth: false });
}
return res.status(400).json({ status: 'fail', message: 'Bad request happened!' });
};

sails.js session data not saved into db

I might be doing something wrong. Please guide me in right direction.
I am trying to implement sails session feature with 'connect-mongo'. I did the implementation same as explained in the docs Sails session mongo. After successful authentication I am trying to save session data into mongoDb. But in my case it is not saved in mongo collection and collection always remains empty.
My configurations in session.js
url: 'mongodb+srv://username:password#cluster0-tkjwp.mongodb.net/mydbname?retryWrites=true',
collection: 'sessions',
auto_reconnect: false,
ssl: false,
stringify: true,
cookie: {
secure: false,
maxAge: 24 * 60 * 60 * 1000
}
and how I am trying to save.
if(user.length && user[0].id){
// save in DB
req.session.authenticated = true;
req.session.authinfo = user[0];
req.session.save(function(err) {
console.log(req.session);
return res.json({
status: 1,
msg: 'Successfull.'
});
})
}else{
return res.send({
status: 0,
msg: 'Invalid'
});
}
Also I am not getting any error
Its working now. Only thing I missed the adapter option. But now I am using it with mysql. Below I posting my working code with MySql.
In session.js
adapter: 'express-mysql-session',
host: 'localhost',
port: 3306,
user: 'root',
password: 'xxxxxxxxx',
database: 'xyz',
ssl: false,
stringify: true,
cookie: {
maxAge: 24 * 60 * 60 * 1000
},

If no express-cookie timeout is set, is there a defaulted timeout as a preset?

With express session, if you do not specify a max timeout example:
cookie: { maxAge: new Date(Date.now() + (60 * 1000 * 30)) })
is there a default time that is preset?
It's right there in the docs, man:
"Settings object for the session ID cookie. The default value is { path: '/', httpOnly: true, secure: false, maxAge: null }."

Resources