-1

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)

1 Answers1

0

"received request is using different session / cookie?"

To my understanding, I see that it creates a new cookie/session each time it logins, in other words, it creates a login token that lasts for 12h EACH time when you login, should probably fix that, as it seems that it doesn't overwrite the old ones, or at least replace them.

  • hi! thx for your reply! i dont get what to fix as i dont know why it creates a new cookie / session each time i login. can you please enlighten me on this? – Physimo Mar 21 '22 at 14:10
  • Well at 'app.ts' you literally create a new session each time a login is made/successful. You need to use a method to check IF an session already exists for that user and if it does then retrieve it instead of initializing a new one. – Masked Hentai Man Mar 21 '22 at 14:39
  • which part of app.ts are you talking about? do you mean the login.ts or...? – Physimo Mar 21 '22 at 14:50
  • Avoiding the obv. are we? I clearly I mentioned the 'app.ts', which is the first thing in your post. – Masked Hentai Man Mar 21 '22 at 15:03
  • can you highlight which part of the code you're talking about? – Physimo Mar 21 '22 at 15:16
  • **/* Session Store */; this.session_store = new MongoStore({ mongoUrl: this.dbURL });** and then you **store: this.session_store,**. You are creating a new session for each login/connection and even the cookies, but instead you should be checking and getting the already existing ones. Hence pseudo code: **if(session().Exists()) { */Retrieve the existing session and NOT create cookies/* } else { */Create a new 'empty' session and cookies, then write stuff there when the user logins. (But you're doing this regardless every time in your current code./* }** – Masked Hentai Man Mar 21 '22 at 15:22