I'm not sure what I did wrong Last project before this was fine, session is saving / persisting
Stack: MEAN Node version: v14.15.0 Express version: v4.17.1 Express session version: v1.17.2
app.ts
// ...
_session: typeof expressSession = require('express-session')
/* Session Store */; this.session_store = new MongoStore({ mongoUrl: this.dbURL });
this.session = this._session({
secret: this.keys,
store: this.session_store,
saveUninitialized: false,
resave: true,
cookie: {
path: '/',
httpOnly: true,
secure: false,
maxAge: 1 * 12 * 60 * 60 * 1000 // 12 hours
},
rolling: true
})
// ...
/* Config */; require('./config.ts');
config.ts
// ...
/* Session Middleware */; app.use((request, response, next) => APP.session(request, response, next));
// ...
login.ts
app.post("/api/login", async (request, response) => {
let body = request.body,
username: string = body.username,
password: string = body.password,
db_account = APP.db.collection("accounts");
if ((!username || !password)) {
if (!request.session["_register"]) return response.sendStatus(411)
username = request.session["_register"].username
password = request.session["_register"].password
// request.session["_register"] = undefined
}
// validator check
if (!validator.isAlphanumeric(username) && !validator.isEmail(username)) return response.status(400).send("username")
// find DB, either username or email
const docs = await db_account.find({ $or: [{ username: username }, { email: username }] }).toArray()
// Not found
if (!docs.length) return response.status(404).json({ error: "username" })
let account: Account = docs[0] as any
if (password != account.password) return response.status(401).json({ error: "password" })
request.session["auth"] = username
console.log(request.session["auth"]) // username attribute exist at this point
return response.status(200).json({ error: null })
})
app.post('/api/auth', async (request, response) => {
console.log(request.session["auth"]); // undefined
request.session["auth"]
? response.send({ auth: true })
: response.send({ auth: false })
})
Front end side login.component.ts
async login() {
if (this.password.invalid || this.username.invalid) return;
let res: any = await lastValueFrom(this.http.post(server_host() + "/api/login", {
username: this.username.value,
password: md5(this.password),
}))
.catch(err => {
if (err)
return alert("Something went wrong. Please refresh the page and try again.")
})
if (res && !res.error) {
localStorage.setItem("auth", "true")
return this.router.navigate([''])
}
return alert("Something went wrong. Please refresh the page and try again.")
}
Front end middleware app.component.ts
async auth(): Promise<boolean> {
if (!localStorage.getItem('auth')) return false
var res = await lastValueFrom(this.http.post(server_host() + "/api/auth", {}, { withCredentials: true })) as any;
if (!res.auth) { localStorage.removeItem("auth"); return false }
return true
}
// ...
if (ev instanceof NavigationStart) {
//Middleware
this.loading = true;
await this.auth();
}
// ...
On previous project, following more or less same template / work logic, it works as intended (session persisting / saving) Where did I go wrong?
EDIT: found a way to see all active session View all currently active sessions in express.js
so I tried to do this
app.post('/api/auth', async (request, response) => {
(request as any).sessionStore.all((err: Error, sessions: any) => {
console.log(sessions);
})
console.log(request.session["auth"]); // still undefined
request.session["auth"]
? response.send({ auth: true })
: response.send({ auth: false })
})
I got this output:
undefined // from console.log(request.session["auth"]);
[
{
cookie: {
originalMaxAge: 43200000,
expires: '2022-03-21T18:14:12.367Z',
secure: false,
httpOnly: true,
path: '/'
},
auth: 'person'
},
{
cookie: {
originalMaxAge: 43200000,
expires: '2022-03-21T18:16:04.345Z',
secure: false,
httpOnly: true,
path: '/'
},
auth: 'person'
},
{
cookie: {
originalMaxAge: null,
expires: null,
secure: false,
httpOnly: true,
path: '/'
},
auth: 'person1'
},
// the list goes on...
]
meaning the session IS SAVED but received request is using different session / cookie? I'm not sure what's wrong here, I'm using Angular (MEAN stack)