I'm currently working on my sessions for my app. Whenever i use the link
TAKE NOTE OF MY LINKS
as you can see on my localhost:3000/login after logging in my cookies and sessions are being set successfully.
This are my cookies after logging in successfully.
HOWEVER, when i wanted to access my app on the built server and after logging in.
My sessions are not able to persists on the cookies tab.
This is my code on setting the session for users
app.use(
cors({
// Change the origin to
// 192.168.254.100
//DEPENDS ON YOUR LOCAL NETWORK OR
// localhost
//origin: ["http://localhost:3000"],
origin: ["http://192.168.254.100:3000"],
methods: ["GET", "POST", "PUT", "DELETE"],
credentials: true,
optionSuccessStatus: 200,
})
);
app.use(
session({
key: "userId",
secret: "subscribe",
resave: false,
saveUninitialized: false,
cookie: {
maxAge: 24 * 60 * 60 * 1000,
},
})
);
this is my routes on setting the session:
app.get("/login", (req, res) => {
if (req.session.user) {
res.send({ loggedIn: true, user: req.session.user });
} else {
res.send({ loggedIn: false });
}
});
Related
i try to create an app using react and nodejs
i'm using express-session and express-mysql-session to store sessions,
It's store session on mysql but note stored on browser cookies. knowing that the response cookies including the session that created from server, knowing also that work just fine on development, but after deploy the application on render i found this problem.
server.js :
const express = require("express");
const app = express();
const cors = require("cors");
const config = require("./config/config");
const mode = process.env.NODE_ENV;
app.use(express.json());
const session = require("express-session");
const sqlSessionStor = require("express-mysql-session")(session);
const dbInfo = config[mode];
const options = {
...dbInfo,
schema: {
tableName: "sessions",
columnNames: {
session_id: "session_id",
expires: "expires",
data: "data",
},
},
};
const sessionStor = new sqlSessionStor(options);
app.use(
session({
name: "auth",
key: "auth",
resave: false,
saveUninitialized: false,
secret: "strongSecretKey",
store: sessionStor,
cookie: {
maxAge: 1000 * 60 * 60 * 24,
},
}),
);
const clientUrl = process.env.CLIENT_URL;
app.use(
cors({
origin: clientUrl,
credentials: true,
}),
);
on login.js file:
exports.login = (req, res) => {
authModel
.login(req.body)
.then((result) => {
req.session.isUser = result.user;
res.send(result);
})
.catch((err) => {
res.send(err);
});
};
on client (react):
async function login() {
const options = {
headers: { "Content-Type": "application/json" },
withCredentials: true,
};
const req = await axios.post(`${VITE_API_KEY}/login`, userInfo, options);
const user = await req.data;
if (user.login) {
//
} else {
//
}
}
response cookies:
screenshot
cookies:
screenshot
this is some solutions that not helpful to me:
i insert httpOnly to true and secure: true and the server does not send any response cookies, that way i'm not inserting this potions on code above.
i try to use sameSite with all values
Here is some sample code that outlines my issue. I'm trying to get express-session / connect-session-sequelize to work for a website with login functionalities.
However, when I try to call my POST request, I get the following error:
I can only assume it's trying to store session data onto my database, but cannot find a table. I can bypass this by going in and creating the table manually with all the columns it wants, but I'm wondering if there's an issue in my code preventing the package from working properly (or if this is how it's supposed to work.)
require('dotenv').config({ path: './config/.env' })
const express = require('express')
const session = require('express-session')
const mysql = require('mysql2')
const Sequelize = require('sequelize')
const path = require('path')
const SequelizeStore = require('connect-session-sequelize')(session.Store)
const app = express()
const PORT = 9999
app.use(express.json())
app.use(express.static(path.join(__dirname, 'public')))
// Allowing connection to database in Workbench
const db = new Sequelize('somedatabase', 'root', process.env.PASSWORD, {
host: 'localhost',
dialect: 'mysql'
})
db.authenticate()
.then(() => {
console.log('Connected...')
}).catch(error => {
console.log('Failed to connect...', error)
})
// Setting up session
app.use(session({
secret: 'shhh',
store: new SequelizeStore({
db: db
}),
resave: false,
saveUninitialized: true,
cookie: {
maxAge: 1000000
}
}))
// Sample model
const User = db.define('user', {
id: {
type: Sequelize.INTEGER,
primaryKey: true,
autoIncrement: true
},
username: Sequelize.STRING,
password: Sequelize.STRING
})
// Sample request
app.post('/api/create', async (req, res) => {
const newUser = {
username: john,
password: verysecurepassword
}
await User.create(newUser)
})
app.listen(PORT, () => {
console.log(`Listening on localhost:${PORT}...`)
})
In this code, you are using several packages: express-session, which manages the session itself but delegates how the session is saved to connect-session-sequelize.
So the problem is that connect-session-sequelize is trying to save session data in the database, but it cannot because there is no table for sessions.
As written in the documentation of this package (https://www.npmjs.com/package/connect-session-sequelize):
If you want SequelizeStore to create/sync the database table for you, you can call sync() against an instance of SequelizeStore along with options if needed.
So try creating the store, attaching it to the session manager, and then
initializing it (I did not test this code):
// Setting up session
var myStore = new SequelizeStore({
db: db
});
app.use(
session({
secret: "shhh",
store: myStore,
resave: false,
saveUninitialized: true,
cookie: {
maxAge: 1000000
}
})
);
myStore.sync();
I've tried many ways but I still get undefined when I log my sessions
Get "undefined" for req.session in nodejs
Session in nodejs
app.use(session({
secret: 'mYsEcReTkEy',
resave: true,
saveUninitialized: true,
cookie: { secure: false }
}));
app.use('/users/data' , getUserData);
app.get('/order/new' , addOrderPage)
addOrderPage: (req, res) => {
console.log('ll', req.session.userData);},
getUserData: (req, res) => {
let userData = req.query.userData;
req.session.userData = userData;
console.log('ll55', req.session.userData);
}
in my log i got the first one ehere I set my session but the next I got undefined
I am trying to customize the registration page with Stormpath and I can't figure out why the configuration options are not working. The enableXXX and requireXXX work, but none of the info inside web:{...} is showing up. I've tried reordering the options, but that doesn't work either.
Specifically, I want to:
-- Register users at /signup instead of /register. Right now only /register is working.
-- I want to redirect them to another site after registration. I randomly put google.com in there, but I'm still redirected to "/" after registration is complete.
-- I want to reorder the registration fields. I want email to be the first field, but username is currently first.
Here's app.js:
// Import required modules.
var express = require('express');
var stormpath = require('express-stormpath');
var path = require('path');
var engine = require('ejs-mate');
var app = express();
// use ejs-locals for all ejs templates:
app.engine('ejs', engine);
// Configure public views
app.set('views','./views');
app.use(stormpath.init(app, {
apiKeyFile: process.env[(process.platform == 'win32') ? 'USERPROFILE' : 'HOME'] + ~removed
secretKey: '~removed',
application: '~removed',
enableRegistration: true,
enableGivenName: false,
requireGivenName: false,
enableSurname: false,
requireSurname: false,
website: true,
api: true,
web: {
register: {
uri: '/signup', // Use a different URL
nextUri: 'http://google.com', // Where to send the user to, if auto login is enabled
fields: {
passwordConfirm: {
enabled: true,
required: true
}
},
fieldOrder: [ "email", "username", "password", "passwordConfirm" ],
}
},
enableUsername: true,
requireUsername: true,
enableConfirmPassword: true,
requireConfirmPassword: true
}
));
app.get('/', function(req, res) {
res.render('home.ejs', {
title: 'Welcome'
});
});
app.get('/', function(req, res) {
res.send('home page!');
});
app.listen(process.env.PORT || 3000);
Other possibly relevant info:
-- The site is hosted on Heroku, but I'm not using the Stormpath add-on because I couldn't get it to work.
-- I'm on a Mac.
I've been stuck on this for days and I haven't been able to figure out what I'm doing wrong. Any help would be much appreciated.
The issue is likely this: we released a new version of this library recently which has new configuration options, and it appears you are using our OLD docs as a reference.
Here's what you'll want to do:
Update to the latest express-stormpath release. Then use the code below: (I converted your example to work with the latest release):
app.use(stormpath.init(app, {
client: {
apiKey: {
file: process.env[(process.platform == 'win32') ? 'USERPROFILE' : 'HOME'] + '~removed'
}
},
application: {
href: '~removed',
},
web: {
register: {
enabled: true,
uri: '/signup',
nextUri: 'http://google.com', // don't send them here =)
fields: {
username: {
enabled: true,
required: true
},
givenName: {
enabled: false,
required: false
},
surname: {
enabled: false,
required: false
},
passwordConfirm: {
enabled: true,
required: true
}
},
fieldOrder: ['username', 'email', 'password', 'passwordConfirm']
}
},
website: true,
api: true
}));
I'm trying to develop a facebook connect with node and passport. But I'm having this error in my browser console:
Refused to display 'https://www.facebook.com/dialog/oauth?response_type=code&redirect_uri=http%…te_event%2Cuser_birthday%2Cemail&client_id=632348833449996&type=web_server' in a frame because it set 'X-Frame-Options' to 'DENY'. about:blank:1
This is part of the code:
passport.use(new FacebookStrategy({
clientID: "XXX",
clientSecret: "XXX",
callbackURL: "`http://localhost:3000/auth/facebook/callback`"
},
function(accessToken, refreshToken, profile, done) {
var fullname = profile._json.first_name + ' ' + profile._json.last_name;
// Web services all for user persistence
}
));
// configure Express
app.configure(function() {
app.use(express.logger());
app.use(express.cookieParser());
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(express.session({ secret: 'keyboard cat' }));
// Initialize Passport! Also use passport.session() middleware, to support
// persistent login sessions (recommended).
app.use(passport.initialize());
app.use(passport.session());
app.use(app.router);
});
app.all('/auth/facebook', passport.authenticate('facebook', { scope: ['read_stream', 'publish_actions','user_interests','read_friendlists','create_event','user_birthday','email' ]}));
app.all('/auth/facebook/callback', passport.authenticate('facebook',{ successRedirect: '/',failureRedirect: '/login' }));
app.listen(3000);
On my facebook app configuration I've set the App On Facebook configuration with the following URL: http://localhost:3000/auth/facebook/
What I'm doing wrong?